Justin R Justin R - 1 year ago 115
HTML Question

Convert HTML File to PDF Using Java

I am looking for a way to convert an HTML file to PDF using a Java library that is preferably free. I have done some searching online to look for tools to use, but haven't found a solution that sticks out (I have seen some mention of iText, but it looked like that would have a charge to use it). Is there an existing library that I can utilize to accomplish the conversion of HTML to PDF?

Answer Source


I ended up using Flying-Saucer from the Maven repo: https://mvnrepository.com/artifact/org.xhtmlrenderer/flying-saucer-pdf

It was very simple to get this to work for me, here is a method I created to use this:

public static void generatePDF(String inputHtmlPath, String outputPdfPath)
    try {
        String url = new File(inputHtmlPath).toURI().toURL().toString();
        System.out.println("URL: " + url);

        OutputStream out = new FileOutputStream(outputPdfPath);

        //Flying Saucer part
        ITextRenderer renderer = new ITextRenderer();


    } catch (DocumentException | IOException e) {
        // TODO Auto-generated catch block

And here is the usage:

public static void main(String[] args){
    String inputFile = "C:/Users/jrothst/Desktop/TestHtml.htm";
    String outputFile = "C:/Users/jrothst/Desktop/TestPdf.pdf";

    generatePDF(inputFile, outputFile);


It worked very well to output the PDF and was very simple to use. It also handled the CSS in the html pretty well. Didn't use it for external CSS, but I believe that is possible too.