C#使用PrintDocument类生成PDF并加水印
例如:根据现有的纸质文档设计其电子文档PDF,并能上抛。
C#使用PrintDocument类生成PDF并加水印
C#使用PrintDocument类生成PDF并加水印
一、需求分析
需求:
- 根据现有的生产打印小票,设计电子文档PDF并将数据显示。
- 直接生成到本地文件或者使用对话框,需加LOGO以及文字水印。
提示:以下是本篇文章正文内容,下面案例可供参考
二、具体实现
step1.引入库和命名空间
引入System.Drawing命名空间:using System.Drawing;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Printing;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
step2.已经封装好的方法
两个关键函数:PrintDocumentPrint()和PrintDocumentPrintPage
具体的注释都在代码中
//两个全局变量
PDFPoundEntity throwFDFDataShow = new PDFPoundEntity();//显示打印内容全局变量
string upFildName = "";//存储本地pdf路径
/// <summary>
/// 调用PrintController和printDocument生成PDF文件
/// </summary>
void PrintDocumentPrint()
{
//PrintController:控制一个PrintDocument是如何打印的。
PrintDocument printDocument1 = new PrintDocument();
//需要为当前页打印内容发生的函数
printDocument1.PrintPage += new PrintPageEventHandler(PrintDocumentPrintPage);
PrintController printController = new StandardPrintController();
//获取或设置指导打印进程的打印控制器
printDocument1.PrintController = printController;
// 加入打印页面的设置处理
//设置为PDF打印
//printDocument1.PrinterSettings.PrinterName = "Microsoft Print to PDF";
//printDocument1.DocumentName = "计量单.pdf";
try
{
string pathName = @"C:\NTPoundPDF";
string fileName = @"C:\NTPoundPDF\磅单号为 " + throwFDFDataShow.measureListNo + @" 南通计量单 " + throwFDFDataShow.BusinessTypeText + ".pdf";
upFildName = fileName;
//string fileName = @"C:\NTPoundPDF\TestPrinting2.pdf";
if (!Directory.Exists(pathName))
{
Directory.CreateDirectory(pathName);//在指定路径创建文件夹
}
if (!File.Exists(fileName))
{
printDocument1.PrinterSettings.PrintFileName = fileName;//设置保存文件路径和名字
}
else
{
LogFile.WriteLogLine($"磅单号为:{
throwFDFDataShow.measureListNo} 的计量单的pdf已存在!");
return;