C# 利用itextsharp、Spire配合使用为pdf文档每页添加水印

下载类库:

直接下载

引入类库

功能实现

using iTextSharp.text.pdf;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System;
using System.Drawing;
using System.Windows.Forms;
using PdfDocument = Spire.Pdf.PdfDocument;
using PdfFont = Spire.Pdf.Graphics.PdfFont;

namespace ProcessPdfDemo
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Button1_Click(object sender, EventArgs e)
        {
            string fileName = @"C:\Users\Administrator\Desktop\图纸\WH440-H111-F01_111分段结构图.pdf";
            //创建一个新的PDF实例,导入PDF文件            
            PdfDocument pdf = new PdfDocument();
            pdf.LoadFromFile(fileName);
            PdfPageBase pb = pdf.Pages.Add(); //新增一页
            pdf.Pages.Remove(pb); //去除第一页水印
            for (int i = 0; i < GetPdfPageNum(fileName); i++)
            {
                PdfPageBase page = pdf.Pages[i];                
                //添加文本水印到文件的第一页,设置文本格式
                PdfTilingBrush brush = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 3, page.Canvas.ClientSize.Height / 3)); //设置每行每列几个水印
                brush.Graphics.SetTransparency(0.2f); //透明度
                brush.Graphics.Save();
                brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);
                brush.Graphics.RotateTransform(-45); //旋转角度
                brush.Graphics.DrawString("Draft Version", new PdfFont(PdfFontFamily.Helvetica, 40), PdfBrushes.Blue, 0, 0, new PdfStringFormat(PdfTextAlignment.Center));
                brush.Graphics.Restore();
                brush.Graphics.SetTransparency(1);
                page.Canvas.DrawRectangle(brush, new RectangleF(new PointF(0, 0), page.Canvas.ClientSize));
            }
            //保存文件
            pdf.SaveToFile(@"C:\Users\Administrator\Desktop\图纸\2222.pdf");
            MessageBox.Show("ok");
        }
        /// <summary>
        /// 获取pdf页数
        /// </summary>
        /// <param name="pdfFile"></param>
        /// <returns></returns>
        public int GetPdfPageNum(string pdfFile)
        {
            PdfReader reader = new PdfReader(pdfFile);
            int iPageNum = reader.NumberOfPages;
            reader.Close(); //不关闭会一直占用pdf资源,对接下来的操作会有影响
            return iPageNum;
        }
    }
}

效果

 

posted @ 2019-10-30 15:30  陈彦斌  阅读(2472)  评论(1编辑  收藏  举报