当我们在网上共享 PDF 文件时,重要的是要让屏幕另一侧的人相信发布的信息是正确的。毕竟,任何文件都可以被攻击者截获并进行修改。带有你的标志或特定文本的水印 PDF 将证明文件的真实性,并为将要发送给的每个人证明其安全性。
我们将在本文中详细介绍应用水印 PDF 的方法。本文将分为三个部分,详细为您介绍如何通过 C#/VB.NET 代码将文本/图像水印添加到 PDF 文档。想要实现此功能,只需执行几个简单的步骤。详情请阅读以下内容。
 
程序环境:
本次测试时,在程序中引入 Spire.PDF.dll 文件。
 
方法 1:
将 FreeSpire.PDF for .NET 下载到本地,解压,找到 BIN 文件夹下的 Spire.PDF.dll。然后在 Visual Studio 中打开“解决方案资源管理器”,鼠标右键点击“引用”,“添加引用”,将本地路径 BIN 文件夹下的 dll 文件添加引用至程序。
 
方法 2:
通过 NuGet 安装。可通过以下 2 种方法安装:
 
  1. 可以在 Visual Studio 中打开“解决方案资源管理器”,鼠标右键点击“引用”,“管理 NuGet 包”,然后搜索“Free Spire.PDF”,点击“安装”。等待程序安装完成。
 
  2. 将以下内容复制到 PM 控制台安装。
 
Install-Package FreeSpire.PDF-Version 8.6.0
给 PDF 文档添加文本水印
具体步骤:
- 创建 PdfDocument 对象并用 PdfDocument.LoadFromFile()方法加载示例文档。 
- 用 PdfFontBase.MeasureString()方法设置水印文字和测量文字大小。 
- 浏览文档中的所有页面。 
- 使用 PdfPageBase.Canvas.TraslateTransform()方法将某个页面的坐标系平移指定坐标,使用 PdfPageBase.Canvas.RotateTransform() 方法将坐标系逆时针旋转 45 度。 
- 使用 PdfPageBase.Canvas.DrawString()方法在页面上绘制水印文字。 
- 用 PdfDocument.SaveToFile()方法保存为 PDF 文件。 
 
完整代码:
【C#】
 using Spire.Pdf;using Spire.Pdf.Graphics;using System.Drawing;
