In the last article we learned about how we can generate pdf from dom elements but there was some bottleneck like that method was only adding one big page and sometime div are cut in half i.e some portion of the div were displaying in the next page. In this article we will gonna learn how we can generate pdf from dom with multiple pages and without cutting.
Dom to pdf
We will gonna use a package name dom-to-pdf in today article. This package basically convert html elements into canvas and svg. After that it converts canvas into the pdf.
This package is more simple and easy to use as compare to last article. In the last article we were using the two different packages one package is converting the dom into an image and then other package was converting the image into the dom. But with dom-to-pdf we can do both the things with single package.
The plus point of this package is it automatically manage the multiple pages format and at the same time it also manage that the content should not be cut while adding into the pdf. In other words no div will gonna be cut in parts while adding to the pdf instead of that it will gonna add whole div to next page which is very useful for most of the cases.
Installation and Usage
We can install this package from npm simply.
npm install --save dom-to-pdf
After the installation import this package one time.
import domToPdf from 'dom-to-pdf';
domToPdf will gonna receive three arguments.
- First argument will be the dom element.
- Second argument will be the option object.
- Third will be a callback function.
const element = document.querySelector('.summary-report-container');
const options = {
filename: "test.pdf",
};
domToPdf(element, options, () => {
// callback function
});
The whole pdf generate function will be gonna look like this.
generatePdf = () => {
const element = document.querySelector('.summary-report-container');
const options = {
filename: "test.pdf",
};
return domToPdf(element, options, () => {
// callback function
});
}
It will gonna save the pdf automatically after generation. This way you can generate the pdf with multiple pages and without cutting the content.
Top comments (0)