項目在變,需求在變,不變的永遠是敲擊鍵盤的程序員.....
PDF 生成後,有時候需要在PDF上面添加一些其他的內容,比如文字,圖片....
經歷幾次失敗的嘗試,終於獲取到了正確的代碼書寫方式。
在此記錄總結,方便下次以不變應萬變,需要的 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);
代碼流程就變做下面這個樣子
管道復制代碼如下:
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添加其他內容代碼如下:
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();