Generating PDF from HTML using html2canvas and pdfMake in AngularJS

Dec 03, 2025 · Programming · 25 views · 7.8

Keywords: AngularJS | pdfMake | html2canvas | PDF generation

Abstract: This guide explains how to generate PDFs from HTML in AngularJS using html2canvas and pdfMake, covering error resolution, step-by-step implementation, and code examples.

Introduction

This article addresses a common challenge in web development: generating PDF documents from HTML content in AngularJS applications. The user attempted to use pdfMake directly with HTML but encountered an error due to unrecognized document structure.

Error Analysis

The error "Unrecognized document structure" occurs because pdfMake does not natively support HTML content. Instead, it requires structured data or images. The initial approach of passing a Blob with innerHTML is incorrect.

Solution Overview

An effective solution involves using html2canvas to capture the HTML as a canvas, convert it to an image, and then use pdfMake to generate the PDF. This method preserves the visual appearance of the HTML.

Implementation Steps

  1. Include Libraries: Add html2canvas and pdfMake to your project. No AngularJS injection is required; simply include the scripts.
  2. Prepare HTML: Identify the div element to be converted by adding an ID, e.g., <div id="exportthis">.
  3. AngularJS Controller Code: Use html2canvas to capture the div, convert the canvas to a data URL, and define the PDF document.

Code Example

html2canvas(document.getElementById('exportthis'), {
    onrendered: function (canvas) {
        var data = canvas.toDataURL();
        var docDefinition = {
            content: [{
                image: data,
                width: 500,
            }]
        };
        pdfMake.createPdf(docDefinition).download("Score_Details.pdf");
    }
});

Alternative Methods

Other libraries like Kendo UI offer similar functionality. For instance, Kendo's drawDOM method can convert HTML to PDF while preserving CSS styles. However, the html2canvas and pdfMake combination is lightweight and widely supported.

Conclusion

By integrating html2canvas and pdfMake, developers can efficiently generate PDFs from HTML in AngularJS applications. This approach handles complex layouts and is easy to implement.

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.