Exporting HTML to PDF Using html2canvas and jsPDF: A Proper and Simple Approach

Dec 03, 2025 · Programming · 8 views · 7.8

Keywords: html2canvas | jsPDF | PDF export

Abstract: This article details how to combine html2canvas and jsPDF libraries to export HTML content, including data tables and div elements, into high-quality PDF files. By analyzing best practices, it explores the complete workflow from Canvas rendering to PDF generation, covering resolution adjustment, cross-browser compatibility, and solutions to common issues, providing technical guidance for applications like school management software that require document export.

Introduction and Background

In modern web development, exporting HTML content to PDF files is a common requirement, especially in applications such as school management software and reporting systems. Users often need to export complex layouts containing data tables and div tags while preserving original CSS styles. However, direct use of libraries like jsPDF can lead to issues such as broken table alignment and lost styles. Based on community-validated best answers, this article delves into how to use html2canvas to capture HTML elements as Canvas and then convert them to PDF via jsPDF, offering a simple and effective export solution.

Core Technical Principles

html2canvas is a JavaScript library that renders HTML elements into Canvas images, retaining CSS styles and layout. jsPDF is used for generating and manipulating PDF documents. By combining both, target HTML elements can first be converted to image data and then embedded into PDFs, avoiding compatibility issues inherent in direct HTML-to-PDF conversion. Key steps include selecting target elements, configuring html2canvas parameters, processing Canvas data, and using jsPDF to create and save PDFs.

Detailed Implementation Steps

Referring to the best answer, the implementation process can be divided into the following steps. First, define the target element and trigger button in HTML, e.g., <canvas id="canvas" width="480" height="320"></canvas> and <button id="download">Download Pdf</button>. Then, write the export logic in JavaScript.

A core code example is provided below, based on the onrendered callback function of html2canvas:

html2canvas($("#canvas"), {
    onrendered: function(canvas) {
        var imgData = canvas.toDataURL('image/png');
        var doc = new jsPDF('p', 'mm');
        doc.addImage(imgData, 'PNG', 10, 10);
        doc.save('sample-file.pdf');
    }
});

This code first captures the element with ID "canvas", generates a Canvas, and converts it to a PNG-format data URL. Then, it creates a portrait-oriented ('p') jsPDF instance with units set to millimeters ('mm'), adds the image to the PDF at specified coordinates (10, 10), and finally calls the save method to download the PDF file.

Advanced Configuration and Optimization

To enhance export quality, optimizations from other answers can be incorporated. For example, adjust resolution and DPI settings for high-definition needs. A code example is as follows:

html2canvas(document.getElementById("content"), {
    dpi: 300,
    scale: 3,
    onrendered: function(canvas) {
        var img = canvas.toDataURL("image/jpeg", 1);
        var w = document.getElementById("content").offsetWidth;
        var h = document.getElementById("content").offsetHeight;
        var doc = new jsPDF('L', 'px', [w, h]);
        doc.addImage(img, 'JPEG', 0, 0, w, h);
        doc.save('sample-file.pdf');
    }
});

Here, dpi is set to 300 and scale to 3 to improve image quality. Using JPEG format may enhance compatibility in some browsers like Safari. PDF dimensions are dynamically set based on the element's actual width and height, ensuring layout integrity.

Cross-Browser Compatibility Handling

Testing shows that the above approach works well in Chrome, IE11, and Firefox, but may encounter issues in Safari. Solutions include switching to JPEG format, as noted by Andrew in comments. For instance, changing the toDataURL parameter from 'image/png' to 'image/jpeg' can prevent rendering errors in Safari. Developers should adjust format choices based on target user bases and conduct thorough testing.

Common Issues and Solutions

During implementation, problems such as broken table alignment or incomplete CSS styles may arise. Using html2canvas can partially mitigate these, as it renders visual output rather than raw HTML structure. If performance issues occur, consider limiting capture areas or optimizing HTML structure. Additionally, ensure all dependency libraries (e.g., html2canvas and jsPDF) are version-compatible and correctly included as script files.

Conclusion and Application Recommendations

Combining html2canvas and jsPDF offers a reliable method for exporting HTML content to PDF, particularly suited for scenarios like school management software that require preserving complex styles. It is recommended to start with a simple implementation and gradually add advanced configurations such as DPI adjustment and format optimization. Developers should focus on browser compatibility and customize parameters based on actual needs. With guidance from this article, you can efficiently implement high-quality PDF export functionality to enhance user experience.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.