用C#实现连续打印pdf文件

要实现连续打印多个 PDF 文件而不在两个文件中间留下空白的效果,你可以使用 PdfSharp 或 iTextSharp 等库来合并这些 PDF 文件。然后,将合并后的 PDF 文件发送到打印机。下面是使用 PdfSharp 的示例代码。

使用 PdfSharp 实现 PDF 合并并打印

  1. 首先,你需要安装 PdfSharp NuGet 包。在项目目录下运行以下命令:

    bash 复制代码
    dotnet add package PdfSharp --version 1.50.5147
  2. 然后,使用以下代码合并 PDF 并打印:

    cs 复制代码
    using System;
    using System.Diagnostics;
    using PdfSharp.Pdf;
    using PdfSharp.Pdf.IO;
    
    class Program
    {
        static void Main()
        {
            string[] pdfFiles = { "file1.pdf", "file2.pdf", "file3.pdf" };
            string outputPdf = "merged.pdf";
    
            MergePdfFiles(pdfFiles, outputPdf);
            PrintPdf(outputPdf);
        }
    
        static void MergePdfFiles(string[] pdfFiles, string outputPdf)
        {
            using (var outputDocument = new PdfDocument())
            {
                foreach (string pdfFile in pdfFiles)
                {
                    using (var inputDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import))
                    {
                        // 将输入PDF文件的所有页面添加到输出文档
                        for (int i = 0; i < inputDocument.PageCount; i++)
                        {
                            outputDocument.AddPage(inputDocument.Pages[i]);
                        }
                    }
                }
    
                outputDocument.Save(outputPdf);
            }
        }
    
        static void PrintPdf(string pdfFile)
        {
            Process printProcess = new Process();
            printProcess.StartInfo.FileName = pdfFile;
            printProcess.StartInfo.Verb = "print";
            printProcess.StartInfo.CreateNoWindow = true;
            printProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
            printProcess.Start();
        }
    }

代码解释

  1. MergePdfFiles 方法: 这个方法将多个 PDF 文件合并为一个。通过逐个打开每个 PDF 文件,并将每个 PDF 的所有页面添加到一个新的输出文档中。

  2. PrintPdf 方法 : 这个方法使用 Process 类来启动打印任务。它将合并后的 PDF 文件发送到默认打印机。

  3. Main 方法: 在主函数中,你可以指定要合并的 PDF 文件,并调用合并和打印的函数。

注意事项

  • 这段代码假设你要打印的 PDF 文件都在项目的根目录下。如果文件路径不同,请确保指定正确的路径。
  • Process.StartInfo.Verb = "print" 将调用默认打印机,如果你想指定特定的打印机,可以进一步配置 ProcessStartInfo。

通过这种方式,你可以避免在多个 PDF 文件之间产生空白页,实现连续打印效果。

相关推荐
samble15 小时前
从零搭建灌装监控系统(十八):自定义控件,三色灯与状态指示
c#·wpf·mvvm·modbus·工业控制
jun_bai16 小时前
使用Aspose实现word文档合并,内容替换
windows·c#·word
字节暗面19 小时前
客户端上报不可信:游戏服务端数据校验与对局重演设计
c#·游戏开发·服务端校验·反作弊
chingho20 小时前
GitHub上这10个C#项目,不仅实用,还怪好玩的
c#·github·.net·开源项目
半亩码田1 天前
C#转Python第5.1篇:异步编程:asyncio vs async/await,语法相似但机制不同
开发语言·python·c#
阿华田5121 天前
Java 类加载冲突实战:解决 is not an instance of
c#·linq
Metaphor6921 天前
Python 实用技巧:从零自主生成结构化 PDF 页面
python·pdf
samble1 天前
从零搭建灌装监控系统(十七):LiveCharts 实时温度曲线
c#·wpf·mvvm·modbus·工业控制
淡海水2 天前
02-07-原理篇-GC暂停时间的本质
开发语言·unity·c#·gc·暂停时间
tianyatest2 天前
给 AI Agent 写了个 Skill:扫描版电子书自动解压合并 + 加书签(附 PDG 格式逆向)
ai·pdf·电子书