1

I have requirement in my project to generate PDF files dynamically. this PDF file should contain Header image, Footer Image and some content depending upon parameters passed to my servlet. These contents can be in HTML text format and can be PDF files or both. I am able to create PDF file for HTML text using HTMLWorker and able to copy PDF file as well, but whenever content comes in HTML and PDF file then some how its not working. My contents are getting overridden. Here is the code, I am trying right now.

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.StringReader;
import java.net.MalformedURLException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.ExceptionConverter;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.html.simpleparser.HTMLWorker;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
public class itextPdf {
static class PageHeader extends PdfPageEventHelper{
    String header;

    public void setHeader(String header) {
        this.header = header;
    }

    public void onEndPage(PdfWriter writer, Document document) {
        System.out.print("Yeahhhhh...now add header");
        PdfPTable table = new PdfPTable(1);
        try {
            table.setWidths(new int[]{527});
            table.setTotalWidth(600);
            table.setLockedWidth(true);
            table.getDefaultCell().setFixedHeight(40);
            //table.getDefaultCell().setBorder(Rectangle.BOTTOM);
            Image img = Image.getInstance(header);
            img.setScaleToFitLineWhenOverflow(true);
            PdfPCell cell = new PdfPCell(img);
            //cell.setBorder(Rectangle.BOTTOM);
            table.addCell(cell);
            table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
            //table.addCell(String.format("Page %d of", writer.getPageNumber()));
            //PdfPCell cell = new PdfPCell(Image.getInstance(total));
            //cell.setBorder(Rectangle.BOTTOM);
            //table.addCell(cell);
            //System.out.println(850 - document.topMargin() + table.getTotalHeight());
            table.writeSelectedRows(0, -1, 0, 845 , writer.getDirectContent());
        }
        catch(DocumentException de) {
            throw new ExceptionConverter(de);
        } catch (MalformedURLException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

public static void main(String[] args){
    try{
        Document document = new Document(PageSize.A4, 50, 50, 50, 50);
        FileOutputStream fos = new FileOutputStream("parsedpdf.pdf");
        PdfWriter pdfWriter = PdfWriter.getInstance(document, fos);
        PageHeader event = new PageHeader();
        event.setHeader("C:/logos/120x60_KU.jpg");

        pdfWriter.setPageEvent(event);
        document.open();
        document.addAuthor("Author of the Doc");
        document.addCreator("Creator of the Doc");
        document.addSubject("Subject of the Doc");
        document.addCreationDate();
        document.addTitle("This is the title");

        //SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
        //SAXmyHtmlHandler shh = new SAXmyHtmlHandler(document);

        HTMLWorker htmlWorker = new HTMLWorker(document);
        String str = "<B>NINAD ROCKS</B> :: <table><tr><td><p style=’font-size: 10pt; font-family: Times’>" +
            "Cher Monsieur,</p><br><p align=’justify’ style=’text-indent: 2em; font-size: 10pt; font-family: Times’>" +
            "asdasdasdsadas<br></p><p align=’justify’ style=’text-indent: 2em; font-size: 10pt; font-family: Times’>" +
            "En vous remerciant &agrave; nouveau de la confiance que vous nous t&eacute;moignez,</p>" +
            "<br><p style=’font-size: 10pt; font-family: Times’>Bien Cordialement,<br>" +
            "<br>ADMINISTRATEUR ADMINISTRATEUR<br>Ligne directe : 04 42 91 52 10<br>Acadomia&reg; – " +
            "37 BD Aristide Briand  – 13100 Aix en Provence  </p></td></tr></table>";
        StringBuffer sb = new StringBuffer(str);

        for(int i=0; i< 5 ; i++){
            sb.append(str);
        }
        htmlWorker.parse(new StringReader(sb.toString()));

        Image image = Image.getInstance("C:/Documents/Shared/compliance/btn_submit1.jpg");
        document.add(image);
        //document.add

        PdfReader reader = new PdfReader("C:/Ebooks/Interview/interview_questions 3.pdf");
        int size = reader.getNumberOfPages();
        System.out.println("Size:" + size);
        PdfPTable table = new PdfPTable(2);
        document.newPage();
        PdfImportedPage page;
        PdfContentByte cb = pdfWriter.getDirectContent();
        Rectangle psize = reader.getPageSize(1);
        float width = psize.getWidth();
        for(int i=1; i <=size; i++){
            //byte[] dataBytes = reader.getPageContent(i);
            //System.out.println(i + " " + dataBytes.length);
            //PdfObject pbo = new PdfStream(dataBytes);
            //((PdfStream)pbo).writeContent(fos);
            System.out.println("In:" + i);
            page = pdfWriter.getImportedPage(reader, i);
            cb.addTemplate(page, 0 , 0);
            System.out.println("$$" +page.toString());
            table.addCell(Image.getInstance(page));
            //document.add(page);
        }
        document.add(table);
        cb.beginText();
        cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED), 9);
        String str1 = "<B>NINAD ROCKS</B> :: FOOTER FOOTER :: NINAD ROCKS :: FOOTER FOOTER";
        cb.showText(str1);
        cb.endText();

        document.close();
        HTMLWorker htmlWorker1 = new HTMLWorker(document);
        StringBuffer sb1 = new StringBuffer(str1);
        htmlWorker1.parse(new StringReader(sb1.toString()));

        document.close();
    }catch(Exception e){
        e.printStackTrace();
    }
}
}

Please help with this. Or let me know if there is any other way to achieve my functionality.

madth3
  • 7,275
  • 12
  • 50
  • 74
  • Generate HTML to PDF using iText and then merge the document with another PDF. If you are having at the time of merge. Only way to identify is place the sample files here to test and let you know. – Phani Apr 13 '12 at 13:17
  • Thanks @Phani for solution. I'll try and will let you know if it works. – Ninad Shaha Apr 17 '12 at 07:40
  • Hi @Phani, the problem with your solution is it adds lots of blank spaces in between. When we merge pdfs they get merged page by page, so if any page contains only half page data then rest looks blank and I don't want this. If html content is small and pdf file contains only half page data then dynamically generated PDF should contain only single page. ANy way this can be achieved? – Ninad Shaha Apr 25 '12 at 12:10
  • I think..you could achieve it only when the other document generated from backing up XML or HTML.That way, you could read HTML form of actual PDF and merge this inside of it. Otherwise, We can not control the layout as far as i know. – Phani Apr 25 '12 at 12:56
  • @Phani, didn't understand. can you show me any code snippet or link that can show me some examples. – Ninad Shaha Apr 25 '12 at 15:01
  • Apache FOP is one of the library which creates PDF documents using XML. So, if you have documents created using XML, then we could read the PDF file backed up by XML and modify XML to control layout in PDF.http://xmlgraphics.apache.org/fop/ – Phani Apr 25 '12 at 15:30

0 Answers0