Home > database >  How to convert html, css to PDF using Java?
How to convert html, css to PDF using Java?

Time:02-21

I was wondering what are some good tutorials or logic on how to convert HTML and XHTML web pages to PDF using Java?

And also suggest me How can I convert html, bootstrap css to pdf using Java?

CodePudding user response:

There is a library named wkhtmltopdf (https://wkhtmltopdf.org). We used it in our project. wkhtmltopdf command line utility must be installed on a machine. Download page: https://wkhtmltopdf.org/downloads.html Note it also must be installed on servers your app will execute.

Your code should fetch html and css. Css should be added to html header in style tags. I'm not aware of possibility to fetch it as a separate file to html.

Next step is to convert your html to a PDF. This code will produce byte[] containing your PDF.

      String html = "<...> your html";
      Pdf pdf = new Pdf();
      pdf.addPageFromString(html);
      pdf.addParam(new Param("--disable-smart-shrinking"));
      pdf.addParam(new Param("--header-html", headerPath));
      pdf.addParam(new Param("--footer-html", footer.toAbsolutePath().toString()));
      return pdf.getPDF();
  • Related