Aspose.Pdf为开发人员提供了多种常用的处理PDF文档的功能,其中常用的一种功能就是文本查找和替换,通常可以查找和替换指定的文本,也可以使用特殊的正则表达式进行查找和替换,这篇文章主要介绍怎么使用正则表达式对PDF文件内的文本进行查找和替换,控件提供了TextFragmentAbsorber方法来构造正则表达式,然后创建一个TextSearchOptions对象来设置是否采用正则表达式,一旦找到匹配的文本都放在TextFragments集合里,然后可以对该集合进行替换修改等操作了,具体可以参考下面的部分代码:
//open document
Document pdfDocument = new Document("input.pdf");
//create TextAbsorber object to find all instances of the input search phrase
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber("\\d{4}-\\d{4}"); //like 1999-2000
//set text search option to specify regular expression usage
TextSearchOptions textSearchOptions = new TextSearchOptions(true);
textFragmentAbsorber.TextSearchOptions = textSearchOptions;
//accept the absorber for all the pages
pdfDocument.Pages.Accept(textFragmentAbsorber);
//get the extracted text fragments
TextFragmentCollection textFragmentCollection = textFragmentAbsorber.TextFragments;
//loop through the fragments
foreach (TextFragment textFragment in textFragmentCollection)
{
//update text and other properties
textFragment.Text = "New Phrase";
set to an instance of an object.
textFragment.TextState.Font = FontRepository.FindFont("Verdana");
textFragment.TextState.FontSize = 22;
textFragment.TextState.ForegroundColor =
Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Blue);
textFragment.TextState.BackgroundColor =
Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Green);
}
pdfDocument.Save("output.pdf");
开发人员可以从
控件中国网上下载
Aspose.Pdf的试用版进行功能上的测试,也可以使用试用版进行项目的开发,试用版只是比正式版多了试用版水印,其他功能都是和正式版一样,当项目开发好以后购买正式版进行替换即可。