【问题标题】:PDFsharp does not see pages in documentsPDFsharp 看不到文档中的页面
【发布时间】:2016-08-24 16:36:27
【问题描述】:

我之前使用 PDFsharp 进行了一些文件合并,现在我正在尝试更改几个文件(插入或删除一些页面),但我遇到了库看不到页面的问题。它说 PageCount == 0 并且我在对象中找不到页面(在调试时)。当然,我不能做我目前的工作。我使用这个非常简单的代码:

var destinationPdf = new PdfDocument(destinationFilePath);
Int32 count = destinationPdf.PageCount;

还有,这里是我之前用来将文件合并为一个 PDF 的代码:

public class PdfCreator
{
    private PdfDocument document;

    public PdfCreator()
    {
        this.document = new PdfDocument();
    }

    public void AddImage(String imageFilePath)
    {
        PdfPage newPage = this.document.AddPage();
        XGraphics xGraphics = XGraphics.FromPdfPage(newPage);
        XImage image = XImage.FromFile(imageFilePath);
        xGraphics.DrawImage(image, 0, 0);
    }

    public void AddPdfFile(String pdfFilePath)
    {
        PdfDocument inputDocument = PdfReader.Open(pdfFilePath, PdfDocumentOpenMode.Import);
        Int32 count = inputDocument.PageCount;
        for (Int32 currentPage = 0; currentPage < count; currentPage++)
        {
            PdfPage page = inputDocument.Pages[currentPage];
            this.document.AddPage(page);
        }
    }

    public void AddTextFile(String txtFilePath)
    {
        PdfPage newPage = this.document.AddPage();
        XGraphics xGraphics = XGraphics.FromPdfPage(newPage);
        var xFont = new XFont("Times New Roman", 12, XFontStyle.Bold);
        var xTextFormatter = new XTextFormatter(xGraphics);
        var rect = new XRect(30, 30, 540, 740);
        xGraphics.DrawRectangle(XBrushes.Transparent, rect);
        xTextFormatter.Alignment = XParagraphAlignment.Left;
        xTextFormatter.DrawString(File.ReadAllText(txtFilePath), xFont, XBrushes.Black, rect, XStringFormats.TopLeft);
    }

    public void Save(String destinationFilePath)
    {
        if (this.document.Pages.Count > 0)
        {
            this.document.Save(destinationFilePath);
            this.document.Close();
        }
    }
}

【问题讨论】:

标签: c# pdfsharp


【解决方案1】:

你的代码

var destinationPdf = new PdfDocument(destinationFilePath);
Int32 count = destinationPdf.PageCount;

在内存中创建一个新文档 - 这个文档肯定是空的。

使用PdfReader.Open 从现有文件在内存中创建文档。

当我在您的代码中将鼠标光标放在 PdfDocument 上时,我会得到以下工具提示:

使用指定的文件名创建一个新的 PDF 文档。该文件是 立即创建并保持锁定,直到文档关闭,在 那时文档会自动保存。不要调用 Save() 使用此构造函数创建的文档,只需调用 Close()。打开一个 现有的 PDF 文件并导入它,使用 PdfReader 类。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多