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?
PDFreactor converts complex HTML and XML content to PDF. The generated PDF documents can be printed or viewed on the web. This way, you can easily and quickly create PDF documents. The software is delivered as a Java library or as a Web Service.
On a Windows computer, open an HTML web page in Internet Explorer, Google Chrome, or Firefox. On a Mac, open an HTML web page in Firefox. Click the “Convert to PDF” button in the Adobe PDF toolbar to start the PDF conversion. Enter a file name and save your new PDF file in a desired location.
Generate PDF using JavaScript The following example shows how to use the jsPDF library to generate PDF file using JavaScript. Specify the content in text() method of jsPDF object. Use the addPage() method to add new page to PDF. Use the save() method to generate and download PDF file.
You have a few options:
UPDATE:
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();
renderer.setDocument(url);
renderer.layout();
renderer.createPDF(out);
out.close();
} catch (DocumentException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
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);
System.out.println("Done!");
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With