PNG to PDF Java Servlet Example - iText Tutorial

In this tutorial, we will extend our JPG to PDF conversion servlet code, to support PNG to PDF conversion. The servlet will accept a user uploaded PNG image document and convert this to PDF and stream it back to the user in the browser.This tutorial refers to a standalone PNG to PDF conversion example provided in our blog earlier. It is advised to refer to the tutorial before proceeding with the servlet example.This example provides only the code that needs to be modified from the initial servlet example. There are two components to this example;

1) Modifying the index.jsp file to support an option that enables the PNG to PDF change.
2) Writing code at the server end to write the PDF file to document and send it back to the browser.

The code snippets for each of these cases is provided below. You will have to append this code with the original example to get the conversion going. If you are stuck at any point, you can post it as a comment and we will be happy to fix it for you.The modification that needs to be done in index.jsp file is provided below;
  <select name="convertTo" id="convertTo" onChange="javascript:enableField()">
      <option>Gif2Pdf</option> <!-- New Option to Capture Gif2Pdf conversion -->
      <option>Bmp2Pdf</option> <!-- Option to support BMP to PDF conversion -->
      <option>Png2Pdf</option> <!-- Option to convert PNG to PDF -->
With this option included, the user will get a drop down option to select the conversion type we are after. This needs to be supported with some code in our servlet; the snippet that needs to be added to the existing code is provided below;
            //Check if PNG to PDF is opted as selection
            // PNG 2 PDF servlet example
            if (conversionType.equals("Png2Pdf")){
               Image tempImage=PngImage.getImage(FilePath);                     
Make sure that you include the following import declaration to the existing code; otherwise the conversion would not work (you will neither be able to compile and deploy your servlet code )
import com.itextpdf.text.pdf.codec.PngImage;
Search our site on how to deploy to Tomcat, if you need to know how to deploy a WAR file in Tomcat web server. Post a comment for any other question, on this servlet code.

No comments:

Post a Comment