首页 > 解决方案 > PDFsharp 要求在添加页面时打开 PDF 以进行导入

问题描述

我有 3 个 PDF,我想将它们中的页面添加到输出 PDF 文件中。我要做的是:导入第一个 PDF -> 创建新的 PDF 文档 -> 添加页面 -> 在特定页面中绘制,最后我想将该文档中的页面添加到将导出的主要 PDF 文档中。如果需要,继续对第二个 PDF 文件执行相同操作。

ERROR: A PDF document must be opened with PdfDocumentOpenMode.Import to import pages from it.

从主类中,我调用处理 PDF 的方法:

        Pdftest pdftest = new Pdftest();
        PdfDocument pdf = PdfReader.Open(@"C:\Users\pdf_file.pdf", PdfDocumentOpenMode.Import);
        pdftest.CreatePages(pdf_file);

pdf测试类:

public class Pdftest
{
    PdfDocument PDFNewDoc = new PdfDocument();
    XFont fontChico = new XFont("Verdana", 8, XFontStyle.Bold);
    XFont fontGrande = new XFont("Verdana", 12, XFontStyle.Bold);
    XBrush fontBrush = XBrushes.Black;

    public void CreatePages(PdfDocument archivoPdf)
    {
        PdfDocument NuevoDoc = new PdfDocument();

        for (int Pg = 0; Pg < archivoPdf.Pages.Count; Pg++)
        {
            PdfPage pp = NuevoDoc.AddPage(archivoPdf.Pages[Pg]);
        }

        XGraphics Graficador = XGraphics.FromPdfPage(NuevoDoc.Pages[0]);

        XPoint coordinate = new XPoint();
        coordinate.X = XUnit.FromInch(1.4);
        coordinate.Y = XUnit.FromInch(1.8);

        graficador.DrawString("TEST", fontChico, fontBrush, coordinates);

        for (int Pg = 0; Pg < NuevoDoc.Pages.Count; Pg++)
        {
            PdfPage pp = PDFNewDoc.AddPage(NuevoDoc.Pages[Pg]); //Error mentioned.
        }
    }
 }

标签: c#pdfpdf-generationpdfsharp

解决方案


错误消息与NuevoDoc. 您必须保存NuevoDoc在 MemoryStream 中并在 Import 模式下重新打开它才能让您的代码继续运行。

我不明白您为什么尝试将页面从 to 复制NuevoDoc-PDFNewDoc所以很可能您可以在优化代码时避免 MemoryStream 。


推荐阅读