Converting a html file to pdf file. I have html file,css file and js files are in one folder how can i convert that index.html to create pdf using itext in java. can anyone help me for this issue. is there is any sample project ?
Asked
Active
Viewed 3,970 times
0
-
See this. your question is duplicate http://stackoverflow.com/questions/17825782/how-to-convert-html-to-pdf-using-itext – AJJ Oct 21 '13 at 13:48
-
possible duplicate of [Converting HTML files to PDF](http://stackoverflow.com/questions/633780/converting-html-files-to-pdf) – Autar Sep 17 '15 at 14:19
2 Answers
0
You can use iTextPdf library or flying saucer (which in turns makes use of iText library). I prefer Flying Saucer because it can convert almost all css styles from html to pdf whereas iTextPdf is very limited in css compliant. Here is the static method I used Flying saucer to convert HTML to PDF:
public static void convertHtml2Pdf(String htmlPath, String pdfPath) throws FileNotFoundException, IOException, com.lowagie.text.DocumentException {
final ITextRenderer iTextRenderer = new ITextRenderer();
iTextRenderer.setDocument(htmlPath);
iTextRenderer.layout();
/** The generated pdf will be written to the file. */
final FileOutputStream fileOutputStream =
new FileOutputStream(new File(pdfPath));
/** Creating the pdf */
iTextRenderer.createPDF(fileOutputStream);
fileOutputStream.close();
}

Tony Vu
- 4,251
- 3
- 31
- 38
0
There is a Built-in helper class called HtmlConverter
for this use case. If you have HTML in place, then it is easy to convert it to PDF like this.
Add the following dependencies to your project.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>kernel</artifactId>
<version>7.1.14</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>html2pdf</artifactId>
<version>3.0.3</version>
</dependency>
And then in your code, you can convert the HTML files to PDF like this.
HtmlConverter.convertToPdf(new File("./simple-input.html"),new File("simple-output.pdf"));
If you want to read from HTML string then you could do something like this.
HtmlConverter.convertToPdf("<h1>Hello String Content!</h1>", fileOutputStream);
I have some detail here at my blog on iText HTML to PDF in Java with Examples.

Raja Anbazhagan
- 4,092
- 1
- 44
- 64