import com.aspose.pdf.*;
import java.io.InputStream;
public class ChangePDF {
private static String srcPath = "E:\\demo\\TNBZQSC01.pdf"; // 源文件路径
private static String targetPath = "E:\\\\demo\\\\TNBZQSC01_2.pdf"; // 输入文件路径
private static String srcText = "ABCDEFGHIJKLNMOPQRSTUVWXYZ"; // 需要替换的文本TNBBFZ.pdf / TNBZQSC.pdf
//private static String targetText = " 糖尿病早期风险评估报告 "; // 替换的目标文本,糖尿病并发症 / 糖尿病早期筛查
private static String targetText = " 糖尿病并发症风险评估报告 ";
public static void main(String[] args) {
InputStream license = ChangePDF.class.getClassLoader().getResourceAsStream("\\license.xml");
try {
new License().setLicense(license);
} catch (Exception e) {
e.printStackTrace();
}
Document pdfDoc = new Document(srcPath);
TextFragmentAbsorber textFragmentAbsorber = new TextFragmentAbsorber(srcText);
PageCollection pages = pdfDoc.getPages();
System.out.println("文档总页码数:" + pages.size());
pages.accept(textFragmentAbsorber);
int i = 0;
for (TextFragment textFragment : (Iterable<TextFragment>)textFragmentAbsorber.getTextFragments()) {
textFragment.setText(targetText);
//textFragment.getTextState().setBackgroundColor(com.aspose.pdf.Color.getRed()); // 添加红色背景
System.out.println(++i);
}
pdfDoc.save(targetPath);
System.out.println("总共替换" + i + "处");
System.out.println("OK");
}
}
注意:license.xml需要放在根目录下(src或者resources)
licenes.xml内容如下:
<License>
<Data>
<Products>
<Product>Aspose.Total for Java</Product>
<Product>Aspose.Pdf for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>20991231</SubscriptionExpiry>
<LicenseExpiry>20991231</LicenseExpiry>
<SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
</Data>
<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>