Let's say I have two PDF templates created with Adobe Acrobat, which are both single-page, 8.5x11 documents. The first template (A.pdf) has content for the top half of the page. The second template (B.pdf) has content for the bottom half of the page. (It just so happens the content in both templates does not "overlap" each other.)
I would like to use iText to take these two templates and create a single, "merged" template from it (C.pdf) that is only a single page (with A.pdf's content on the top half and B.pdf's content on the bottom half).
(I do not want to "merge" these two files into a 2-page document. I need the final product to be a single page.)
I will be running iText in a servlet environment (Tomcat 6) but I don't think that makes a difference to the answer.
Is this possible?
I got help from Mark Storer on the iText mailing list. The solution is to get PdfTemplate
objects for each file, and then use the addTemplate()
method to add them together, e.g.:
PdfTemplate topOfPage = writer.getImportedPage( reader, 1 );
PdfTemplate bottomOfPage = writer.getImportedPage( reader, 2 );
PdfContentByte content = writer.getDirectContent();
// in PDF, "0, 0" is the lower left corner.
content.addTemplate( bottomOfPage );
content.addTemplate( topOfPage, 0, bottomOfPage.getHeight() );
Perhaps this code sample helps
http://kickjava.com/src/com/lowagie/tools/handout_pdf.java.htm
a much more used case is to merge a single page background pdf with a multi page source pdf file. The background pdf contains only a header and footer for instance. The source pdf is already prepared with upper und lower margins as placeholders for the header and footer of the background pdf template in this scene. If you are looking for this - like I did - you will stumbling over this thread here and you could apply the following approach:
tplFile$ = "c:/0/background.pdf"
srcFile$ = "c:/0/source1.pdf"
destFile$ = "c:/0/newMergedDest.pdf"
declare Document destDoc!
declare PdfWriter destWriter!
declare PdfReader mainDocReader!
declare PdfReader singlePageBackgroundReader!
declare PdfImportedPage mainDocPage!
declare PdfImportedPage backgroundPage!
declare PdfContentByte dcb!
declare PdfContentByte ucb!
destDoc! = new Document()
destWriter! = PdfWriter.getInstance(destDoc!, new FileOutputStream(destFile$))
destDoc!.open()
dcb! = destWriter!.getDirectContent()
ucb! = destWriter!.getDirectContentUnder()
mainDocReader! = new PdfReader(srcFile$)
singlePageBackgroundReader! = new PdfReader(tplFile$)
backgroundPage! = destWriter!.getImportedPage(singlePageBackgroundReader!,1)
for i=1 to mainDocReader!.getNumberOfPages()
destDoc!.newPage()
mainDocPage! = destWriter!.getImportedPage(mainDocReader!,i)
dcb!.addTemplate(mainDocPage!,0,0)
ucb!.addTemplate(backgroundPage!,0,0)
next i
destDoc!.close()