Creating a PDF file from HTML can be done using iText Java library. iText has an add-on that enables converting HTML to PDF document. This post shows how to use iText to convert HTML to PDF.
“When using iText PDF in a closed source environment, you will need to purchase an iText PDF commercial license.”
pom.xml
com.itextpdf itext7-core 7.1.9 pom com.itextpdf html2pdf 2.1.6
package com.hmkcode; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.html2pdf.HtmlConverter; public class App public static final String HTML = "Hello
" + "This was created using iText
" + "hmkcode.com"; public static void main( String[] args ) throws FileNotFoundException, IOException HtmlConverter.convertToPdf(HTML, new FileOutputStream("string-to-pdf.pdf")); System.out.println( "PDF Created!" ); > >
Output: The code above will create a PDF file string-to-pdf.pdf
index.html
HTML to PDF href="style.css" rel="stylesheet" type="text/css" /> HTML to PDF class="itext">itext 7.1.9 class="description"> converting HTML to PDF class="label">Title iText - Java HTML to PDF URL http://hmkcode.com/itext-html-to-pdf-using-java
package com.hmkcode; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import com.itextpdf.html2pdf.HtmlConverter; public class App public static void main( String[] args ) throws FileNotFoundException, IOException HtmlConverter.convertToPdf(new FileInputStream("index.html"), new FileOutputStream("index-to-pdf.pdf")); System.out.println( "PDF Created!" ); > >
Output: The code above will create a PDF file string-to-index.pdf