Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 7: convert HTML to PDF

Tags:

I'm trying to convert an HTML table to a PDF without success.

I've used jsPDF to do that but the result is really poor and I'm trying to understand why.

Considering I have a tablet, what I want is to have this table printed on A4 pages in landscape mode (using all the pages that are needed). My problem is that the PDF is composed by images (and I prefer text) and that images are in a really low quality.

What I've tryed is this:

const html = document.getElementById('resultTable');
const pdf = new jsPDF('landscape', 'px', 'a4');

pdf.addHTML(html, 0, 0, {
    'width': html.clientWidth,
    'height': html.clientHeight
}, () => { pdf.save('web.pdf'); });

I've already tried to use, as width and height, the size of the pdf page (with pdf.internal.pageSize) without success. And I've already tried to use 'pt' and 'mm' instead of 'px'.

Any ideas?

like image 752
DeooK Avatar asked Feb 11 '19 11:02

DeooK


2 Answers

Use this way stackblitz working example

In yout typescript file

import {jsPDF} from 'jspdf';

@ViewChild('content', {static: false}) content: ElementRef;


public downloadPDF() {
   const doc = new jsPDF();

   const specialElementHandlers = {
      '#editor': function (element, renderer) {
       return true;
       }
   };

   const content = this.content.nativeElement;

   doc.fromHTML(content.innerHTML, 15, 15, {
      width: 190,
     'elementHandlers': specialElementHandlers
   });

   doc.save('test.pdf');
}

In your html file

<div id="content" #content>
    <!-- Put your content here -->
</div>

<button (click)="downloadPDF()">Export To PDF</button>
like image 110
dasunse Avatar answered Oct 01 '22 06:10

dasunse


This is not so trivial task. On the server I tried using wkhtmltopdf but end up looking for a better solution, because with it I can't use all the power of CSS for printing. I think it is the same problem with client-side tools like jsPDF, you will not get an expected and consistent result.

Headless chrome in Google Cloud is my choice right now.

Here is a good overview of available tools and technologies Modern HTML to PDF conversion

UPDATE:

If you need to create a PDF and can't install anything on your server, you can do so by using Headless Chrome and Google Cloud Function.

using-puppeteer-in-google-cloud-functions

puppeteering-in-firebase-google-cloud-functions

UPDATE 2:

And by the way, you always have an option to Print to PDF in browser. However, I'm not sure how it works on Android tablets, Safari for iOS can export to PDF.

like image 33
Vladimir Prudnikov Avatar answered Oct 01 '22 07:10

Vladimir Prudnikov