I have a component (Angular 6) which is an aggregation of several components. This produces a long HTML (I am using Bootstrap 4). Now I want to convert this HTML to PDF. I have searched far and wide and found many solutions that work on jsPDF. The requirement is to produce a crisp layout as it appears in the HTML (so that users can select, copy, etc). But the solutions I found either try to add lines of text manually, which is impossible in my scenario; or they convert (rasterize?) the HTML to image format. Also, I want to preserve the formatting and fonts and styling of my HTML.
So far I have tried: this and this.
The quickest way to convert your PDF is to open it in Acrobat. Go to the File menu, navigate down to Export To, and select HTML Web Page. Your PDF will automatically convert and open in your default web browser. For more nuanced options, begin with your PDF open in Acrobat and click on the Export PDF tool on the right.
Best possible solution I could come up with till now.
You would have to install the below packages from npm
html2canvas
jspdf
import * as jsPDF from 'jspdf'; import html2canvas from 'html2canvas'; htmltoPDF() { // parentdiv is the html element which has to be converted to PDF html2canvas(document.querySelector("#parentdiv")).then(canvas => { var pdf = new jsPDF('p', 'pt', [canvas.width, canvas.height]); var imgData = canvas.toDataURL("image/jpeg", 1.0); pdf.addImage(imgData,0,0,canvas.width, canvas.height); pdf.save('converteddoc.pdf'); }); }
UPDATE:
Came up with another solution. I wasn't able to break it down into A4 size pages, but I was able to make a single pdf file.
Packages:
dom-to-image
jspdf
import domtoimage from 'dom-to-image'; import * as jsPDF from 'jspdf'; downloadPDF() { var node = document.getElementById('parentdiv'); var img; var filename; var newImage; domtoimage.toPng(node, { bgcolor: '#fff' }) .then(function(dataUrl) { img = new Image(); img.src = dataUrl; newImage = img.src; img.onload = function(){ var pdfWidth = img.width; var pdfHeight = img.height; // FileSaver.saveAs(dataUrl, 'my-pdfimage.png'); // Save as Image var doc; if(pdfWidth > pdfHeight) { doc = new jsPDF('l', 'px', [pdfWidth , pdfHeight]); } else { doc = new jsPDF('p', 'px', [pdfWidth , pdfHeight]); } var width = doc.internal.pageSize.getWidth(); var height = doc.internal.pageSize.getHeight(); doc.addImage(newImage, 'PNG', 10, 10, width, height); filename = 'mypdf_' + '.pdf'; doc.save(filename); }; }) .catch(function(error) { // Error Handling }); }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With