You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用PDFsharp打印PDF时出现PdfPage Stream空引用错误的问题

使用PDFsharp打印PDF时出现PdfPage Stream空引用错误的问题

我之前也踩过PDFsharp打印的这个坑,先给你说清楚核心问题:你用错了获取页面内容的方式——PdfPage.Stream属性根本不是用来处理现有PDF打印的,对于从文件加载的现成PDF页面,这个属性本来就是null,和你的文件路径、PDF是否存在完全没关系,这是PDFsharp的设计逻辑导致的,别再怀疑自己的路径了😅

咱们换个正确的思路来实现打印:不用Stream,而是直接用PDFsharp的XGraphics把PDF页面渲染到打印事件提供的画布上。我把你的代码补全并修正了,你可以直接参考:

using PdfSharp.Drawing;
using PdfSharp.Pdf;
using PdfSharp.Pdf.IO;
using System.Windows.Forms;
using System.Drawing.Printing;

// 注意:要确保你声明了这两个静态变量(和你原代码对应)
private static PdfDocument pdfDoc;
private static int CurrentPage;

public static void PrintPdfWithPrintDocument(string pdfPath)
{
    if (!System.IO.File.Exists(pdfPath))
    {
        MessageBox.Show("Not Found.");
        return;
    }

    // 这里建议用ReadOnly模式打开,因为你只是打印不需要修改PDF
    pdfDoc = PdfReader.Open(pdfPath, PdfDocumentOpenMode.ReadOnly);
    CurrentPage = 0;

    PrintDocument prnPdf = new PrintDocument();
    prnPdf.PrintPage += OnPrintPage;

    PrintDialog ptdPrinter = new PrintDialog();
    ptdPrinter.AllowSomePages = true;
    ptdPrinter.Document = prnPdf;

    // 处理用户选择的页码范围
    if (ptdPrinter.ShowDialog() == DialogResult.OK)
    {
        // 如果用户选了特定页码,调整起始页
        if (ptdPrinter.PrinterSettings.FromPage > 0)
        {
            // PDFsharp的页码从0开始,打印对话框的页码从1开始,要减1
            CurrentPage = ptdPrinter.PrinterSettings.FromPage - 1;
        }
        prnPdf.PrinterSettings = ptdPrinter.PrinterSettings;
        prnPdf.Print();
    }
}

private static void OnPrintPage(object sender, PrintPageEventArgs e)
{
    PrintDocument pd = (PrintDocument)sender;
    int pageCount = pdfDoc.PageCount;

    // 处理用户选择的结束页码
    int endPage = pd.PrinterSettings.ToPage > 0 ? pd.PrinterSettings.ToPage - 1 : pageCount - 1;

    // 只处理当前页码在用户选择范围内的情况
    if (CurrentPage > endPage)
    {
        e.HasMorePages = false;
        return;
    }

    PdfPage page = pdfDoc.Pages[CurrentPage];

    // 关键:用XGraphics把PDF页面画到打印画布上
    using (XGraphics gfx = XGraphics.FromGraphics(e.Graphics, new XSize(page.Width, page.Height)))
    {
        // 这里可以设置打印的缩放,比如适配打印机的纸张
        XRect rect = new XRect(0, 0, page.Width, page.Height);
        gfx.DrawPdfPage(page, rect);
    }

    // 准备下一页
    CurrentPage++;
    e.HasMorePages = CurrentPage <= endPage;
}

最后再给你提几个关键注意点:

  • 打开PDF时用PdfDocumentOpenMode.ReadOnly而非Modify,毕竟只是打印不需要修改,这样更高效安全
  • 打印对话框的页码从1开始计数,但PDFsharp的页面索引是从0开始的,一定要做减1转换,不然会打错页面
  • 始终用XGraphics.DrawPdfPage来渲染页面,这是PDFsharp官方推荐的打印/渲染方式,完全绕开了那个没用的Stream属性

备注:内容来源于stack exchange,提问作者Vinicius Leandro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.04.16 09:12:58