【问题标题】:Copy page from pdf file to new document将页面从 pdf 文件复制到新文档
【发布时间】:2018-09-22 18:31:02
【问题描述】:

我正在尝试从现有的 .pdf 文件中复制一页并将其粘贴到新文档中,如下所示:

     using (var writer = new PdfWriter(OutputFile))
        {
          var reader = new PdfReader("Templates//PDF_Template_Empty.pdf");
          PdfDocument template = new PdfDocument(reader);
          var titlepage = template.GetPage(1);
          using (var pdf = new PdfDocument(writer))
            {
                pdf.AddPage(titlepage); // exception

但是在.AddPage() 上它会抛出这个异常:

iText.Kernel.PdfException: '页面 iText.Kernel.Pdf.PdfPage 不能 添加到文档 iText.Kernel.Pdf.PdfDocument,因为它属于 文档 iText.Kernel.Pdf.PdfDocument.'

我该如何解决这个问题?

【问题讨论】:

  • 你在用什么PdfWriter?例如,您能否提供指向其文档的链接,或者提供其程序集或完整命名空间的名称?

标签: c# pdf itext itext7


【解决方案1】:

一个 PDF 页面对象通常有许多相关的对象。如果您只将页面本身添加到新文档而不是相关对象,则生成的页面将是不完整的。

因此,iText 7 在AddPage 中检查相关页面是否已在目标文档中创建,并在后一种情况下引发异常以防止丢失依赖对象。

要跨文档复制页面,有PdfDocument 方法CopyPagesTo 有许多重载。比如给你

PdfDocument template = new PdfDocument(reader);
using (var pdf = new PdfDocument(writer))
{
    // copy template pages 1..1 to pdf as target page 1 onwards
    template.CopyPagesTo(1, 1, pdf, 1); 
}

(请注意,如果页面上有额外内容,您可能希望选择该方法的重载,该方法接受额外的 IPdfPageExtraCopier 实例,例如,对于 AcroForm 字段,PdfPageFormCopier。)

【讨论】:

  • 你的意思是,我可以更改从template文档复制的新页面中的字段吗?
  • 更准确地说:只有当您复制带有PdfPageFormCopier 的页面时,AcroField 字段才会被复制到目标文档中。在这种情况下,我希望您能够在目标文档中更改它们的值(我还没有尝试过)。
猜你喜欢
  • 2018-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多