spire.pdf 支持查找和替换pdf文档中文本。该文将详细介绍如何使用spire.pdf查找pdf文档中的某一个特定词汇并使用新文本进行替换。
c#
using spire.pdf;
using spire.pdf.fields;
using spire.pdf.general.find;
using system.drawing;
using spire.pdf.graphics;
using system;
namespace findandreplacetextonpdf
{
class program
{
static void main(string[] args)
{
//新建一个pdf文档对象并加载sample文档
pdfdocument doc = new pdfdocument();
doc.loadfromfile("sample.pdf");
//获取第一页
pdfpagebase page = doc.pages[0];
//查找一个特定字符串 ”spire.pdf for .net”并忽略大小写
pdftextfindcollection collection = page.findtext("spire.pdf for .net", textfindparameter.ignorecase);
//替换字符串
string newtext = "e-iceblue spire.pdf";
//替换查找文本并设置字体,颜色
pdfbrush brush = new pdfsolidbrush(color.darkblue);
pdftruetypefont font = new pdftruetypefont(new font("arial", 12f, fontstyle.regular));
rectanglef rec;
foreach (pdftextfind find in collection.finds)
{
rec = find.bounds;
page.canvas.drawrectangle(pdfbrushes.white, rec);
page.canvas.drawstring(newtext, font, brush, rec);
}
//保存文档
doc.savetofile("result.pdf");
}
}
}
vb.net
imports spire.pdf
imports spire.pdf.fields
imports spire.pdf.general.find
imports system.drawing
imports spire.pdf.graphics
namespace findandreplacetextonpdf
class program
private shared sub main(args as string())
'新建一个pdf文档对象并加载sample文档
dim doc as new pdfdocument()
doc.loadfromfile("sample.pdf")
'获取第一页
dim page as pdfpagebase = doc.pages(0)
'查找一个特定字符串 ”spire.pdf for .net”并忽略大小写
dim collection as pdftextfindcollection = page.findtext("spire.pdf for .net", textfindparameter.ignorecase)
'替换字符串
dim newtext as [string] = "e-iceblue spire.pdf"
'替换查找文本并设置字体,颜色
dim brush as pdfbrush = new pdfsolidbrush(color.darkblue)
dim font as new pdftruetypefont(new font("arial", 12f, fontstyle.regular))
dim rec as rectanglef
for each find as pdftextfind in collection.finds
rec = find.bounds
page.canvas.drawrectangle(pdfbrushes.white, rec)
page.canvas.drawstring(newtext, font, brush, rec)
next
'保存文档
doc.savetofile("result.pdf")
end sub
end class
end namespace
源文档:
替换文本后的效果图: