Edit DirectContent of iTextSharp PdfSmartCopy class

风流意气都作罢 提交于 2019-11-29 14:42:42

First this: using PdfWriter/PdfImportedPage is not a good idea. You throw away all interactive features! Being the author of iText, it's very frustrating to so many people making the same mistake in spite of the fact that I wrote two books about this, and in spite of the fact that I convinced my publisher to offer one of the most important chapters for free: http://www.manning.com/lowagie2/samplechapter6.pdf

Is my writing really that bad? Or is there another reason why people keep on merging documents using PdfWriter/PdfImportedPage?

As for your specific questions, here are the answers:

  1. Yes. Download the sample chapter and search the PDF file for PageStamp.
  2. Only if you create the PDF in two passes. For instance: create the huge PDF first, then reduce the size by passing it through PdfCopy; or create the merged PDF first with PdfCopy, then add the extra content in a second pass using PdfStamper.

Code after using Bruno Lowagie answer

for (int i = 0; i < pdfPath.Length; i++)
{
       PdfReader reader = new PdfReader(pdfPath[i]);
       PdfImportedPage page;
       PdfSmartCopy.PageStamp stamp;
       for (int ii = 0; ii < reader.NumberOfPages; ii++)
       {
            page = copy.GetImportedPage(reader, ii + 1);
            stamp = copy.CreatePageStamp(page);
            PdfContentByte cb = stamp.GetOverContent();
            cb.Rectangle(100, 100, 100, 100);
            cb.SetColorStroke(BaseColor.RED);
            cb.SetColorFill(BaseColor.RED);
            cb.FillStroke();
            stamp.AlterContents(); // don't forget to add this line
            copy.AddPage(page);                  
        }
}

2.Only if you create the PDF in two passes. For instance: create the huge PDF first, then reduce the size by passing it through PdfCopy; or create the merged PDF first with PdfCopy, then add the extra content in a second pass using PdfStamper.

It is much more difficult to use the PdfStamper with a second pass. When your working with lots of data it's far easier to create 1 pdf stamp then append.

PdfCopyFields had worked well for this. Now it doesn't work as of the 5.4.4.0 release which is why I'm here.

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