HTML Convert to PDF Summary

A recent requirement, HTML convert to PDF, FE is response for the whole process implement.

There are two methods to achieve this task after searching through the web:

  1. Manually write PDF content , jsPDF supports text picture writing and then generate PDF directly, which can be combined with antoTable for easier presentation of tables
  2. Using the html2pdf library, the implementation mechanism DOM => IMAGE => PDF

The first method:

pdf_1

The first method uses a native-like writing style, requiring various properties such as text properties and location to be equivalent to writing a document by hand.

Pros: Documents are more readable, appropriately sized, and controlled

Cons: Layout restrictions, computational height, heavy workload

For our actual situation, we are going to print a specific page, but at the same time add some content that will only be displayed in PDF, in fact, the equivalent of a newly written page dedicated to printing, printing content including chart and some complex typographical content. Base on these two points, the first method is abandoned.

The process of implementing the second method:

  1. We use reactjs, so we've written a new component that loads when we click Print Button, set the PDF to invisible
  1. The html2pdf library is called at the end of the page dom rendering, and the call is similar

    html2pdf().set(option).from(element).save()

image-20210415194613933

Pros:Cons:
The layout is more casual, depending on the layout of the HTML
Support complex graphics such as tablet, chart, etc.,
Browser render,and the progress relies heavily on the computer configuration
Canvas rendering speed limit
File size is limited and cannot be compressed
Text is not optional and readability is limited

Here let's look at the problems and solutions that arise after use:

canvas

There are still two issue to use this scheme:

 

After through this item, It feels like that this PDF is indeed handed over to the back end is more reliable, after all, the front end limit is really a lot.