c# - PDFsharp 看不到文档中的页面

标签 c# pdfsharp

我之前使用 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();
        }
    }
}

最佳答案

你的代码

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

在内存中创建一个新文档——当然这个文档是空的。

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

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

Creates a new PDF document with the specified file name. The file is immediately created and keeps locked until the document is closed, at that time the document is saved automatically. Do not call Save() for documents created with this constructor, just call Close(). To open an existing PDF file and import it, use the PdfReader class.

关于c# - PDFsharp 看不到文档中的页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36939643/

相关文章:

c# - 如何让 Monotorrents DHT 工作?

C# WinForms 程序,能够为其制作 C++ 插件

c# - 创 build 置 (MSI) 以注册(regasm)程序集

java - 请推荐一个基于 Java 的图形 PDF 生成器

c# - 打开 PDF 文件时出现“PDFsharp 无法处理 Acrobat 6 引入的此 PDF 功能”错误

c# - 你如何在 migradoc/pdfsharp 中有一个项目符号列表

c# - 如何在Unity Editor中运行两个游戏窗口

c# - Azure 移动服务对表的限制

c# - 如何使用 PDFsharp 将动态生成的位图插入到 PDF 文档中?

c# - 使用具有包含在 HTML 中的外部 CSS 类的 PdfSharp 从 HTML 片段创建 PDF