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
- Include Libraries: Add html2canvas and pdfMake to your project. No AngularJS injection is required; simply include the scripts.
- Prepare HTML: Identify the div element to be converted by adding an ID, e.g.,
<div id="exportthis">. - 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.