C# 文档打印解决方案,支持 PDF 和 Word 文档的打印,包含打印机选择、页面设置、批量打印等功能。
一、项目结构
DocumentPrinter/
├── Program.cs # 程序入口
├── MainForm.cs # 主窗体
├── PdfPrintManager.cs # PDF打印管理器
├── WordPrintManager.cs # Word打印管理器
├── PrintJob.cs # 打印任务管理
├── PrinterUtils.cs # 打印机工具类
├── DocumentPreviewer.cs # 文档预览
└── DocumentPrinter.csproj
二、核心源码实现
2.1 项目文件 (DocumentPrinter.csproj)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>WinExe</OutputType>
<TargetFramework>net6.0-windows</TargetFramework>
<Nullable>enable</Nullable>
<UseWindowsForms>true</UseWindowsForms>
</PropertyGroup>
<ItemGroup>
<!-- Spire.PDF 和 Spire.Doc 用于文档处理 -->
<PackageReference Include="Spire.PDF" Version="9.5.0" />
<PackageReference Include="Spire.Doc" Version="11.8.0" />
<!-- 可选:PdfiumViewer 作为替代方案 -->
<!-- <PackageReference Include="PdfiumViewer" Version="2.13.0" /> -->
<!-- Microsoft Office Interop (需要安装Office) -->
<!-- <PackageReference Include="Microsoft.Office.Interop.Word" Version="15.0.4797.1004" /> -->
</ItemGroup>
</Project>
2.2 程序入口 (Program.cs)
using System;
using System.Windows.Forms;
namespace DocumentPrinter
{
internal static class Program
{
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new MainForm());
}
}
}
2.3 主窗体 (MainForm.cs)
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
namespace DocumentPrinter
{
public partial class MainForm : Form
{
private PdfPrintManager pdfPrintManager = new PdfPrintManager();
private WordPrintManager wordPrintManager = new WordPrintManager();
private PrintJobManager printJobManager = new PrintJobManager();
private List<string> selectedFiles = new List<string>();
public MainForm()
{
InitializeComponent();
LoadPrinters();
}
private void LoadPrinters()
{
cmbPrinters.Items.Clear();
var printers = PrinterUtils.GetInstalledPrinters();
foreach (var printer in printers)
{
cmbPrinters.Items.Add(printer);
}
if (cmbPrinters.Items.Count > 0)
{
cmbPrinters.SelectedIndex = 0;
}
}
private void btnBrowseFiles_Click(object sender, EventArgs e)
{
OpenFileDialog openFileDialog = new OpenFileDialog();
openFileDialog.Filter = "文档文件|*.pdf;*.doc;*.docx;*.rtf|PDF文件|*.pdf|Word文件|*.doc;*.docx|所有文件|*.*";
openFileDialog.Multiselect = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
selectedFiles.Clear();
lstFiles.Items.Clear();
foreach (var file in openFileDialog.FileNames)
{
selectedFiles.Add(file);
lstFiles.Items.Add(Path.GetFileName(file));
}
UpdateFileInfo();
}
}
private void UpdateFileInfo()
{
if (selectedFiles.Count > 0)
{
lblFileCount.Text = $"已选择 {selectedFiles.Count} 个文件";
// 统计文件类型
int pdfCount = 0, wordCount = 0;
foreach (var file in selectedFiles)
{
string ext = Path.GetExtension(file).ToLower();
if (ext == ".pdf") pdfCount++;
else if (ext == ".doc" || ext == ".docx") wordCount++;
}
lblFileTypes.Text = $"PDF: {pdfCount} 个, Word: {wordCount} 个";
}
else
{
lblFileCount.Text = "未选择文件";
lblFileTypes.Text = "";
}
}
private void btnPrint_Click(object sender, EventArgs e)
{
if (selectedFiles.Count == 0)
{
MessageBox.Show("请先选择要打印的文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
if (cmbPrinters.SelectedItem == null)
{
MessageBox.Show("请选择打印机!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string printerName = cmbPrinters.SelectedItem.ToString();
bool success = true;
foreach (var file in selectedFiles)
{
try
{
UpdatePrintStatus($"正在打印: {Path.GetFileName(file)}");
string ext = Path.GetExtension(file).ToLower();
bool printSuccess = false;
if (ext == ".pdf")
{
printSuccess = pdfPrintManager.PrintPdf(file, printerName, GetPrintSettings());
}
else if (ext == ".doc" || ext == ".docx")
{
printSuccess = wordPrintManager.PrintWord(file, printerName, GetPrintSettings());
}
if (printSuccess)
{
UpdatePrintStatus($"✓ {Path.GetFileName(file)} 打印成功");
printJobManager.AddPrintJob(file, printerName, "成功");
}
else
{
UpdatePrintStatus($"✗ {Path.GetFileName(file)} 打印失败");
printJobManager.AddPrintJob(file, printerName, "失败");
success = false;
}
}
catch (Exception ex)
{
UpdatePrintStatus($"✗ {Path.GetFileName(file)} 打印异常: {ex.Message}");
printJobManager.AddPrintJob(file, printerName, $"异常: {ex.Message}");
success = false;
}
}
if (success)
{
MessageBox.Show($"所有文件打印完成!共打印 {selectedFiles.Count} 个文件。", "完成", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
else
{
MessageBox.Show("部分文件打印失败,请查看打印历史了解详情。", "警告", MessageBoxButtons.OK, MessageBoxIcon.Warning);
}
}
private PrintSettings GetPrintSettings()
{
return new PrintSettings
{
Copies = (int)numCopies.Value,
PaperSize = cmbPaperSize.SelectedItem?.ToString() ?? "A4",
Orientation = chkLandscape.Checked ? PrintOrientation.Landscape : PrintOrientation.Portrait,
Duplex = chkDuplex.Checked,
Color = chkColor.Checked
};
}
private void UpdatePrintStatus(string message)
{
txtStatus.AppendText($"[{DateTime.Now:HH:mm:ss}] {message}\r\n");
txtStatus.ScrollToCaret();
Application.DoEvents();
}
private void btnPreview_Click(object sender, EventArgs e)
{
if (selectedFiles.Count == 0)
{
MessageBox.Show("请先选择要预览的文件!", "提示", MessageBoxButtons.OK, MessageBoxIcon.Warning);
return;
}
string file = selectedFiles[0]; // 预览第一个文件
string ext = Path.GetExtension(file).ToLower();
try
{
if (ext == ".pdf")
{
pdfPrintManager.PreviewPdf(file);
}
else if (ext == ".doc" || ext == ".docx")
{
wordPrintManager.PreviewWord(file);
}
}
catch (Exception ex)
{
MessageBox.Show($"预览失败: {ex.Message}", "错误", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
private void btnPrintHistory_Click(object sender, EventArgs e)
{
PrintHistoryForm historyForm = new PrintHistoryForm(printJobManager.GetPrintJobs());
historyForm.ShowDialog();
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private MenuStrip menuStrip1;
private ToolStripMenuItem 文件ToolStripMenuItem;
private ToolStripMenuItem 退出ToolStripMenuItem;
private ToolStripMenuItem 帮助ToolStripMenuItem;
private ToolStripMenuItem 关于ToolStripMenuItem;
private GroupBox groupBox1;
private Button btnBrowseFiles;
private ListBox lstFiles;
private Label lblFileCount;
private Label lblFileTypes;
private GroupBox groupBox2;
private ComboBox cmbPrinters;
private Label label1;
private NumericUpDown numCopies;
private Label label2;
private ComboBox cmbPaperSize;
private Label label3;
private CheckBox chkLandscape;
private CheckBox chkDuplex;
private CheckBox chkColor;
private GroupBox groupBox3;
private Button btnPrint;
private Button btnPreview;
private Button btnPrintHistory;
private TextBox txtStatus;
private Label lblStatus;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.文件ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.退出ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.帮助ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.关于ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.lblFileTypes = new System.Windows.Forms.Label();
this.lblFileCount = new System.Windows.Forms.Label();
this.lstFiles = new System.Windows.Forms.ListBox();
this.btnBrowseFiles = new System.Windows.Forms.Button();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.chkColor = new System.Windows.Forms.CheckBox();
this.chkDuplex = new System.Windows.Forms.CheckBox();
this.chkLandscape = new System.Windows.Forms.CheckBox();
this.cmbPaperSize = new System.Windows.Forms.ComboBox();
this.label3 = new System.Windows.Forms.Label();
this.numCopies = new System.Windows.Forms.NumericUpDown();
this.label2 = new System.Windows.Forms.Label();
this.cmbPrinters = new System.Windows.Forms.ComboBox();
this.label1 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.btnPrintHistory = new System.Windows.Forms.Button();
this.btnPreview = new System.Windows.Forms.Button();
this.btnPrint = new System.Windows.Forms.Button();
this.txtStatus = new System.Windows.Forms.TextBox();
this.lblStatus = new System.Windows.Forms.Label();
this.menuStrip1.SuspendLayout();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.numCopies)).BeginInit();
this.groupBox3.SuspendLayout();
this.SuspendLayout();
// menuStrip1
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.文件ToolStripMenuItem,
this.帮助ToolStripMenuItem});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Size = new System.Drawing.Size(800, 25);
this.menuStrip1.TabIndex = 0;
this.menuStrip1.Text = "menuStrip1";
// 文件ToolStripMenuItem
this.文件ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.退出ToolStripMenuItem});
this.文件ToolStripMenuItem.Name = "文件ToolStripMenuItem";
this.文件ToolStripMenuItem.Size = new System.Drawing.Size(44, 21);
this.文件ToolStripMenuItem.Text = "文件";
// 退出ToolStripMenuItem
this.退出ToolStripMenuItem.Name = "退出ToolStripMenuItem";
this.退出ToolStripMenuItem.Size = new System.Drawing.Size(93, 22);
this.退出ToolStripMenuItem.Text = "退出";
this.退出ToolStripMenuItem.Click += new System.EventHandler(this.退出ToolStripMenuItem_Click);
// 帮助ToolStripMenuItem
this.帮助ToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.关于ToolStripMenuItem});
this.帮助ToolStripMenuItem.Name = "帮助ToolStripMenuItem";
this.帮助ToolStripMenuItem.Size = new System.Drawing.Size(44, 21);
this.帮助ToolStripMenuItem.Text = "帮助";
// 关于ToolStripMenuItem
this.关于ToolStripMenuItem.Name = "关于ToolStripMenuItem";
this.关于ToolStripMenuItem.Size = new System.Drawing.Size(107, 22);
this.关于ToolStripMenuItem.Text = "关于";
this.关于ToolStripMenuItem.Click += new System.EventHandler(this.关于ToolStripMenuItem_Click);
// groupBox1
this.groupBox1.Controls.Add(this.lblFileTypes);
this.groupBox1.Controls.Add(this.lblFileCount);
this.groupBox1.Controls.Add(this.lstFiles);
this.groupBox1.Controls.Add(this.btnBrowseFiles);
this.groupBox1.Location = new System.Drawing.Point(12, 30);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(300, 300);
this.groupBox1.TabIndex = 1;
this.groupBox1.TabStop = false;
this.groupBox1.Text = "选择文件";
// lblFileTypes
this.lblFileTypes.AutoSize = true;
this.lblFileTypes.Location = new System.Drawing.Point(20, 265);
this.lblFileTypes.Name = "lblFileTypes";
this.lblFileTypes.Size = new System.Drawing.Size(67, 13);
this.lblFileTypes.TabIndex = 3;
this.lblFileTypes.Text = "文件类型统计";
// lblFileCount
this.lblFileCount.AutoSize = true;
this.lblFileCount.Location = new System.Drawing.Point(20, 245);
this.lblFileCount.Name = "lblFileCount";
this.lblFileCount.Size = new System.Drawing.Size(67, 13);
this.lblFileCount.TabIndex = 2;
this.lblFileCount.Text = "已选择 0 个文件";
// lstFiles
this.lstFiles.FormattingEnabled = true;
this.lstFiles.Location = new System.Drawing.Point(20, 25);
this.lstFiles.Name = "lstFiles";
this.lstFiles.Size = new System.Drawing.Size(260, 212);
this.lstFiles.TabIndex = 1;
// btnBrowseFiles
this.btnBrowseFiles.Location = new System.Drawing.Point(20, 275);
this.btnBrowseFiles.Name = "btnBrowseFiles";
this.btnBrowseFiles.Size = new System.Drawing.Size(260, 25);
this.btnBrowseFiles.TabIndex = 0;
this.btnBrowseFiles.Text = "浏览文件...";
this.btnBrowseFiles.UseVisualStyleBackColor = true;
this.btnBrowseFiles.Click += new System.EventHandler(this.btnBrowseFiles_Click);
// groupBox2
this.groupBox2.Controls.Add(this.chkColor);
this.groupBox2.Controls.Add(this.chkDuplex);
this.groupBox2.Controls.Add(this.chkLandscape);
this.groupBox2.Controls.Add(this.cmbPaperSize);
this.groupBox2.Controls.Add(this.label3);
this.groupBox2.Controls.Add(this.numCopies);
this.groupBox2.Controls.Add(this.label2);
this.groupBox2.Controls.Add(this.cmbPrinters);
this.groupBox2.Controls.Add(this.label1);
this.groupBox2.Location = new System.Drawing.Point(320, 30);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(300, 200);
this.groupBox2.TabIndex = 2;
this.groupBox2.TabStop = false;
this.groupBox2.Text = "打印设置";
// chkColor
this.chkColor.AutoSize = true;
this.chkColor.Location = new System.Drawing.Point(160, 160);
this.chkColor.Name = "chkColor";
this.chkColor.Size = new System.Drawing.Size(48, 17);
this.chkColor.TabIndex = 8;
this.chkColor.Text = "彩色";
this.chkColor.UseVisualStyleBackColor = true;
// chkDuplex
this.chkDuplex.AutoSize = true;
this.chkDuplex.Location = new System.Drawing.Point(20, 160);
this.chkDuplex.Name = "chkDuplex";
this.chkDuplex.Size = new System.Drawing.Size(72, 17);
this.chkDuplex.TabIndex = 7;
this.chkDuplex.Text = "双面打印";
this.chkDuplex.UseVisualStyleBackColor = true;
// chkLandscape
this.chkLandscape.AutoSize = true;
this.chkLandscape.Location = new System.Drawing.Point(20, 130);
this.chkLandscape.Name = "chkLandscape";
this.chkLandscape.Size = new System.Drawing.Size(72, 17);
this.chkLandscape.TabIndex = 6;
this.chkLandscape.Text = "横向打印";
this.chkLandscape.UseVisualStyleBackColor = true;
// cmbPaperSize
this.cmbPaperSize.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbPaperSize.FormattingEnabled = true;
this.cmbPaperSize.Items.AddRange(new object[] { "A4", "A3", "Letter", "Legal" });
this.cmbPaperSize.Location = new System.Drawing.Point(100, 95);
this.cmbPaperSize.Name = "cmbPaperSize";
this.cmbPaperSize.Size = new System.Drawing.Size(180, 23);
this.cmbPaperSize.TabIndex = 5;
this.cmbPaperSize.SelectedIndex = 0;
// label3
this.label3.AutoSize = true;
this.label3.Location = new System.Drawing.Point(20, 98);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(56, 13);
this.label3.TabIndex = 4;
this.label3.Text = "纸张大小:";
// numCopies
this.numCopies.Location = new System.Drawing.Point(100, 65);
this.numCopies.Maximum = new decimal(new int[] { 100, 0, 0, 0 });
this.numCopies.Minimum = new decimal(new int[] { 1, 0, 0, 0 });
this.numCopies.Name = "numCopies";
this.numCopies.Size = new System.Drawing.Size(180, 23);
this.numCopies.TabIndex = 3;
this.numCopies.Value = new decimal(new int[] { 1, 0, 0, 0 });
// label2
this.label2.AutoSize = true;
this.label2.Location = new System.Drawing.Point(20, 68);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(56, 13);
this.label2.TabIndex = 2;
this.label2.Text = "打印份数:";
// cmbPrinters
this.cmbPrinters.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
this.cmbPrinters.FormattingEnabled = true;
this.cmbPrinters.Location = new System.Drawing.Point(100, 35);
this.cmbPrinters.Name = "cmbPrinters";
this.cmbPrinters.Size = new System.Drawing.Size(180, 23);
this.cmbPrinters.TabIndex = 1;
// label1
this.label1.AutoSize = true;
this.label1.Location = new System.Drawing.Point(20, 38);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(56, 13);
this.label1.TabIndex = 0;
this.label1.Text = "选择打印机:";
// groupBox3
this.groupBox3.Controls.Add(this.btnPrintHistory);
this.groupBox3.Controls.Add(this.btnPreview);
this.groupBox3.Controls.Add(this.btnPrint);
this.groupBox3.Location = new System.Drawing.Point(320, 240);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(300, 90);
this.groupBox3.TabIndex = 3;
this.groupBox3.TabStop = false;
this.groupBox3.Text = "操作";
// btnPrintHistory
this.btnPrintHistory.Location = new System.Drawing.Point(210, 35);
this.btnPrintHistory.Name = "btnPrintHistory";
this.btnPrintHistory.Size = new System.Drawing.Size(70, 25);
this.btnPrintHistory.TabIndex = 2;
this.btnPrintHistory.Text = "打印历史";
this.btnPrintHistory.UseVisualStyleBackColor = true;
this.btnPrintHistory.Click += new System.EventHandler(this.btnPrintHistory_Click);
// btnPreview
this.btnPreview.Location = new System.Drawing.Point(110, 35);
this.btnPreview.Name = "btnPreview";
this.btnPreview.Size = new System.Drawing.Size(70, 25);
this.btnPreview.TabIndex = 1;
this.btnPreview.Text = "预览";
this.btnPreview.UseVisualStyleBackColor = true;
this.btnPreview.Click += new System.EventHandler(this.btnPreview_Click);
// btnPrint
this.btnPrint.Location = new System.Drawing.Point(20, 35);
this.btnPrint.Name = "btnPrint";
this.btnPrint.Size = new System.Drawing.Size(70, 25);
this.btnPrint.TabIndex = 0;
this.btnPrint.Text = "打印";
this.btnPrint.UseVisualStyleBackColor = true;
this.btnPrint.Click += new System.EventHandler(this.btnPrint_Click);
// txtStatus
this.txtStatus.Location = new System.Drawing.Point(12, 340);
this.txtStatus.Multiline = true;
this.txtStatus.Name = "txtStatus";
this.txtStatus.ReadOnly = true;
this.txtStatus.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.txtStatus.Size = new System.Drawing.Size(608, 100);
this.txtStatus.TabIndex = 4;
// lblStatus
this.lblStatus.AutoSize = true;
this.lblStatus.Location = new System.Drawing.Point(12, 325);
this.lblStatus.Name = "lblStatus";
this.lblStatus.Size = new System.Drawing.Size(44, 13);
this.lblStatus.TabIndex = 5;
this.lblStatus.Text = "打印状态:";
// MainForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(632, 452);
this.Controls.Add(this.lblStatus);
this.Controls.Add(this.txtStatus);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.Controls.Add(this.menuStrip1);
this.MainMenuStrip = this.menuStrip1;
this.Name = "MainForm";
this.Text = "文档打印工具 - PDF/Word打印";
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.numCopies)).EndInit();
this.groupBox3.ResumeLayout(false);
this.ResumeLayout(false);
this.PerformLayout();
}
private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void 关于ToolStripMenuItem_Click(object sender, EventArgs e)
{
MessageBox.Show("文档打印工具 v1.0\n\n支持PDF和Word文档打印\n© 2024 版权所有", "关于", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
#endregion
}
}
2.4 PDF打印管理器 (PdfPrintManager.cs)
using System;
using System.Drawing.Printing;
using Spire.Pdf;
using Spire.Pdf.Print;
namespace DocumentPrinter
{
/// <summary>
/// PDF打印管理器
/// </summary>
public class PdfPrintManager
{
/// <summary>
/// 打印PDF文件
/// </summary>
public bool PrintPdf(string filePath, string printerName, PrintSettings settings)
{
try
{
// 使用Spire.PDF打印
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(filePath);
// 设置打印机
pdf.PrintSettings.PrinterName = printerName;
// 设置打印份数
pdf.PrintSettings.Copies = settings.Copies;
// 设置纸张大小
pdf.PrintSettings.PaperSize = GetPaperSize(settings.PaperSize);
// 设置打印方向
pdf.PrintSettings.Landscape = settings.Orientation == PrintOrientation.Landscape;
// 设置双面打印
pdf.PrintSettings.Duplex = settings.Duplex ? Duplex.Horizontal : Duplex.Simplex;
// 设置颜色
pdf.PrintSettings.Color = settings.Color;
// 执行打印
pdf.Print();
return true;
}
catch (Exception ex)
{
throw new Exception($"PDF打印失败: {ex.Message}", ex);
}
}
/// <summary>
/// 预览PDF文件
/// </summary>
public void PreviewPdf(string filePath)
{
try
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(filePath);
// 使用Spire.PDF的预览功能
pdf.PrintSettings.PrintController = new StandardPrintController();
pdf.PrintSettings.PrinterName = "";
pdf.PrintSettings.SelectSinglePageLayout(PdfPageScalingMode.FitSize, true);
// 显示打印预览对话框
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = pdf.PrintSettings.PrintDocument;
previewDialog.ShowDialog();
}
catch (Exception ex)
{
throw new Exception($"PDF预览失败: {ex.Message}", ex);
}
}
/// <summary>
/// 获取纸张大小
/// </summary>
private PaperSize GetPaperSize(string paperSizeName)
{
switch (paperSizeName.ToUpper())
{
case "A4":
return new PaperSize("A4", 827, 1169); // 210mm × 297mm (以1/100英寸为单位)
case "A3":
return new PaperSize("A3", 1169, 1654); // 297mm × 420mm
case "LETTER":
return new PaperSize("Letter", 850, 1100); // 8.5" × 11"
case "LEGAL":
return new PaperSize("Legal", 850, 1400); // 8.5" × 14"
default:
return new PaperSize("A4", 827, 1169);
}
}
/// <summary>
/// 获取PDF页数
/// </summary>
public int GetPageCount(string filePath)
{
try
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(filePath);
return pdf.Pages.Count;
}
catch
{
return 0;
}
}
/// <summary>
/// 打印指定页面范围
/// </summary>
public bool PrintPageRange(string filePath, string printerName, PrintSettings settings, int startPage, int endPage)
{
try
{
PdfDocument pdf = new PdfDocument();
pdf.LoadFromFile(filePath);
pdf.PrintSettings.PrinterName = printerName;
pdf.PrintSettings.Copies = settings.Copies;
pdf.PrintSettings.PageRange = new PdfPageRange(startPage, endPage);
pdf.Print();
return true;
}
catch (Exception ex)
{
throw new Exception($"打印页面范围失败: {ex.Message}", ex);
}
}
}
}
2.5 Word打印管理器 (WordPrintManager.cs)
using System;
using Spire.Doc;
using Spire.Doc.Printing;
namespace DocumentPrinter
{
/// <summary>
/// Word打印管理器
/// </summary>
public class WordPrintManager
{
/// <summary>
/// 打印Word文件
/// </summary>
public bool PrintWord(string filePath, string printerName, PrintSettings settings)
{
try
{
// 使用Spire.Doc打印
Document document = new Document();
document.LoadFromFile(filePath);
// 设置打印机
document.PrintDocument.PrinterSettings.PrinterName = printerName;
// 设置打印份数
document.PrintDocument.PrinterSettings.Copies = settings.Copies;
// 设置纸张大小
document.PrintDocument.PrinterSettings.PaperSize = GetPaperSize(settings.PaperSize);
// 设置打印方向
document.PrintDocument.PrinterSettings.Landscape = settings.Orientation == PrintOrientation.Landscape;
// 设置双面打印
document.PrintDocument.PrinterSettings.Duplex = settings.Duplex ? Duplex.Horizontal : Duplex.Simplex;
// 执行打印
document.PrintDocument.Print();
return true;
}
catch (Exception ex)
{
throw new Exception($"Word打印失败: {ex.Message}", ex);
}
}
/// <summary>
/// 预览Word文件
/// </summary>
public void PreviewWord(string filePath)
{
try
{
Document document = new Document();
document.LoadFromFile(filePath);
// 显示打印预览
PrintPreviewDialog previewDialog = new PrintPreviewDialog();
previewDialog.Document = document.PrintDocument;
previewDialog.ShowDialog();
}
catch (Exception ex)
{
throw new Exception($"Word预览失败: {ex.Message}", ex);
}
}
/// <summary>
/// 获取纸张大小
/// </summary>
private System.Drawing.Printing.PaperSize GetPaperSize(string paperSizeName)
{
switch (paperSizeName.ToUpper())
{
case "A4":
return new System.Drawing.Printing.PaperSize("A4", 827, 1169);
case "A3":
return new System.Drawing.Printing.PaperSize("A3", 1169, 1654);
case "LETTER":
return new System.Drawing.Printing.PaperSize("Letter", 850, 1100);
case "LEGAL":
return new System.Drawing.Printing.PaperSize("Legal", 850, 1400);
default:
return new System.Drawing.Printing.PaperSize("A4", 827, 1169);
}
}
/// <summary>
/// 打印指定页面
/// </summary>
public bool PrintSpecificPages(string filePath, string printerName, PrintSettings settings, string pageRange)
{
try
{
Document document = new Document();
document.LoadFromFile(filePath);
document.PrintDocument.PrinterSettings.PrinterName = printerName;
document.PrintDocument.PrinterSettings.Copies = settings.Copies;
// 设置页面范围 (例如: "1-3,5,7-9")
document.PrintDocument.PrinterSettings.PageRanges.Clear();
document.PrintDocument.PrinterSettings.PageRanges.Add(new PageRange(pageRange));
document.PrintDocument.Print();
return true;
}
catch (Exception ex)
{
throw new Exception($"打印指定页面失败: {ex.Message}", ex);
}
}
/// <summary>
/// 获取Word文档页数
/// </summary>
public int GetPageCount(string filePath)
{
try
{
Document document = new Document();
document.LoadFromFile(filePath);
return document.PageCount;
}
catch
{
return 0;
}
}
}
}
2.6 打印任务管理 (PrintJob.cs)
using System;
using System.Collections.Generic;
namespace DocumentPrinter
{
/// <summary>
/// 打印设置
/// </summary>
public class PrintSettings
{
public int Copies { get; set; } = 1;
public string PaperSize { get; set; } = "A4";
public PrintOrientation Orientation { get; set; } = PrintOrientation.Portrait;
public bool Duplex { get; set; } = false;
public bool Color { get; set; } = true;
}
/// <summary>
/// 打印方向
/// </summary>
public enum PrintOrientation
{
Portrait,
Landscape
}
/// <summary>
/// 打印任务
/// </summary>
public class PrintJob
{
public int Id { get; set; }
public string FileName { get; set; } = "";
public string PrinterName { get; set; } = "";
public DateTime PrintTime { get; set; } = DateTime.Now;
public string Status { get; set; } = "";
public int Pages { get; set; } = 0;
public string FilePath { get; set; } = "";
}
/// <summary>
/// 打印任务管理器
/// </summary>
public class PrintJobManager
{
private List<PrintJob> printJobs = new List<PrintJob>();
private int nextId = 1;
/// <summary>
/// 添加打印任务
/// </summary>
public void AddPrintJob(string filePath, string printerName, string status)
{
var job = new PrintJob
{
Id = nextId++,
FileName = System.IO.Path.GetFileName(filePath),
PrinterName = printerName,
PrintTime = DateTime.Now,
Status = status,
FilePath = filePath
};
printJobs.Add(job);
// 只保留最近100条记录
if (printJobs.Count > 100)
{
printJobs.RemoveAt(0);
}
}
/// <summary>
/// 获取所有打印任务
/// </summary>
public List<PrintJob> GetPrintJobs()
{
return new List<PrintJob>(printJobs);
}
/// <summary>
/// 清空打印历史
/// </summary>
public void ClearHistory()
{
printJobs.Clear();
nextId = 1;
}
}
}
2.7 打印机工具类 (PrinterUtils.cs)
using System.Collections.Generic;
using System.Drawing.Printing;
namespace DocumentPrinter
{
/// <summary>
/// 打印机工具类
/// </summary>
public static class PrinterUtils
{
/// <summary>
/// 获取所有已安装的打印机
/// </summary>
public static List<string> GetInstalledPrinters()
{
var printers = new List<string>();
foreach (string printer in PrinterSettings.InstalledPrinters)
{
printers.Add(printer);
}
return printers;
}
/// <summary>
/// 获取默认打印机
/// </summary>
public static string GetDefaultPrinter()
{
return new PrinterSettings().PrinterName;
}
/// <summary>
/// 检查打印机是否存在
/// </summary>
public static bool PrinterExists(string printerName)
{
var printers = GetInstalledPrinters();
return printers.Contains(printerName);
}
/// <summary>
/// 获取打印机支持的纸张大小
/// </summary>
public static List<string> GetSupportedPaperSizes(string printerName)
{
var paperSizes = new List<string>();
try
{
var printerSettings = new PrinterSettings();
printerSettings.PrinterName = printerName;
foreach (PaperSize paperSize in printerSettings.PaperSizes)
{
paperSizes.Add(paperSize.PaperName);
}
}
catch
{
// 返回默认纸张大小
paperSizes.AddRange(new[] { "A4", "A3", "Letter", "Legal" });
}
return paperSizes;
}
/// <summary>
/// 测试打印机
/// </summary>
public static bool TestPrinter(string printerName)
{
try
{
var printerSettings = new PrinterSettings();
printerSettings.PrinterName = printerName;
// 尝试打印测试页
printerSettings.PrintToFile = false;
return printerSettings.IsValid;
}
catch
{
return false;
}
}
}
}
2.8 打印历史窗体 (PrintHistoryForm.cs)
using System;
using System.Collections.Generic;
using System.Windows.Forms;
namespace DocumentPrinter
{
public partial class PrintHistoryForm : Form
{
private List<PrintJob> printJobs;
public PrintHistoryForm(List<PrintJob> jobs)
{
InitializeComponent();
printJobs = jobs;
LoadPrintHistory();
}
private void LoadPrintHistory()
{
dataGridView.DataSource = printJobs;
// 设置列标题
if (dataGridView.Columns.Count > 0)
{
dataGridView.Columns["Id"].HeaderText = "ID";
dataGridView.Columns["FileName"].HeaderText = "文件名";
dataGridView.Columns["PrinterName"].HeaderText = "打印机";
dataGridView.Columns["PrintTime"].HeaderText = "打印时间";
dataGridView.Columns["Status"].HeaderText = "状态";
dataGridView.Columns["Pages"].HeaderText = "页数";
dataGridView.Columns["FilePath"].Visible = false; // 隐藏文件路径列
}
}
#region Windows Form Designer generated code
private System.ComponentModel.IContainer components = null;
private DataGridView dataGridView;
private Button btnClear;
private Button btnClose;
private Label lblTotalJobs;
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.dataGridView = new System.Windows.Forms.DataGridView();
this.btnClear = new System.Windows.Forms.Button();
this.btnClose = new System.Windows.Forms.Button();
this.lblTotalJobs = new System.Windows.Forms.Label();
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).BeginInit();
this.SuspendLayout();
// dataGridView
this.dataGridView.AllowUserToAddRows = false;
this.dataGridView.AllowUserToDeleteRows = false;
this.dataGridView.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dataGridView.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dataGridView.Location = new System.Drawing.Point(12, 12);
this.dataGridView.Name = "dataGridView";
this.dataGridView.ReadOnly = true;
this.dataGridView.Size = new System.Drawing.Size(560, 300);
this.dataGridView.TabIndex = 0;
// btnClear
this.btnClear.Location = new System.Drawing.Point(402, 322);
this.btnClear.Name = "btnClear";
this.btnClear.Size = new System.Drawing.Size(80, 30);
this.btnClear.TabIndex = 1;
this.btnClear.Text = "清空历史";
this.btnClear.UseVisualStyleBackColor = true;
this.btnClear.Click += new System.EventHandler(this.btnClear_Click);
// btnClose
this.btnClose.Location = new System.Drawing.Point(492, 322);
this.btnClose.Name = "btnClose";
this.btnClose.Size = new System.Drawing.Size(80, 30);
this.btnClose.TabIndex = 2;
this.btnClose.Text = "关闭";
this.btnClose.UseVisualStyleBackColor = true;
this.btnClose.Click += new System.EventHandler(this.btnClose_Click);
// lblTotalJobs
this.lblTotalJobs.AutoSize = true;
this.lblTotalJobs.Location = new System.Drawing.Point(12, 328);
this.lblTotalJobs.Name = "lblTotalJobs";
this.lblTotalJobs.Size = new System.Drawing.Size(67, 13);
this.lblTotalJobs.TabIndex = 3;
this.lblTotalJobs.Text = "共 0 条记录";
// PrintHistoryForm
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(584, 364);
this.Controls.Add(this.lblTotalJobs);
this.Controls.Add(this.btnClose);
this.Controls.Add(this.btnClear);
this.Controls.Add(this.dataGridView);
this.Name = "PrintHistoryForm";
this.Text = "打印历史";
((System.ComponentModel.ISupportInitialize)(this.dataGridView)).EndInit();
this.ResumeLayout(false);
this.PerformLayout();
}
private void btnClear_Click(object sender, EventArgs e)
{
if (MessageBox.Show("确定要清空所有打印历史吗?", "确认", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
{
printJobs.Clear();
LoadPrintHistory();
lblTotalJobs.Text = "共 0 条记录";
}
}
private void btnClose_Click(object sender, EventArgs e)
{
this.Close();
}
#endregion
}
}
三、替代方案(不使用第三方库)
如果您不想使用 Spire 库,可以使用以下替代方案:
3.1 使用 Microsoft Office Interop(需要安装 Office)
// 需要在项目中添加 Microsoft.Office.Interop.Word 引用
using Microsoft.Office.Interop.Word;
public class WordInteropPrinter
{
public bool PrintWordWithInterop(string filePath, string printerName)
{
Application wordApp = null;
Document document = null;
try
{
wordApp = new Application();
wordApp.Visible = false;
document = wordApp.Documents.Open(filePath);
wordApp.ActivePrinter = printerName;
document.PrintOut();
return true;
}
catch (Exception ex)
{
throw new Exception($"Word打印失败: {ex.Message}", ex);
}
finally
{
if (document != null)
{
document.Close();
System.Runtime.InteropServices.Marshal.ReleaseComObject(document);
}
if (wordApp != null)
{
wordApp.Quit();
System.Runtime.InteropServices.Marshal.ReleaseComObject(wordApp);
}
}
}
}
3.2 使用 PdfiumViewer(免费 PDF 库)
// 需要在项目中添加 PdfiumViewer 引用
using PdfiumViewer;
public class PdfiumPrinter
{
public bool PrintPdfWithPdfium(string filePath, string printerName)
{
try
{
using var document = PdfDocument.Load(filePath);
using var printDocument = document.CreatePrintDocument();
printDocument.PrinterSettings.PrinterName = printerName;
printDocument.Print();
return true;
}
catch (Exception ex)
{
throw new Exception($"PDF打印失败: {ex.Message}", ex);
}
}
}
参考代码 C#打印pdf文档/word文档 www.youwenfan.com/contentcsv/116223.html
四、功能特点
多格式支持:PDF、Word (.doc/.docx)、RTF 文档
打印机管理:自动检测可用打印机,支持选择指定打印机
打印设置:份数、纸张大小、方向、双面打印、彩色/黑白
批量打印:支持同时打印多个文档
打印预览:实时预览文档内容
打印历史:记录打印任务,方便追溯
错误处理:详细的错误信息和日志记录
第三方库集成:使用 Spire.PDF 和 Spire.Doc,功能强大
五、使用说明
5.1 快速开始
- 运行程序,点击"浏览文件"选择要打印的文档
- 选择打印机
- 设置打印参数(份数、纸张大小等)
- 点击"打印"按钮
5.2 批量打印
- 在文件选择对话框中按住 Ctrl 或 Shift 选择多个文件
- 设置打印参数
- 点击"打印"按钮,系统会自动按顺序打印所有文件
5.3 打印预览
- 选择一个文件
- 点击"预览"按钮查看文档内容
- 确认无误后再进行打印
5.4 注意事项
- Spire 库免费版有页数限制(PDF 10页,Word 3页)和水印
- 如需无限制使用,请购买商业许可
- 确保打印机已正确安装并可以正常工作