使用iText 7将背景添加到PDF中的每个页面

问题描述

我的PDF文件只有一页,我想将第二页PDF文件中的所有页面都用作背景使用,并提供一些信息。我已经尝试过使用 CopyPagesTo 做到这一点,但它只是每隔两页复制一次PDF。

10 minutes - 2 hours

是否可以像背景一样使用一个PDF文件,并在文本后面的每一页将其放入其他PDF文件。

解决方法

根据我的理解,您正在寻找以下解决方案。如果我错过了什么,请告诉我。

  1. 为要创建背景的原始PDF创建阅读器。
  2. 为背景PDF创建PDF阅读器
  3. 在要生成最终PDF的位置创建PDF标记。
  4. 使用Stamper的GetImportedPage方法获取背景。
  5. 环绕原始PDF页面的所有页面并添加背景。

下面是代码:

static void CreatePdfwithBackGround(string originalPdf,string backgroundPdf,string destPdf)
    {
        PdfReader originalPdfReader = new PdfReader(originalPdf);
        PdfReader backgroundPdfReader = new PdfReader(backgroundPdf);
        // Create the stamper for Destination pdf
        PdfStamper stamper = new PdfStamper(originalPdfReader,new FileStream(destPdf,FileMode.Create));
        // Add the backgroundPdf to each page of original PDF
        PdfImportedPage page = stamper.GetImportedPage(backgroundPdfReader,1);
        int pageCount = originalPdfReader.NumberOfPages;
        PdfContentByte background;
        for (int i = 1; i <= pageCount; i++)
        {
            background = stamper.GetUnderContent(i);
            background.AddTemplate(page,0);
        }
        // Close the Destination stamper
        stamper.Close();
    }

示例调用为:

CreatePdfwithBackGround(@"C:\TEST\MainPDF.pdf",@"C:\TEST\BackGroundTemplate.pdf",@"C:\TEST\FinalPDFOutput.pdf");
,

这是iText 7代码。请注意,假定背景和正在处理的文档页面的页面大小相等。

PdfDocument backgroundDocument = new PdfDocument(new PdfReader(@"path/to/background_doc.pdf"));
PdfDocument pdfDocument = new PdfDocument(new PdfReader(@"path/to/source.pdf"),new PdfWriter(@"path/to/target.pdf"));
PdfFormXObject backgroundXObject = backgroundDocument.GetPage(1).CopyAsFormXObject(pdfDocument);
for (int i = 1; i <= pdfDocument.GetNumberOfPages(); i++) {
    PdfPage page = pdfDocument.GetPage(i);
    PdfStream stream = page.NewContentStreamBefore();
    new PdfCanvas(stream,page.GetResources(),pdfDocument).AddXObject(backgroundXObject,0);
}
pdfDocument.Close();
backgroundDocument.Close();

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...