java 查找替換pdf中的指定文本
本文介紹通過(guò)Java程序批量替換PDF中的指定文本內(nèi)容。
程序環(huán)境準(zhǔn)備如下:程序使用環(huán)境如圖,需要注意的是,本文使用了免費(fèi)版的PDF jar工具;另外JDK版本建議使用高版本更佳。
jar文件導(dǎo)入后,可調(diào)用Spire.PDF提供的接口、方法等操作PDF,參考如下導(dǎo)入結(jié)果:
注:可手動(dòng)下載jar包。下載后,解壓文件,將lib文件夾下的Spire.Pdf.jar文件導(dǎo)入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'); //遍歷文檔每一頁(yè) for (int i = 0; i < pdf.getPages().getCount(); i++) { //獲取所有頁(yè)面 PdfPageBase page = pdf.getPages().get(i); //查找指定文本 PdfTextFindCollection textFindCollection; textFindCollection = page.findText('咖啡',false); //創(chuàng)建畫刷、字體 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(); }}
文本替換前后效果:
以上就是java 查找替換pdf中的指定文本的詳細(xì)內(nèi)容,更多關(guān)于java 查找替換文本的資料請(qǐng)關(guān)注好吧啦網(wǎng)其它相關(guān)文章!
相關(guān)文章:
1. XML入門的常見(jiàn)問(wèn)題(一)2. html小技巧之td,div標(biāo)簽里內(nèi)容不換行3. PHP字符串前后字符或空格刪除方法介紹4. AspNetCore&MassTransit Courier實(shí)現(xiàn)分布式事務(wù)的詳細(xì)過(guò)程5. jsp cookie+session實(shí)現(xiàn)簡(jiǎn)易自動(dòng)登錄6. css進(jìn)階學(xué)習(xí) 選擇符7. 將properties文件的配置設(shè)置為整個(gè)Web應(yīng)用的全局變量實(shí)現(xiàn)方法8. 解析原生JS getComputedStyle9. Echarts通過(guò)dataset數(shù)據(jù)集實(shí)現(xiàn)創(chuàng)建單軸散點(diǎn)圖10. nestjs實(shí)現(xiàn)圖形校驗(yàn)和單點(diǎn)登錄的示例代碼
