java 查找替換pdf中的指定文本
本文介紹通過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. div的offsetLeft與style.left區(qū)別2. 不要在HTML中濫用div3. html清除浮動(dòng)的6種方法示例4. 前端html+css實(shí)現(xiàn)動(dòng)態(tài)生日快樂代碼5. CSS代碼檢查工具stylelint的使用方法詳解6. 詳解CSS偽元素的妙用單標(biāo)簽之美7. WML語(yǔ)言的基本情況8. CSS3實(shí)例分享之多重背景的實(shí)現(xiàn)(Multiple backgrounds)9. 使用css實(shí)現(xiàn)全兼容tooltip提示框10. 利用CSS3新特性創(chuàng)建透明邊框三角
