How to add a cover/PDF in a existing iText document [closed]

廉价感情. 提交于 2019-12-29 08:22:27

问题


I need some help with iText. I need to add an existing pdf cover in other existing iText document or PDF document. Anybody could help me? I've searched in some books (iText in action) but it's somewhat compicated.


回答1:


Suppose that we have a document named pages.pdf and that we want to add the cover hero.pdf as the cover of this document.

Approach 1: Use PdfCopy

Take a look at the AddCover1 example:

PdfReader cover = new PdfReader("hero.pdf");
PdfReader reader = new PdfReader("pages.pdf");
Document document = new Document();
PdfCopy copy = new PdfCopy(document, new FileOutputStream("pages_with_cover.pdf"));
document.open();
copy.addDocument(cover);
copy.addDocument(reader);
document.close();
cover.close();
reader.close();

The result is a document where you first have the cover and then the rest of the document: pages_with_cover.pdf

Approach 2: Use PdfStamper

Take a look at the AddCover2 example:

PdfReader cover = new PdfReader("hero.pdf");
PdfReader reader = new PdfReader("pages.pdf");
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("cover_with_pages.pdf"));
stamper.insertPage(1, cover.getPageSizeWithRotation(1));
PdfContentByte page1 = stamper.getOverContent(1);
PdfImportedPage page = stamper.getImportedPage(cover, 1);
page1.addTemplate(page, 0, 0);
stamper.close();
cover.close();
reader.close();

In this case, we take the original document pages.pdf and we insert a new page 1 with the same page size as the cover. We then get this page1 and we add the first page of hero.pdf to this first page. The result is cover_with_pages.pdf

What is the difference between the two approaches?

With PdfCopy, you may lose some of the properties that are defined at the document level (e.g. the page layout setting), but you keep the interactive features of both files. You may need to set some parameters in case you want to preserve tagging, form fields, etc... but for simple PDFs, you don't need all of that.

With PdfStamper, you preserve the properties that are defined at the document level of pages.pdf, but you lose all the interactive features of the cover page (if any). You may need to tweak the example if you want to define the cover as an artifact and if the original cover page has odd page boundaries, but it would lead us too far to discuss this in this simple answer.



来源:https://stackoverflow.com/questions/29563942/how-to-add-a-cover-pdf-in-a-existing-itext-document

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!