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>