項目在變,需求在變,不變的永遠是敲擊鍵盤的程序員.....html
PDF 生成後,有時候須要在PDF上面添加一些其餘的內容,好比文字,圖片....java
經歷幾回失敗的嘗試,終於獲取到了正確的代碼書寫方式。程序員
在此記錄總結,方便下次以不變應萬變,須要的 jar 請移步:生成PDF全攻略數據庫
PdfReader reader = new PdfReader("E:\\A.pdf"); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("E:\\B.pdf")); PdfContentByte overContent = stamper.getOverContent(1);
上述的這段代碼算是在原有 PDF 上面添加內容的核心代碼,具體流程以下服務器
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);
代碼流程就變作下面這個樣子post
管道複製代碼以下:spa
public static void fileChannelCopy(File sources, File dest) { try { FileInputStream inputStream = new FileInputStream(sources); FileOutputStream outputStream = new FileOutputStream(dest); FileChannel fileChannelin = inputStream.getChannel();//獲得對應的文件通道 FileChannel fileChannelout = outputStream.getChannel();//獲得對應的文件通道 fileChannelin.transferTo(0, fileChannelin.size(), fileChannelout);//鏈接兩個通道,而且從in通道讀取,而後寫入out通道 inputStream.close(); fileChannelin.close(); outputStream.close(); fileChannelout.close(); } catch (Exception e) { e.printStackTrace(); } }
完整的在已有PDF添加其餘內容代碼以下:code
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-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED); overContent.beginText(); overContent.setFontAndSize(font, 10); overContent.setTextMatrix(200, 200); overContent.showTextAligned(Element.ALIGN_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.setLineWidth(5f); overContent.ellipse(250, 450, 350, 550); overContent.stroke(); stamper.close();