DEV Community

Cover image for HTML to PDF — Java
Erwan Le Tutour
Erwan Le Tutour

Posted on

HTML to PDF — Java

Use Case

At the beginning of the year 2020, my wife wanted to redo her CV, so I offered to give her a small tool where she had only to inform her trainings, her diplomas and her experiences and who would then put them in a document.
At first I wanted to create a document in word format, but I was not satisfied with the rendering, the HTML of the frontend looked better than the final document, that’s when I wondered if there was no way to turn this HTML into PDF.
Which led to the use of html2pdf, my frontend sent me an object corresponding to her CV and I just had to format it and generate the PDF.

HTML2PDF

The Dependency

First imported via your favorite dependency manager (here maven).

What is a PDF?

What is a PDF? It’s a file format, so let’s start from the beginning, create a file (thanks captain obvious).

Fill the File

To do this, nothing is simpler than to use the HtmlConverter class and its convertToPdf method which takes as a parameter :

  • A String : The HTML code as a String

  • An OutputStream : The PDF file.

    In the above example, the html variable is a StringBuilder that is built by browsing the properties of a previously populated object. Warning, tags such as are not taken into account, so how to insert css?

That simple :

  • Use the style property of the HTML tag

    <span style=”font-weight: bold;”>

  • use tags and feed the content between the two by the content of a css file that you will read before

    And then use the class property of the HTML tag to add your style

    html.append("

    ")

    Warning : complex file like the Bootstrap css can produce some errors in the console of your IDE, but nothing to fear, the file will be generated anyway.

    pros and cons

    Pro

    • Easy to use.

    • Well documented.

    • Converting HTML to PDF is a fraction of the possibility of this library.

    Cons

    • Code redundancy if the object in question is already displayed on the frontend side.

    • Complex CSS files can generate console errors.

    • Maintenance difficulty in case of a large file.

Top comments (0)