namespace AddTextWatermarkToPdf{    class Program    {        static void Main(string[] args)        {            //创建 PdfDocument 对象            PdfDocument pdf = new PdfDocument();
            //加载PDF文档             pdf.LoadFromFile("Sample.pdf");
            //创建PdfTrueTypeFont对象            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 50f), true);
            //设置水印文本            string text = "CONFIDENTIAL";
            //测量文本尺寸            SizeF textSize = font.MeasureString(text);
            //计算两个偏移变量的值,用于计算坐标系的平移量            float offset1 = (float)(textSize.Width * System.Math.Sqrt(2) / 4);            float offset2 = (float)(textSize.Height * System.Math.Sqrt(2) / 4);
            //浏览文档中的所有页面。            foreach (PdfPageBase page in pdf.Pages)            {                //设置页面透明度                page.Canvas.SetTransparency(0.8f);
                //通过指定坐标平移坐标系                page.Canvas.TranslateTransform(page.Canvas.Size.Width / 2 - offset1 - offset2, page.Canvas.Size.Height / 2 + offset1 - offset2);
                //将坐标系逆时针旋转 45 度                page.Canvas.RotateTransform(-45);
                //在页面上绘制水印文字                page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0);            }
            //保存修改为新文件            pdf.SaveToFile("TextWatermark.pdf");        }    }}
   复制代码
 【VB.NET】
 Imports Spire.PdfImports Spire.Pdf.GraphicsImports System.Drawing
Namespace AddTextWatermarkToPdf        Class Program                Private Shared Sub Main(ByVal args() As String)            '创建 PdfDocument 对象            Dim pdf As PdfDocument = New PdfDocument            '加载PDF文档            pdf.LoadFromFile("Sample.pdf")            '创建PdfTrueTypeFont 对象            Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 50!), true)            '设置水印文本            Dim text As String = "CONFIDENTIAL"            '测量文本尺寸            Dim textSize As SizeF = font.MeasureString(text)            '计算两个偏移变量的值,用于计算坐标系的平移量            Dim offset1 As Single = CType((textSize.Width  _                        * (System.Math.Sqrt(2) / 4)),Single)            Dim offset2 As Single = CType((textSize.Height  _                        * (System.Math.Sqrt(2) / 4)),Single)            '浏览文档中的所有页面。            For Each page As PdfPageBase In pdf.Pages                '设置页面透明度                page.Canvas.SetTransparency(0.8!)                '通过指定坐标平移坐标系                  page.Canvas.TranslateTransform(((page.Canvas.Size.Width / 2)  _                                - (offset1 - offset2)), ((page.Canvas.Size.Height / 2)  _                                + (offset1 - offset2)))                '将坐标系逆时针旋转 45 度                page.Canvas.RotateTransform(-45)                '在页面上绘制水印文字                page.Canvas.DrawString(text, font, PdfBrushes.DarkGray, 0, 0)            Next            '保存修改为新文件            pdf.SaveToFile("TextWatermark.pdf")        End Sub    End ClassEnd Namespace
   复制代码
 效果图:
向 PDF 添加多行文本水印
具体步骤:
 
- 创建 PDF 文档并用 PdfDocument. LoadFromFile()方法加载文件。 
- 获取第一页。 
- 绘制文字水印。 使用 PdfCanvas.TranslateTransform() 方法设置文本大小。 使用 PdfCanvas.RotateTransform()方法设置字体角度。并使用 PdfCanvas.DrawString() 方法绘制您想要的文本内容。 
- 使用 PdfDocument.SaveToFile() 方法将文档保存到新的 PDF 文件。 
 
完整代码:
【C#】
 using System.Drawing;using Spire.Pdf;using Spire.Pdf.Graphics;
namespace TextWaterMark{    class Program    {        static void Main(string[] args)        {            //创建PDF文档并加载文件            PdfDocument doc = new PdfDocument();            doc.LoadFromFile("Sample1.pdf");
            //获取第一页            PdfPageBase page = doc.Pages[0];
            //绘制文字水印            PdfTilingBrush brush                = new PdfTilingBrush(new SizeF(page.Canvas.ClientSize.Width / 2, page.Canvas.ClientSize.Height / 3));            brush.Graphics.SetTransparency(0.3f);            brush.Graphics.Save();            brush.Graphics.TranslateTransform(brush.Size.Width / 2, brush.Size.Height / 2);            brush.Graphics.RotateTransform(-45);            brush.Graphics.DrawString("internal use",                new PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 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文件            doc.SaveToFile("TextWaterMark1.pdf");                  }    }}
   复制代码
 【VB.NET】
 Imports System.DrawingImports Spire.PdfImports Spire.Pdf.Graphics
Namespace TextWaterMark        Class Program                Private Shared Sub Main(ByVal args() As String)            '创建PDF文档并加载文件            Dim doc As PdfDocument = New PdfDocument            doc.LoadFromFile("Sample1.pdf")            '获取第一页            Dim page As PdfPageBase = doc.Pages(0)            '绘制文字水印            Dim brush As PdfTilingBrush = New PdfTilingBrush(New SizeF((page.Canvas.ClientSize.Width / 2), (page.Canvas.ClientSize.Height / 3)))            brush.Graphics.SetTransparency(0.3!)            brush.Graphics.Save            brush.Graphics.TranslateTransform((brush.Size.Width / 2), (brush.Size.Height / 2))            brush.Graphics.RotateTransform(-45)            brush.Graphics.DrawString("internal use", New PdfFont(PdfFontFamily.Helvetica, 24), PdfBrushes.Violet, 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文件            doc.SaveToFile("TextWaterMark1.pdf")        End Sub    End ClassEnd Namespace
   复制代码
 效果图:
给 PDF 添加图像水印
具体步骤:
- 创建一个 PdfDocument 对象并使用 PdfDocument.LoadFromFile() 方法加载一个示例 PDF 文档。 
- 使用 Image.FromFile() 方法加载图像。 
- 获取图片尺寸。 
- 循环浏览文档中的页面,通过 PdfDocument.Pages() 属性获取具体页面。 
- 通过 PdfPageBase.BackgroundImage 属性设置图片为当前页面的水印图片。通过 PdfPageBase.BackgroundRegion 属性设置图像位置和大小。 
- 使用 PdfDocument.SaveToFile() 方法将文档保存到文件中。 
完整代码:
【C#】
 using Spire.Pdf;using System.Drawing;
namespace AddImageWatermark{    class Program    {        static void Main(string[] args)        {            //创建一个PdfDocument 对象            PdfDocument document = new PdfDocument();
            //加载一个示例PDF 文档            document.LoadFromFile("sample.pdf");
            //加载图像            Image image = Image.FromFile("logo.png");
            //获取图片尺寸            int imgWidth = image.Width;            int imgHeight = image.Height;
            //浏览文档中的页面            for (int i = 0; i < document.Pages.Count; i++)            {                //获取页面宽高                float pageWidth = document.Pages[i].ActualSize.Width;                float pageHeight = document.Pages[i].ActualSize.Height;
                //设置背景不透明度                document.Pages[i].BackgroudOpacity = 0.3f;
                //设置图片为当前页面的水印图片                document.Pages[i].BackgroundImage = image;
                //将背景图片放在页面的中心                Rectangle rect = new Rectangle((int)(pageWidth - imgWidth) / 2, (int)(pageHeight - imgHeight) / 2, imgWidth, imgHeight);                document.Pages[i].BackgroundRegion = rect;            }
            //将文档保存为PDF文件            document.SaveToFile("AddImageWatermark.pdf");            document.Close();        }    }}
   复制代码
 【VB.NET】
 Imports Spire.PdfImports System.Drawing
Namespace AddImageWatermark        Class Program                Private Shared Sub Main(ByVal args() As String)            '创建一个PdfDocument 对象            Dim document As PdfDocument = New PdfDocument            '加载一个示例PDF 文档            document.LoadFromFile("sample.pdf")            '加载图像            Dim image As Image = Image.FromFile("logo.png")            '获取图片尺寸            Dim imgWidth As Integer = image.Width            Dim imgHeight As Integer = image.Height            '浏览文档中的页面              Dim i As Integer = 0            Do While (i < document.Pages.Count)                '获取页面宽高                Dim pageWidth As Single = document.Pages(i).ActualSize.Width                Dim pageHeight As Single = document.Pages(i).ActualSize.Height                '设置背景不透明度                document.Pages(i).BackgroudOpacity = 0.3!                '设置图片为当前页面的水印图片                document.Pages(i).BackgroundImage = image                '将背景图片放在页面的中心                Dim rect As Rectangle = New Rectangle((CType((pageWidth - imgWidth),Integer) / 2), (CType((pageHeight - imgHeight),Integer) / 2), imgWidth, imgHeight)                document.Pages(i).BackgroundRegion = rect                i = (i + 1)            Loop                        '将文档保存为PDF文件            document.SaveToFile("AddImageWatermark.pdf")            document.Close        End Sub    End ClassEnd Namespace
   复制代码
 效果图:
评论