c#winform打印设置好的模版文件示例
时间: 2024-10-25 22:07:59 浏览: 63
在C# WinForms中,要设置并打印预定义模板文件,你可以使用`System.Drawing.Printing`命名空间下的`PrintDocument`类。下面是一个简单的示例,说明如何创建`PrintDocument`实例、设置页面范围、选择模板以及最后进行打印:
```csharp
using System;
using System.Drawing.Printing;
public class PrintTemplateExample
{
private void PrintDocument_PrintPage(object sender, PrintPageEventArgs e)
{
// 获取模板路径
string templatePath = @"C:\Templates\MyTemplate.docx"; // 替换为你实际的模板文件路径
// 创建一个模板文档
Microsoft.Office.Interop.Word.Document doc = new Microsoft.Office.Interop.Word.Document();
try
{
doc.Open(templatePath);
int pageCount = doc.PageSetup.Pages.Count; // 获取模板文件总页数
// 设置打印范围,这里假设你想打印整个模板
e.Graphics.DrawImage(doc.GetPicture(pageCount - 1), 0, 0); // 把最后一个页面的内容画到PrintPageEventArgs的图形上下文中
}
catch (Exception ex)
{
Console.WriteLine($"Error opening template: {ex.Message}");
}
finally
{
doc.Close();
}
}
public void PrintWithTemplate()
{
PrintDocument pd = new PrintDocument();
pd.PrintPage += PrintDocument_PrintPage;
// 配置打印设置
PrintDialog printDialog = new PrintDialog();
if (printDialog.ShowDialog() == DialogResult.OK)
{
pd.PrinterSettings = printDialog.PrinterSettings;
pd.Print();
}
}
}
// 调用函数
private void button_Click(object sender, EventArgs e)
{
PrintTemplateExample example = new PrintTemplateExample();
example.PrintWithTemplate();
}
```
在这个例子中,我们首先打开Word模板文件,并获取它的页数。然后在`PrintPage`事件处理程序中,我们读取并画出模板的最后一张图片到页面上。在`PrintWithTemplate`方法中,设置了打印对话框让用户选择打印机,并触发了打印操作。
阅读全文
相关推荐


















