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

C#使用Microsoft Print to PDF打印现有PDF文件遇问题求助

使用C#通过Microsoft Print to PDF打印现有PDF文件

问题原因

你当前的代码存在两个核心问题:

  1. 用StreamReader读取PDF文件——PDF是二进制格式,并非纯文本,这种读取方式无法解析有效内容;
  2. .NET原生的PrintDocument类不具备PDF解析和渲染能力,它仅支持文本、图像等基础格式的打印逻辑,因此最终输出空白PDF。

解决方案1:使用PdfSharp库(推荐)

PdfSharp是专门处理PDF的.NET库,可以解析PDF内容并将页面渲染到PrintDocument上,实现完整打印流程。

步骤

  1. 安装NuGet包:针对.NET Core/.NET 5+项目安装PdfSharpCore,针对.NET Framework项目安装PdfSharp;
  2. 替换为以下代码:
using PdfSharp.Pdf;
using PdfSharp.Drawing;
using System.Drawing.Printing;
using System.IO;

internal class Program
{
    private static PdfDocument _targetPdf;

    private static void Main(string[] args)
    {
        string outputDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string pdfSourceDir = Path.GetFullPath(@"C:\Temp\pdf_out");

        foreach (var pdfFile in new DirectoryInfo(pdfSourceDir).GetFiles("*.pdf"))
        {
            try
            {
                _targetPdf = PdfReader.Open(pdfFile.FullName, PdfDocumentOpenMode.Import);
                
                var printDoc = new PrintDocument
                {
                    PrinterSettings = new PrinterSettings
                    {
                        PrinterName = "Microsoft Print to PDF",
                        PrintToFile = true,
                        PrintFileName = Path.Combine(outputDir, $"reprinted_{pdfFile.Name}")
                    }
                };

                printDoc.PrintPage += RenderPdfPage;
                printDoc.Print();
            }
            finally
            {
                _targetPdf?.Dispose();
            }
        }
    }

    private static void RenderPdfPage(object sender, PrintPageEventArgs e)
    {
        int currentPage = e.PageSettings.PrintableArea.Page;
        if (currentPage >= _targetPdf.PageCount)
        {
            e.HasMorePages = false;
            return;
        }

        var pdfPage = _targetPdf.Pages[currentPage];
        using (var graphics = XGraphics.FromGraphics(e.Graphics, e.PageBounds))
        {
            // 按打印区域缩放PDF页面
            graphics.ScaleTransform(e.PageBounds.Width / pdfPage.Width, e.PageBounds.Height / pdfPage.Height);
            graphics.DrawPdfPage(pdfPage, 0, 0);
        }

        e.HasMorePages = currentPage + 1 < _targetPdf.PageCount;
    }
}

解决方案2:使用Windows Shell命令(无需第三方库)

利用Windows系统自带的PDF查看器(如Microsoft Edge)的命令行能力,直接调用系统打印逻辑,无需引入额外库。

using System.Diagnostics;
using System.IO;

internal class Program
{
    private static void Main(string[] args)
    {
        string outputDir = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        string pdfSourceDir = Path.GetFullPath(@"C:\Temp\pdf_out");

        foreach (var pdfFile in new DirectoryInfo(pdfSourceDir).GetFiles("*.pdf"))
        {
            string outputPath = Path.Combine(outputDir, $"reprinted_{pdfFile.Name}");
            
            // 调用Edge无头模式打印PDF
            var startInfo = new ProcessStartInfo
            {
                FileName = "msedge.exe",
                Arguments = $"--headless --print-to-pdf=\"{outputPath}\" \"{pdfFile.FullName}\"",
                CreateNoWindow = true,
                WindowStyle = ProcessWindowStyle.Hidden
            };

            using (var process = Process.Start(startInfo))
            {
                process.WaitForExit();
            }
        }
    }
}

注意事项

  • 方案1中,若使用PdfSharpCore,部分API命名空间和调用方式会略有差异,需参考对应版本文档调整;
  • 方案2依赖Microsoft Edge浏览器,若系统默认PDF查看器为其他软件(如Adobe Reader),需替换为对应软件的命令行参数。

内容的提问来源于stack exchange,提问作者Manoj RG

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 10:15:50