本简短教程介绍如何使用 C# REST API 替换 PDF 中的文本。您将学习使用基于 .NET 的 Cloud SDK 通过 C# RESTful 服务替换 PDF 中的单词。它将指导您通过比较字符串或使用正则表达式来查找单词,并在单个页面或整个 PDF 文件中执行此任务。
先决条件
创建账户 API 凭证替换 PDF 中的文本
下载 Aspose.PDF Cloud SDK for Dotnet to replace text in a PDF file
使用上述 SDK 设置 C# 项目以查找和替换文本
使用 C# REST 接口在线替换 PDF 中的文本的步骤
- 使用密钥和应用程序 SID 配置 PdfApi 对象来替换文本
- 将源 PDF 文件上传到云存储以查找和替换文本
- 使用一对旧字符串和新字符串创建 TextReplace 对象列表
- 通过提供 TextReplaceListRequest 类来创建文本替换请求
- 调用 PostDocumentTextReplace 将所有旧字符串替换为新字符串
- 下载 API 成功响应的输出文件
上述步骤描述了如何使用 C# REST API 在 PDF 中查找和替换单词。创建包含处理 PDF 文件功能的 PdfApi 对象,将源 PDF 文件上传到在线云存储,创建新旧字符串单词对列表,并使用此列表创建请求对象。调用 PostDocumentTextReplace() 方法替换列出的单词并保存输出文件。
使用基于 C# .NET 的 API 在 PDF 中查找和替换文本的代码
using System; | |
using System.IO; | |
using Aspose.Pdf.Cloud.Sdk.Api; | |
using Aspose.Pdf.Cloud.Sdk.Model; | |
using System.Collections.Generic; | |
namespace Aspose.PDF.Cloud.Examples.Kb | |
{ | |
public class PdfTasks | |
{ | |
public static void ReplaceTextInPdf() | |
{ | |
PdfApi pdfApi = new PdfApi("APP_KEY", "APP_SID"); | |
String fileName = "TextAndImages.pdf"; | |
try | |
{ | |
// Upload source file to aspose cloud storage for replacing words | |
FilesUploadResult result = pdfApi.UploadFile(fileName, new MemoryStream(File.ReadAllBytes(fileName))); | |
if (result.Errors.Count == 0) | |
{ | |
List<TextReplace> textReplaces = new List<TextReplace>() | |
{ | |
new TextReplace("English", "English Subject", false), | |
new TextReplace("Math", "Math Subject", false), | |
new TextReplace("Science", "Science Subject", false), | |
}; | |
TextReplaceListRequest textReplaceListRequest = new TextReplaceListRequest(textReplaces); | |
TextReplaceResponse response = pdfApi.PostDocumentTextReplace(fileName, textReplaceListRequest); | |
if (response.Status == "OK") | |
{ | |
// Download created pdf file | |
Stream storageRes = pdfApi.DownloadFile(fileName); | |
FileStream fileStream = new FileStream("output.pdf", FileMode.Create, FileAccess.Write); | |
storageRes.CopyTo(fileStream); | |
} | |
} | |
} | |
catch (Exception ex) | |
{ | |
Console.WriteLine("error:" + ex.Message + "\n" + ex.StackTrace); | |
} | |
} | |
} | |
} |
此代码演示了使用 C# REST 接口替换 PDF 文件中的文本的过程。您可以在完整文档中搜索字符串时使用字符串列表或正则表达式。如果您想替换上传的 PDF 文件中单个页面中的文本,请使用带有目标页码的 PostPageTextReplace() 方法。
本文教我们如何在 PDF 文件中搜索和替换文本。如果您想在 PDF 文件中添加新页面,请参阅 使用 C# REST API 在 PDF 中添加新页面 上的文章。