HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

HTML to PDF conversion is the most searched topics on google by Java developers. So I am going to explain steps to do it with example of code.

Step 1 : In step one we will render html object like browser render it, so that DOM(Document Object Model) can be clean and fire events like “document ready” and “body onload”. We can do it with help of htmlunit and htmlcleaner jars . To learn how to do it please click on below link.

How to render HTML in java

Step 2 : If you do not want to render html string and only wants to convert it to PDF as is, then you can avoid step 1 and convert that HTML string into DOM with help of DocumentBuilder.


DocumentBuilder db = DocumentBuilderFactory.newInstance().newDocumentBuilder();
InputSource is = new InputSource();
is.setCharacterStream(new StringReader(""));
Document document = db.parse(is);

Step 3 :In step three we will convert that rendered/parsed object into PDF with help of Itext and CoreRenderer Jars. Below is the code given for it.

ITextRenderer renderer = new ITextRenderer();
renderer.setDocument(document,"file:///"+templateLogoPath);
File pdfFile = new File(filePath+pdfFileName);
OutputStream outputStream = new FileOutputStream(pdfFile);
renderer.layout();
rootLogger.debug("Before create PDF with file name --> "+pdfFileName);
renderer.createPDF(outputStream,true);
rootLogger.debug("After create PDF with file Name -->"+pdfFileName);
renderer.finishPDF();
outputStream.flush();
outputStream.close();

This is it now you have converted PDF object.
Jars required for this are :

  1. Itext
  2. CoreRenderer

Please Ask Questions or give suggestions through comments in below section .

Other related posts are :
How to render HTML in java
Top 10 spring interview questions and their answers. Spring basic concepts.
MQ connection not closed and giving MQ Error-2009
Logback logs are not working. Log4j logs are not working. Steps to make logging work.

Please share this posts on facebook,Linkeedin,Google+,Twitter by clicking on below icons.

Advertisements

One thought on “HTML to PDF conversion in JAVA | HTML to PDF example in JAVA

  1. Pingback: Set datasource spring bean properties dynamically if server is not available | Techno Tailor

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s