項目在變,需求在變,不變的永遠是敲擊鍵盤的程序員.....
PDF 生成后,有時候需要在PDF上面添加一些其他的內容,比如文字,圖片....
經歷幾次失敗的嘗試,終于獲取到了正確的代碼書寫方式。
在此記錄總結,方便下次以不變應萬變,需要的 jar 請移步:生成PDF全攻略
1
2
3
|
PdfReader reader = new PdfReader( "E:\\A.pdf" ); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( "E:\\B.pdf" )); PdfContentByte overContent = stamper.getOverContent( 1 ); |
上述的這段代碼算是在原有 PDF 上面添加內容的核心代碼,具體流程如下
•如果看官老爺夠仔細的話,該代碼是將原 A.pdf 讀取,然后將它寫入 B.pdf,然后操作 B.pdf。
•可能有的看官老爺會說,將 A 讀取,然后在寫入 A 中,這樣肯定是不行的,在讀取的時候 A 已經被加載了,不能進行修改。
•我不喜歡這種方式,因為原 PDF 的信息已經存儲在數據庫中,其中包括 PDF 的服務器路徑、舊名稱、新名稱、類型......
•這樣就會多出一次數據庫變更操作,因為這里PDF名稱需要變更,而且鬼知道后續需求還會怎么變。
•這里急需 只在 PDF 中添加內容,其他的什么都不變,將代碼稍微調整了一下。
1
2
3
4
|
FileUtil.fileChannelCopy(A.pdf,A + "tmp" .pdf)); PdfReader reader = new PdfReader(A + "tmp" .pdf); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(A.pdf)); PdfContentByte overContent = stamper.getOverContent( 1 ); |
代碼流程就變做下面這個樣子
這里引入了管道復制文件,將A 復制一份,讀取副本,然后寫回到原 PDF A 中,最后當然需要刪除副本文件。
到這里,無論后續需求怎么變,保證了pdf 的其他屬性不變,就能從容面對。
管道復制代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
pubpc static void fileChannelCopy(File sources, File dest) { try { FileInputStream inputStream = new FileInputStream(sources); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel fileChannepn = inputStream.getChannel(); //得到對應的文件通道 FileChannel fileChannelout = outputStream.getChannel(); //得到對應的文件通道 fileChannepn.transferTo( 0 , fileChannepn.size(), fileChannelout); //連接兩個通道,并且從in通道讀取,然后寫入out通道 inputStream.close(); fileChannepn.close(); outputStream.close(); fileChannelout.close(); } catch (Exception e) { e.printStackTrace(); } } |
完整PDF其他內容代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
|
FileUtil.fileChannelCopy( new File( "E:\\A.pdf" ), new File( "E:\\A+" tmp ".pdf" )); PdfReader reader = new PdfReader( "E:\\A+" tmp ".pdf" ); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream( "E:\\A.pdf" )); PdfContentByte overContent = stamper.getOverContent( 1 ); //添加文字 BaseFont font = BaseFont.createFont( "STSong-pght" , "UniGB-UCS2-H" , BaseFont.NOT_EMBEDDED); overContent.beginText(); overContent.setFontAndSize(font, 10 ); overContent.setTextMatrix( 200 , 200 ); overContent.showTextApgned(Element.ApGN_CENTER, "需要添加的文字" , 580 , 530 , 0 ); overContent.endText(); //添加圖片 PdfDictionary pdfDictionary = reader.getPageN( 1 ); PdfObject pdfObject = pdfDictionary.get( new PdfName( "MediaBox" )); PdfArray pdfArray = (PdfArray) pdfObject; Image image = Image.getInstance( "D:\\1.jpg" ); image.setAbsolutePosition( 100 , 100 ); overContent.addImage(image); //添加一個紅圈 overContent.setRGBColorStroke( 0xFF , 0x00 , 0x00 ); overContent.setpneWidth(5f); overContent.elppse( 250 , 450 , 350 , 550 ); overContent.stroke(); stamper.close(); |
以上這篇生成PDF全攻略之在已有PDF上添加內容的實現方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。