您好,登錄后才能下訂單哦!
這篇文章給大家分享的是有關(guān)如何使用Java通過(guò)關(guān)鍵字修改pdf的內(nèi)容。小編覺(jué)得挺實(shí)用的,因此分享給大家做個(gè)參考,一起跟隨小編過(guò)來(lái)看看吧。
在main方法中測(cè)試該方法,還需要引用的jar包有itextpdf-5.5.10.jar、itext-asian-5.2.0.jar
注意:兩jar包之間有版本對(duì)應(yīng),否則會(huì)出現(xiàn)報(bào)錯(cuò),該報(bào)錯(cuò)主要針對(duì)設(shè)置中文字體的方法java itext 報(bào)錯(cuò) com.itextpdf.text.DocumentException: Font 'STSong-Light' with 'UniGB-UCS2-H'
import com.itextpdf.text.Chunk; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Font; import com.itextpdf.text.Paragraph; import com.itextpdf.text.pdf.BaseFont; import com.itextpdf.text.pdf.ColumnText; import com.itextpdf.text.pdf.PdfContentByte; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.PdfStamper; import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; /** * @Desc * @Author madengling * @Time 2021/5/11 15:18 */ public class UpdatePdf { public static void main(String[] args) { File file = new File("G://files//cs//111.pdf");//模擬文件位置 if(file!=null && file.exists()){ FileInputStream is = null; try { //本地根據(jù)文件路徑獲取文件流 is = new FileInputStream(file); long length = file.length(); byte[] fileBytes = new byte[(int)length]; is.read(fileBytes); //進(jìn)行pdf文件修改 File file1 = pdfFzSqsj(fileBytes); if(file1!=null && file1.exists()){ System.out.println("修改pdf完成!"); } } catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if(is!=null){ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } } } /** * 根據(jù)pdf的固定關(guān)鍵字,查找進(jìn)行pdf相關(guān)位置增加文字 * @param tpeHtcxyw 文件流 * @return 修改后的文件 */ private static File pdfFzSqsj(byte[] tpeHtcxyw) { PdfStamper stamper = null; try { SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日"); //獲取要寫入的申請(qǐng)時(shí)間 String sj =sdf.format(new Date()); PdfReader reader = new PdfReader(tpeHtcxyw); //創(chuàng)建文件路徑 String filePath = "G://files/cs/"; System.out.println("filePath="+filePath); File directory = new File(filePath); //如果pdf保存路徑不存在,則創(chuàng)建路徑 if (!directory.exists()) { directory.mkdirs(); } String filename = UUID.randomUUID()+"_after.pdf";//修改后文件 String filename1 = UUID.randomUUID()+"_before.pdf";//修改前文件 再輸出一遍,校驗(yàn)自己在修改之前拿到正確的文件流 System.out.println("file:"+filePath+filename); File file = new File(filePath+filename); File file1 = new File(filePath+filename1); //將寫入臨時(shí)文件 FileOutputStream foss = new FileOutputStream (file1); foss.write(tpeHtcxyw); foss.close(); //設(shè)置字體 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false); Font font = new Font(baseFont); stamper = new PdfStamper(reader, new FileOutputStream(file)); //對(duì)于已經(jīng)固話的pdf回填申請(qǐng)時(shí)間 for (int i = 1; i <= reader.getNumberOfPages(); i++) { PdfContentByte over = stamper.getOverContent(i); ColumnText columnText = new ColumnText(over); if(i==1){ String str = "申請(qǐng)日期:"; //根據(jù)關(guān)鍵字獲取關(guān)鍵字位置 float[] po = Html2Pdf.getGzzzb(str,tpeHtcxyw); if(po[0]==1.00f){ // 方法setSimpleColumn(float llx, float lly, float urx, float ury) // llx 和 urx 最小的值決定離左邊的距離. lly 和 ury 最大的值決定離下邊的距離 columnText.setSimpleColumn( po[1]+46f, po[2]-9f, 500, 0); //將時(shí)間文本創(chuàng)建成對(duì)象 Paragraph elements = new Paragraph(0, new Chunk(new Chunk(sj))); // 設(shè)置字體,如果不設(shè)置添加的中文將無(wú)法顯示 elements.setFont(font); columnText.addElement(elements); columnText.go(); } } } return file; } catch (Exception e) { e.printStackTrace(); return null; } finally { if(stamper!=null){ try { stamper.close(); } catch (DocumentException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } } } } }
import com.itextpdf.awt.geom.Rectangle2D; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.parser.ImageRenderInfo; import com.itextpdf.text.pdf.parser.PdfReaderContentParser; import com.itextpdf.text.pdf.parser.RenderListener; import com.itextpdf.text.pdf.parser.TextRenderInfo; public class Html2Pdf { /** * 定位pdf文件中關(guān)鍵字坐標(biāo) * @param signKey 關(guān)鍵字 * @param pdf 文件流 * @return 坐標(biāo)位置 */ public static float[] getGzzzb(String signKey, byte[] pdf){ PdfReader reader=null; final float[] po = new float[3]; try{ reader = new PdfReader(pdf); int pageNum = reader.getNumberOfPages(); final String signKeyWord = signKey; for(int page=1; page <= pageNum; page++){ PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(reader); pdfReaderContentParser.processContent(page, new RenderListener() { StringBuilder sb = new StringBuilder(""); int maxLength = signKeyWord.length(); @Override public void renderText(TextRenderInfo textRenderInfo) { // 只適用 單字塊文檔 以及 關(guān)鍵字整個(gè)為一個(gè)塊的情況 // 設(shè)置 關(guān)鍵字文本為單獨(dú)的塊,不然會(huì)錯(cuò)位 boolean isKeywordChunk = textRenderInfo.getText().length() == maxLength; if (isKeywordChunk) { // 文檔按照 塊 讀取 sb.delete(0, sb.length()); sb.append(textRenderInfo.getText()); } else { // 有些文檔 單字一個(gè)塊的情況 // 拼接字符串 sb.append(textRenderInfo.getText()); // 去除首部字符串,使長(zhǎng)度等于關(guān)鍵字長(zhǎng)度 if (sb.length() > maxLength) { sb.delete(0, sb.length() - maxLength); } } // 判斷是否匹配上 if (signKeyWord.equals(sb.toString())) { // 計(jì)算中心點(diǎn)坐標(biāo) Rectangle2D.Float baseFloat = textRenderInfo.getBaseline() .getBoundingRectange(); Rectangle2D.Float ascentFloat = textRenderInfo.getAscentLine() .getBoundingRectange(); float centreX; float centreY; if (isKeywordChunk) { centreX = baseFloat.x + 5*ascentFloat.width / 6; centreY = baseFloat.y + (5*(ascentFloat.y - baseFloat.y) / 6); } else { centreX = baseFloat.x + ascentFloat.width - (5*maxLength * ascentFloat.width / 6); centreY = baseFloat.y + (5*(ascentFloat.y - baseFloat.y) / 6); } po[0]=1.00f; po[1]=centreX+3; po[2]=centreY; // 匹配完后 清除 sb.delete(0, sb.length()); } } @Override public void renderImage(ImageRenderInfo arg0) {} @Override public void endTextBlock() {} @Override public void beginTextBlock() {} }); } if(po[0]==1.00f){ return po; } }catch(Exception e){ e.printStackTrace(); }finally { if(reader!=null){ reader.close(); } } return null; }
111.pdf是原始文件,其余兩文件在方法執(zhí)行后生成,before文件內(nèi)容與111.pdf一致
我的原始pdf中含有關(guān)鍵字申請(qǐng)時(shí)間
,修改前后文件內(nèi)容如下:
1.SpringMVC,Spring Web MVC是一種基于Java的實(shí)現(xiàn)了Web MVC設(shè)計(jì)模式的請(qǐng)求驅(qū)動(dòng)類型的輕量級(jí)Web框架。2.Shiro,Apache Shiro是Java的一個(gè)安全框架。3.Mybatis,MyBatis 是支持普通 SQL查詢,存儲(chǔ)過(guò)程和高級(jí)映射的優(yōu)秀持久層框架。4.Dubbo,Dubbo是一個(gè)分布式服務(wù)框架。5.Maven,Maven是個(gè)項(xiàng)目管理和構(gòu)建自動(dòng)化工具。6.RabbitMQ,RabbitMQ是用Erlang實(shí)現(xiàn)的一個(gè)高并發(fā)高可靠AMQP消息隊(duì)列服務(wù)器。7.Ehcache,EhCache 是一個(gè)純Java的進(jìn)程內(nèi)緩存框架。
感謝各位的閱讀!關(guān)于“如何使用Java通過(guò)關(guān)鍵字修改pdf”這篇文章就分享到這里了,希望以上內(nèi)容可以對(duì)大家有一定的幫助,讓大家可以學(xué)到更多知識(shí),如果覺(jué)得文章不錯(cuò),可以把它分享出去讓更多的人看到吧!
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。