Friday, December 11, 2015

Converting Html file to PDF file

In this example we learn how to convert the Html file to PDF file programmitically using iText and java.

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Paragraph;
import com.lowagie.text.html.simpleparser.HTMLWorker;
import com.lowagie.text.pdf.PdfWriter;


public class HtmlToPdf {
    public static void main(String[] args) throws DocumentException {
        // TODO Auto-generated method stub
        FileReader fr = null;
        Document document = new Document();
        PdfWriter writer = null;
        try {
         // Initializing the source html file
            String file_name = "[SOURCE_HTML_FILE]";
            fr = new FileReader(file_name);
            PdfWriter.getInstance(document, System.out);
            //initalizing the destination file or file to save location
            writer = PdfWriter.getInstance(document, new FileOutputStream("[FILE_PATH_TO_SAVE]"));
            document.open();
            document.add(new Paragraph("\n"));
            //Converting the Html content to htmldataelements which we will use this in next steps
            ArrayList htmlContentList = HTMLWorker.parseToList(fr, null);

            //fetch the html content line by line and adding the content to pdf document.
            for (int htmlDataCntr = 0; htmlDataCntr < htmlContentList.size(); htmlDataCntr++) {
             Element htmlDataElement = (Element) htmlContentList.get(htmlDataCntr);
                if(htmlDataElement!=null){
                 document.add(new Paragraph("\n"));
                 document.add(htmlDataElement);
                }
            }
            fr.close();
            document.close();

        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}