C# 使用PrintDocument类生成PDF并加水印

C#使用PrintDocument类生成PDF并加水印

例如:根据现有的纸质文档设计其电子文档PDF,并能上抛。


一、需求分析

需求:

  1. 根据现有的生产打印小票,设计电子文档PDF并将数据显示
  2. 直接生成到本地文件或者使用对话框,需加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;
        }
        printDocument1.PrinterSettings.PrinterName = "Microsoft Print to PDF";//打印机名字
                                                                              //是否获取或设置一个值,该值指示打印输出是否发送到文件,而不发送到端口
        printDocument1.PrinterSettings.PrintToFile = true;
        printDocument1.Print(); // 触发PrintPage事件。 
    }
    catch (Exception ex)
    {
        LogFile.WriteLogLine(ex.Message);
        LogFile.WriteLogLine($"计量单生成文件pdf {ex.Message}");
        //printDocument1.PrintController.OnEndPrint(printDocument1, new PrintEventArgs());
    }
}
/// <summary>
/// 打印内容方法。需要打印新的一页时发生,负责打印一页所需要的数据,打印调用该事件,打印内容就是此处设置好的内容。
/// </summary>
/// <param name="sender"></param>
/// <param name="e"> 打印内容参数</param>
void PrintDocumentPrintPage(object sender, PrintPageEventArgs e)
{
    int x = 50;//x轴位置
    int y = 240;//y轴位置
    Font TitleFont = new Font("宋体", 20, FontStyle.Bold);//设置字体格式
    SolidBrush TitleBrush = new SolidBrush(Color.Black);
    Pen pen = new Pen(Color.Black, 2);//线条颜色
    try
    {
        //e.HasMorePages = true;//开启多页打印
                              //Image iamge = Image.FromFile("YCJL.UI.Resources.logo2.png");//加载本地图片
        Image iamge = Properties.Resources.logo2; //加载项目资源图片

        e.Graphics.DrawString("中 天 钢 铁 集 团 (南通) 有 限 公 司", new Font("宋体", 22, FontStyle.Bold), TitleBrush, new Point(160, 50));
        //PointF 结构数组,这些结构表示要连接的点
        Point[] points = { new Point(160, 85), new Point(730, 85) };
        //绘制一系列连接一组 PointF 结构的线段
        e.Graphics.DrawLines(pen, points);
        e.Graphics.DrawString("南通计量单  " + throwFDFDataShow.BusinessTypeText, new Font("黑体", 35, FontStyle.Bold), TitleBrush, new Point(200, 140));

        e.Graphics.DrawString("磅单号: " + throwFDFDataShow.measureListNo, TitleFont, Brushes.Black, new Point(x, y));
        e.Graphics.DrawString("订单号: " + throwFDFDataShow.OrderNo, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("车号: " + throwFDFDataShow.CarrierNo, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("船号: " + throwFDFDataShow.BoatNo, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("来源: " + throwFDFDataShow.SendUnitName, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("去向: " + throwFDFDataShow.RecvUnitName, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("收货点: " + throwFDFDataShow.RecvPlaceName, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("发货点: " + throwFDFDataShow.SendPlaceName, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("物料编号: " + throwFDFDataShow.MatNo, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("物料名称: " + throwFDFDataShow.MatName, TitleFont, Brushes.Black, new Point(x, y += 50));
        //分割线
        Point[] points111 = { new Point(0, y + 50), new Point(1000, y + 50) };
        e.Graphics.DrawLines(pen, points111);

        e.Graphics.DrawString("毛重: " + throwFDFDataShow.MeasureWgt2, TitleFont, Brushes.Black, new Point(x, y += 70));
        e.Graphics.DrawString("计量点: " + throwFDFDataShow.MeasureSiteNo2, TitleFont, Brushes.Black, new Point(x + 300, y));
        e.Graphics.DrawString("皮重: " + throwFDFDataShow.MeasureWgt1, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("计量点: " + throwFDFDataShow.MeasureSiteNo1, TitleFont, Brushes.Black, new Point(x + 300, y));
        e.Graphics.DrawString("净重: " + throwFDFDataShow.MatWgt, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("时间: " + throwFDFDataShow.CreateTime, TitleFont, Brushes.Black, new Point(x + 300, y));
        e.Graphics.DrawString("扣重: " + throwFDFDataShow.DeductWgt, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("废钢等级: " + throwFDFDataShow.SteelLevelName, TitleFont, Brushes.Black, new Point(x + 300, y));

        e.Graphics.DrawString("收发货人: " + throwFDFDataShow.OperatorName, TitleFont, Brushes.Black, new Point(x, y += 50));
        e.Graphics.DrawString("计量单位: kg", TitleFont, Brushes.Black, new Point(x + 300, y));
        //在指定位置并且按指定大小绘制指定的 Image,
        e.Graphics.DrawImage(iamge, 30, 30, 100, 120);

        //加文字水印
        string text = string.Format("ZENITH");
        Font crFont = new Font("微软雅黑", 57, FontStyle.Bold);
        SolidBrush semiTransBrush = new SolidBrush(Color.FromArgb(60, 137, 131, 131));
        //将原点移动 到位置中点
        e.Graphics.TranslateTransform(0, 50);
        //以原点为中心 转 -45度
        e.Graphics.RotateTransform(-45);
        for (int j = 0; j < 10; j++)
        {
            e.Graphics.DrawString(text, crFont, semiTransBrush, new PointF(0 - j * 300, 100 + j * 300));
            e.Graphics.DrawString(text, crFont, semiTransBrush, new PointF(150 - j * 300, 500 + j * 300));
            e.Graphics.DrawString(text, crFont, semiTransBrush, new PointF(650 - j * 300, 600 + j * 300));
        }
    }
    catch (Exception ee)
    {
        LogFile.WriteLogLine(ee.Message);
        LogFile.WriteLogLine($"显示PDF内容错误 {ee.Message}");
    }
}
  • 0
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
C#实现生成PDF文档(附源码) 收藏 //write by wenhui.org using System; using System.IO; using System.Text; using System.Collections; namespace PDFGenerator { public class PDFGenerator { static float pageWidth = 594.0f; static float pageDepth = 828.0f; static float pageMargin = 30.0f; static float fontSize = 20.0f; static float leadSize = 10.0f; static StreamWriter pPDF=new StreamWriter("E:\myPDF.pdf"); static MemoryStream mPDF= new MemoryStream(); static void ConvertToByteAndAddtoStream(string strMsg) { Byte[] buffer=null; buffer=ASCIIEncoding.ASCII.GetBytes(strMsg); mPDF.Write(buffer,0,buffer.Length); buffer=null; } static string xRefFormatting(long xValue) { string strMsg =xValue.ToString(); int iLen=strMsg.Length; if (iLen<10) { StringBuilder s=new StringBuilder(); int i=10-iLen; s.Append('0',i); strMsg=s.ToString() + strMsg; } return strMsg; } static void Main(string[] args) { ArrayList xRefs=new ArrayList(); //Byte[] buffer=null; float yPos =0f; long streamStart=0; long streamEnd=0; long streamLen =0; string strPDFMessage=null; //PDF文档头信息 strPDFMessage="%PDF-1.1 "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="1 0 obj "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="<> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="stream "; ConvertToByteAndAddtoStream(strPDFMessage); ////////PDF文档描述 streamStart=mPDF.Length; //字体 strPDFMessage="BT /F0 " + fontSize +" Tf "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档实体高度 yPos = pageDepth - pageMargin; strPDFMessage=pageMargin + " " + yPos +" Td " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= leadSize+" TL " ; ConvertToByteAndAddtoStream(strPDFMessage); //实体内容 strPDFMessage= "(http://www.wenhui.org)Tj " ; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage= "ET "; ConvertToByteAndAddtoStream(strPDFMessage); streamEnd=mPDF.Length; streamLen=streamEnd-streamStart; strPDFMessage= "endstream endobj "; ConvertToByteAndAddtoStream(strPDFMessage); //PDF文档的版本信息 xRefs.Add(mPDF.Length); strPDFMessage="2 0 obj "+ streamLen + " endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="3 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="4 0 obj <</Type /Pages /Count 1 "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Kids[ 3 0 R ] "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/Resources<</ProcSet[/PDF/Text]/Font<> >> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="/MediaBox [ 0 0 "+ pageWidth + " " + pageDepth + " ] >> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="5 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); xRefs.Add(mPDF.Length); strPDFMessage="6 0 obj <> endobj "; ConvertToByteAndAddtoStream(strPDFMessage); streamStart=mPDF.Length; strPDFMessage="xref 0 7 0000000000 65535 f "; for(int i=0;i<xRefs.Count;i++) { strPDFMessage+=xRefFormatting((long) xRefs[i])+" 00000 n "; } ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="trailer <> "; ConvertToByteAndAddtoStream(strPDFMessage); strPDFMessage="startxref " + streamStart+" %%EOF "; ConvertToByteAndAddtoStream(strPDFMessage); mPDF.WriteTo(pPDF.BaseStream); mPDF.Close(); pPDF.Close(); } } }

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值