【问题标题】:PDFsharp asking for a PDF to be opened for Import when adding pagesPDFsharp 要求在添加页面时打开 PDF 以进行导入
【发布时间】:2018-12-19 11:29:49
【问题描述】:

我有 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);

Pdftest 类:

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# pdf pdf-generation pdfsharp


    【解决方案1】:

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

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

    【讨论】:

    • 这是因为(可能不是一个好方法)我想避免寻找确切的页面来写PDFNewDoc。如果我只是将archivoPdf 页面复制到PDFNewDoc,我将不知道要写的确切页面,因为我可能会使用 2/3 的首字母 pdf。
    • 代码 sn-p 将所有页面从first 复制到second,然后从second 复制所有页面到third 我仍然没有看到不将修改和过滤合并到的理由一步,因此您只需处理一次页面,将它们从source 克隆到final,而无需中间 PDF 文件。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-21
    • 1970-01-01
    • 2015-01-29
    • 1970-01-01
    • 1970-01-01
    • 2023-03-19
    相关资源
    最近更新 更多