本文指导如何使用 C# 编辑 PDF 文档。它包含设置开发环境的信息、执行任务所需的步骤列表以及使用 C#** 开发 **PDF 编辑器应用程序的可运行示例代码。我们还将讨论在 PDF 文件中执行修改所需的类、方法和属性。
使用 C# 修改 PDF 文件的步骤
- 配置 IDE 以使用 Aspose.PDF for .NET 进行编辑
- 创建 PdfContentEditor 类的对象来替换整个文件中的文本
- 替换一些其他文本以及设置前景色和字体大小,并保存到内存流
- 将流加载到 PdfFileMend 对象中以添加一些文本并将其保存回内存流
- 将生成的内存流加载到 Document 类中,以添加带有一些文本的页面
- 将完成上述所有修改的最终 PDF 文件保存在磁盘上
这些步骤介绍了使用 C# 修改 PDF 文档的过程。您可以使用 PdfContentEditor 对象替换整个文件中的文本或用不同的前景色和字体替换文本。 PdfFileMend 类用于向现有页面添加文本,而 Document 类用于添加新页面并在其上呈现一些文本。
使用 C# 更改 PDF 文件的代码
using Aspose.Pdf; | |
using Aspose.Pdf.Facades; | |
using Aspose.Pdf.Text; | |
class Program | |
{ | |
static void Main(string[] args) // Edit PDF in C# | |
{ | |
new License().SetLicense("License.lic"); | |
// Create PdfFileEditor object | |
PdfContentEditor editor = new PdfContentEditor(); | |
editor.BindPdf("Input.pdf"); | |
// Replace some text in the entire file | |
while (true) | |
if (editor.ReplaceText("scenario", "situation") == false) | |
break; | |
// Replace some text and change its font and color | |
TextState textState = new TextState(); | |
textState.ForegroundColor = Color.Red; | |
textState.FontSize = 14; | |
while (true) | |
if (editor.ReplaceText("attack", "fight", textState) == false) | |
break; | |
System.IO.MemoryStream memoryStream = new System.IO.MemoryStream(); | |
editor.Save(memoryStream); | |
// Add text to an existing page | |
PdfFileMend mendor = new PdfFileMend(); | |
memoryStream.Position = 0; | |
mendor.BindPdf(memoryStream); | |
FormattedText message = new FormattedText("Test message on the page"); | |
mendor.AddText(message, 2, 60, 300); | |
mendor.Save(memoryStream); | |
// Add a paragraph with some text on a new page | |
memoryStream.Position = 0; | |
Document document = new Document(memoryStream); | |
Page page = document.Pages.Add(); | |
page.Paragraphs.Add(new TextFragment("New paragraph is added")); | |
// Save the output | |
document.Save("output.pdf"); | |
System.Console.WriteLine("Done"); | |
} | |
} |
此代码演示了使用 C#* 开发 *PDF 修改器。我们使用不同的类来修改内容并将中间结果保存到临时内存流中,以便加载到下一个类中以执行另一项任务。有多种类可用于修改 PDF 文件,包括 PdfPageEditor、PdfFileStamp、PdfFileSignature、PdfConverter 和 PdfBookmarkEditor 等。
本文向我们展示了使用 C#* 的软件 *PDF 编辑器的工作原理。如果您想了解更改 PDF 文件背景的过程,请参阅 如何使用C#编辑PDF背景颜色 上的文章。