Connect with us

CSS

How to Convert HTML (CSS) to PDF Using JavaScript?

Spread the love

Converting an HTML page (styled with CSS) into a PDF file is a common requirement for reports, invoices, resumes, and other downloadable documents. JavaScript provides various ways to achieve this, and in this blog, we’ll explore how to do it effectively.

1. Why Convert HTML to PDF?

✅ Generate printable reports and invoices
✅ Allow users to download content in a structured format
✅ Preserve layout and styling from HTML and CSS
✅ Automate document generation in web applications


2. Popular JavaScript Libraries for HTML to PDF Conversion

Several JavaScript libraries can help convert HTML and CSS into a PDF file:

LibraryFeaturesBest For
jsPDFLightweight, supports text, images, and basic HTMLSimple PDF generation
html2canvasConverts HTML elements into imagesScreenshots of web pages
pdf-libAllows direct PDF manipulationAdvanced PDF editing
puppeteerHeadless browser renderingHigh-quality PDFs from full web pages

For most use cases, jsPDF combined with html2canvas is the best approach.


3. Step-by-Step Guide: Convert HTML (CSS) to PDF Using JavaScript

We’ll use jsPDF and html2canvas to capture an HTML element and convert it into a downloadable PDF.

Step 1: Include Required Libraries

Add the jsPDF and html2canvas libraries via CDN in your HTML file:

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>

Alternatively, install via npm:

npm install jspdf html2canvas

Step 2: Create the HTML Content

Prepare the content you want to convert into a PDF.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Convert HTML to PDF</title>
    <style>
        #pdf-content {
            width: 600px;
            padding: 20px;
            border: 1px solid #ddd;
            font-family: Arial, sans-serif;
        }
    </style>
</head>
<body>

    <div id="pdf-content">
        <h2>Invoice</h2>
        <p>Customer Name: John Doe</p>
        <p>Amount: $150.00</p>
    </div>

    <button onclick="generatePDF()">Download PDF</button>

    <script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.5.1/jspdf.umd.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script>
        async function generatePDF() {
            const { jsPDF } = window.jspdf;
            const pdf = new jsPDF();

            const content = document.getElementById("pdf-content");

            // Convert HTML to Canvas
            const canvas = await html2canvas(content);
            const imgData = canvas.toDataURL("image/png");

            // Add Image to PDF
            pdf.addImage(imgData, "PNG", 10, 10, 180, 0);

            // Save the PDF
            pdf.save("document.pdf");
        }
    </script>

</body>
</html>

Step 3: Explanation of Code

  1. Capture HTML Content
    • The html2canvas library takes a screenshot of the HTML element.
  2. Convert Image to PDF
    • The captured image is added to a jsPDF document.
  3. Download PDF File
    • pdf.save("document.pdf") saves the generated PDF to the user’s device.

4. Advanced Features: Enhancing the PDF Output

1. Adjust PDF Page Size

You can create an A4-sized PDF:

const pdf = new jsPDF("p", "mm", "a4");
pdf.addImage(imgData, "PNG", 10, 10, 190, 0);

2. Add Custom Text to PDF

pdf.text("Custom Header", 10, 10);

3. Handle Multi-Page PDFs

If the content is too long:

const imgHeight = (canvas.height * 190) / canvas.width;
if (imgHeight > 297) {
    pdf.addPage();
    pdf.addImage(imgData, "PNG", 10, 10, 190, 0);
}

5. Conclusion

Converting HTML (with CSS) to a PDF file using JavaScript is simple with jsPDF and html2canvas. Whether you’re generating invoices, reports, or printable content, this method ensures your PDFs maintain the structure and styling of your web page.

Key Takeaways:

✅ Use jsPDF for creating PDF files.
✅ Capture HTML using html2canvas.
✅ Adjust PDF formatting for better output.
✅ Implement multi-page support for large content.

By following this approach, you can seamlessly generate and download PDFs from your website.


Spread the love
Click to comment

Leave a Reply

Your email address will not be published. Required fields are marked *