Java Servlet code to convert Html to PDF using iTextRenderer example.

Converting Html to PDF is necessary in many applications. In this tutorial, let us see that how to convert html code into PDF using ITextRenderer. This code accepts html code from a browser and the servlet converts the html code into PDF.

	    ITextRenderer itxtrenderer = new ITextRenderer();
	    itxtrenderer.setDocument(document,null);
	    itxtrenderer.layout();
	    itxtrenderer.createPDF(os,true);  // creates PDF from the XML document and writes to outputstream.

The above lines of code using ITextRenderer creates PDF from an XML document which was parsed from HTML and writes to outputstream.

The below JSP code accepts Html from the browser and send to servlet Html2Pdf.

html2pdf.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
	<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
	<title>Html to PDF conversion</title>
</head>
<body>
<form name="h2pForm" action="Html2Pdf" method="post">

	<div> Enter / Paste  Your Html in the Text Area and Submit</div>

	<textarea name="html" rows="20" cols="75"></textarea> 

	<input type="submit" value="Submit"/>
</form>

</body>
</html>

The below servlet code converts the html to PDF

Html2Pdf.java


package html2pdf;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.OutputStream;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;

import org.xhtmlrenderer.pdf.ITextRenderer;
import org.xhtmlrenderer.resource.FSEntityResolver;
import org.xml.sax.SAXException;

import com.lowagie.text.DocumentException;

@WebServlet("/Html2Pdf")
public class Html2Pdf extends HttpServlet {
	private static final long serialVersionUID = 1L;

    public Html2Pdf() {
        super();
    }

	protected void doGet(HttpServletRequest requestObj, HttpServletResponse responseObj) throws ServletException, IOException {

		}

	protected void doPost(HttpServletRequest requestObj, HttpServletResponse responseObj) throws ServletException, IOException {

				responseObj.setHeader("Cache-Control", "no-cache"); 

				String html = (String) requestObj.getParameter("html");

				responseObj.setContentType( "application/pdf" );  //Content type should be application/pdf

				responseObj.setHeader("Content-Disposition","attachment; filename=\"" +"MyPdf.pdf\"" );
				responseObj.setHeader("Cache-Control", "no-cache");
			    OutputStream os=responseObj.getOutputStream();
				final DocumentBuilderFactory documentBuilderFactory = DocumentBuilderFactory.newInstance();
			    documentBuilderFactory.setValidating(true);
			    DocumentBuilder builder;
			    try {
						builder = documentBuilderFactory.newDocumentBuilder();
					    builder.setEntityResolver(FSEntityResolver.instance());
						org.w3c.dom.Document document;
						document=builder.parse(new ByteArrayInputStream(html.getBytes())); //Parse the content of the given InputStream as an XML document and return a new DOM Document object. 

					    ITextRenderer itxtrenderer = new ITextRenderer();
					    itxtrenderer.setDocument(document,null);
					    itxtrenderer.layout();
					    itxtrenderer.createPDF(os,true);  // creates PDF from the XML document and writes to outputstream.
				  } catch (ParserConfigurationException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();

				  } catch (SAXException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				  }
					catch (DocumentException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
					}
				 os.flush();
				 os.close();

						}

}

}

The above code converts the HTML which is well formed. If all the elements of the html is not well formed, then it will throw parsing error. In this case you can use HtmlCleaner to clean html before parsing then create PDF.

Example Html to be converted to PDF


<!DOCTYPE html>
<html>
<head>
<title>Html2Pdf</title>
</head>
<body>

<center><h1>Item Master Details</h1></center>
<p>This below table shows the Item Master Details as on Today </p>

<table border="1" style="width:100%">

  <tr>
    <td>Item Name</td>
    <td>Price</td>
    <td>Quantity</td>
  </tr>
  <tr>
    <td>LCD TV</td>
    <td>Rs. 45000</td>
    <td>5</td>
  </tr>
  <tr>
    <td>Split AC</td>
    <td>Rs. 30000</td>
    <td>4</td>
  </tr>
</table>

</body>
</html>

Run the above web application by calling

http://localhost:8080/TestWeb/html2pdf.jsp

Paste the above example html code into the text area and submit. Now your PDF is generated and downloaded into your local machine.

Input Page to accept html:

htmltopdf

 

Generated PDF:

htmltopdf output

Leave a Reply

6 Comments on "Java Servlet code to convert Html to PDF using iTextRenderer example."


Guest
S.K
1 year 1 month ago

Sir it’s not working… all the necessary jar files have been added…. when running the downloaded mypdf.pdf is not opening..file size has zero bytes…. thx

Guest
adarsh
3 months 23 days ago

copy all jars in lib folder inside web-inf

Guest
Id37
1 year 2 months ago

Interessant post but what about css file ? css style is it applied ?