本快速指南介绍了如何使用任何图像或某些文本作为水印在 C# 中向 PDF 添加水印。 为PDF C#添加水印提供了详细描述的代码。无需安装任何第三方工具或软件即可完成任务。
在 C# 中为 PDF 添加水印的步骤
- 将项目配置为从 NuGet 包管理器添加 Aspose.PDF for .NET 以添加水印
- 将目标 PDF 文件加载到要添加水印的 Document 类对象中
- 将图像加载到要用作水印的 ImageStamp 类对象中
- 在添加为水印之前配置加载的图像特征
- 将水印图像添加到所选页面
- 保存带有水印的 PDF
这些步骤描述了 C# 如何将水印添加到 PDF,首先指向运行示例代码所需的必要资源,然后共享执行任务的分步方法。您应该在相关类对象中加载目标 PDF 和图像文件,然后设置加载的图像属性,例如其在页面上的位置、高度和宽度,并设置标志以在背景中显示或不显示。您可以将水印图像添加到 PDF 中的任何选定页面,然后再将其保存回磁盘。
在 C# 中向 PDF 添加水印的代码
using System; | |
using Aspose.Pdf; | |
namespace AddWatermarkToPDFInCSharp | |
{ | |
class Program | |
{ | |
static void Main(string[] args) // Main function to add watermark to PDF in C# | |
{ | |
// Instantiate the license to avoid trial version watermark in the output PDF | |
Aspose.Pdf.License licWatermarkPDF = new Aspose.Pdf.License(); | |
licWatermarkPDF.SetLicense("Aspose.PDF.lic"); | |
// Load the sample PDF file where watermark is to be added | |
Aspose.Pdf.Document pdfToWatermark = new Aspose.Pdf.Document(@"sample.pdf"); | |
// Load the image to be added as a watermark | |
Aspose.Pdf.ImageStamp watermarkImg = new Aspose.Pdf.ImageStamp(@"image_stamp.png"); | |
// Set the location of the waterrmark starting from the bottom left corner | |
watermarkImg.XIndent = 200; | |
watermarkImg.YIndent = 200; | |
// Set the image height and width along with the flag to display it in the background | |
watermarkImg.Height = 60; | |
watermarkImg.Width = 60; | |
watermarkImg.Background = true; | |
// Add the watermark image into the first page of the PDF | |
pdfToWatermark.Pages[1].AddStamp(watermarkImg); | |
// Save the output PDF file | |
pdfToWatermark.Save(@"output.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} | |
} |
通过使用 C# PDF watermark 可以以不同的方式添加,例如在此代码示例中将图像用作水印。但是,您也可以通过在 Aspose.Pdf.TextStamp 类对象的构造函数中设置所需的文本来使用文本水印。它提供了在使用 Aspose.Pdf.Page.AddStamp() 函数添加水印之前设置文本属性(如字体、背景颜色和前景色)的选项,类似于在上面的示例中添加图像水印。
本教程指导我们为 PDF 添加水印,但是,如果您有兴趣从头开始创建 PDF,请参阅 如何在 C# 中创建 PDF 上的文章。