Convert HTML to PDF with Servlet iText- Java Example - Part2

We are providing a tutorial to convert HTML to PDF dynamically using servlets, in the previous part of this post we saw how to write the server side code for our application. If you look at the Java Code, you will find that we are trying to read the FORM data that contains the HTML code snippet, and then use this input to show the converted PDF back to the user. That would mean, we need a HTML page from where we can pass the code for changing to PDF. Refer to a sample HTML code below;
<HTML>
<HEAD>
  <TITLE>Convert HTML to PDF Dynamically Using iText</TITLE>
</HEAD>
<BODY BGCOLOR="#CCFFCC">
<H2>Generate Dynamic PDF Document Using HTML Code Input</H2>
<!-- We invoke the Servlet for PDF generation -->
<FORM ACTION="servlets/servlet/HTMLtoPDFServlet"
      METHOD="POST">
Enter the HTML for Converting to PDF:<BR>
<!-- This Text Area obtains the input from User in HTML format -->
<TEXTAREA NAME="InputData" COLS=40 ROWS=6></TEXTAREA><BR>
<CENTER>
    <INPUT TYPE="SUBMIT" VALUE="Submit">
  </CENTER>
</FORM>
</BODY>
</HTML>
Now, this code shows up a FORM on the page as shown below;
Java Dynamic HTML to PDF Converter
Java HTML to PDF Converter  - HTML Page To Accept Code
Put this HTML file in your webserver in a place that is accessible by browsers.We have to do some configuration changes in the Tomcat server for us to invoke the servlet properly. The changes are listed below;
1) Load all the required JAR files given in Part 1 to lib folder.
(For example: Tomcat\apache-tomcat-7.0.14\lib). Also copy the class file to
your application path. 

2) Edit your web.xml file for configuring the new servlet.
    <servlet-mapping>
        <servlet-name>HTMLtoPDFServlet</servlet-name>
        <url-pattern>/servlets/servlet/HTMLtoPDFServlet</url-pattern>
    </servlet-mapping>

and
    <servlet>
        <servlet-name>HTMLtoPDFServlet</servlet-name>
        <servlet-class>HTMLtoPDFServlet</servlet-class>
    </servlet>

3. Bounce your Tomcat webserver once this is done.
We are now ready to test the code. When used the sample HTML code below, and clicked on submit, I got a PDF opened up on my browser.
<html>
<body>
convert HTML to PDF using itext library in Java - Servlet Based Example
<table border="1">
<tr><td>It Works!</td></tr>
</table>
</body>
</html>
A screenshot of the PDF file is provided below;
PDF Screenshot created by converting the HTML
PDF Screenshot created by converting the HTML
Now, this is not complete. We will have to improvise the servlet code to do the following;
1) Capture Metadata from User and Stamp in XMP format in PDF.
2) Colors and Images..give a try to see if it works!
Let us discuss about this in upcoming tutorials.

No comments:

Post a Comment