C# Spire.PDF 实现pdf文件盖章

发布时间 2023-05-05 14:58:43作者: 流纹

1、添加引用

通过Spire.PDF实现合同盖章,社区版dll(免费,但是只支持10页以内的pdf文档),也可以直接通过VS管理NuGet包添加dll引用,
收费版直接搜索Spire.PDF安装,免费社区版搜索FreeSpire.PDF安装

2、参数定义与调用

string pdfPath = "C:\\Users\\Administrator\\Desktop\\2月份工作报告.pdf";
string imagePath = "C:\\Users\\Administrator\\Desktop\\图片\\20230314161221.jpg";
string outputPath = "C:\\Users\\Administrator\\Desktop\\测试签名文件.pdf";
CreateSign(pdfPath, imagePath, outputPath, 400, 650);

3、具体盖章实现

        /// <summary>
        ///  pdf盖章
        ///  Spire.PDF——收费商用版
        ///  FreeSpire.PDF——免费社区版,但只支持10页以内的pdf文件
        /// </summary>
        /// <param name="pdfPath">源Pdf文件地址</param>
        /// <param name="imagePath">盖章图片地址</param>heng'xiang
        /// <param name="outputPath">盖章后重新生成的pdf地址</param>
        /// <param name="driftX">盖章图片横向偏移</param>
        /// <param name="driftY">盖章图片竖向偏移</param>
        /// <returns></returns>
        public static void CreateSign(string pdfPath, string imagePath, string outputPath, float driftX, float driftY)
        {
            //创建一个PdfDocument类对象,并加载PDF文档
            Spire.Pdf.PdfDocument doc = new Spire.Pdf.PdfDocument();
            doc.LoadFromFile(pdfPath);
            //文档最后一页
            Spire.Pdf.PdfPageBase page = doc.Pages[doc.Pages.Count - 1];
            //新建一个PdfRubberStampAnnotation对象,指定其注释的位置和大小
            Spire.Pdf.Annotations.PdfRubberStampAnnotation loStamp =
            new Spire.Pdf.Annotations.PdfRubberStampAnnotation(
                new System.Drawing.RectangleF(
                    //盖章偏移
                    new System.Drawing.PointF(driftX, driftY),
                    //盖章图片大小
                    new System.Drawing.SizeF(80, 80))
                );
            //实例化一个PdfAppearance对象,并加载作为印章的图片
            Spire.Pdf.Annotations.Appearance.PdfAppearance loApprearance = new Spire.Pdf.Annotations.Appearance.PdfAppearance(loStamp);
            Spire.Pdf.Graphics.PdfImage image = Spire.Pdf.Graphics.PdfImage.FromFile(imagePath);
            //新建一个PDF模板,并在模板里绘制图片
            Spire.Pdf.Graphics.PdfTemplate template = new Spire.Pdf.Graphics.PdfTemplate(150, 150);
            template.Graphics.DrawImage(image, 0, 0);
            loApprearance.Normal = template;
            loStamp.Appearance = loApprearance;
            //添加印章到PDF文档
            page.AnnotationsWidget.Add(loStamp);
            //保存文档
            doc.SaveToFile(outputPath);
            //直接打开文档
            System.Diagnostics.Process.Start(outputPath);
        }
View Code

4、最终效果