本文介紹通過Java程式批量替換PDF中的指定文本內容,
1. 程式環境準備如下:

程式使用環境如圖,需要注意的是,本文使用了免費版的PDF jar工具;另外JDK版本建議使用高版本更佳,
jar檔案匯入后,可呼叫Spire.PDF提供的介面、方法等操作PDF,參考如下匯入結果:

注:可手動下載jar包,下載后,解壓檔案,將lib檔案夾下的Spire.Pdf.jar檔案匯入Java程式,
Java 代碼示例
import com.spire.pdf.*; import com.spire.pdf.general.find.PdfTextFind; import com.spire.pdf.general.find.PdfTextFindCollection; import com.spire.pdf.graphics.PdfBrushes; import com.spire.pdf.graphics.PdfRGBColor; import com.spire.pdf.graphics.PdfSolidBrush; import com.spire.pdf.graphics.PdfTrueTypeFont; import java.awt.*; import java.awt.geom.Rectangle2D; public class FindAndReplaceText { public static void main(String[] args) { //加載示例PDF檔案 PdfDocument pdf = new PdfDocument(); pdf.loadFromFile("咖啡豆.pdf"); //遍歷檔案每一頁 for (int i = 0; i < pdf.getPages().getCount(); i++) { //獲取所有頁面 PdfPageBase page = pdf.getPages().get(i); //查找指定文本 PdfTextFindCollection textFindCollection; textFindCollection = page.findText("咖啡",false); //創建畫刷、字體 PdfSolidBrush brush1 = new PdfSolidBrush(new PdfRGBColor(Color.red)); PdfTrueTypeFont font1= new PdfTrueTypeFont(new Font("宋體",Font.PLAIN,9),true); //用新的文本字符替換原有文本 Rectangle2D rec; for(PdfTextFind find: textFindCollection.getFinds()) { rec = find.getBounds(); page.getCanvas().drawRectangle(PdfBrushes.getWhite(), rec); page.getCanvas().drawString("Coffee", font1, brush1, rec); } } //保存檔案 pdf.saveToFile("FindAndReplaceText.pdf"); pdf.close(); } }
文本替換前后效果:

轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242194.html
標籤:Java
下一篇:阿里大神的刷題筆記.pdf
