java實現(xiàn)在pdf模板的指定位置插入圖片
更新時間:2018年10月30日 11:53:41 作者:yieku
這篇文章主要為大家詳細介紹了java如何實現(xiàn)在pdf模板的指定位置插入圖片,具有一定的參考價值,感興趣的小伙伴們可以參考一下
本文實例為大家分享了java在pdf模板的指定位置插入圖片的具體代碼,供大家參考,具體內容如下
java操作pdf有個非常好用的庫itextpdf,maven:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.6</version> </dependency> <!-- itextpdf的亞洲字體支持 --> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itext-asian</artifactId> <version>5.2.0</version> </dependency>
思路:
- Adobe的Acrobat可以對pdf進行編輯,在文檔中插入域,這個插入的域就是圖片的位置。這兒有關于域的介紹,但是這不重要,我們只是把域作為一個占位符用;
- 利用itextpdf得到目標域所在的頁面、位置、大小;
- 利用域的坐標,把圖片以絕對位置的方式插入到pdf中。
代碼
public static void main(String[] args) throws Exception { // 模板文件路徑 String templatePath = "template.pdf"; // 生成的文件路徑 String targetPath = "target.pdf"; // 書簽名 String fieldName = "field"; // 圖片路徑 String imagePath = "image.jpg"; // 讀取模板文件 InputStream input = new FileInputStream(new File(templatePath)); PdfReader reader = new PdfReader(input); PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(targetPath)); // 提取pdf中的表單 AcroFields form = stamper.getAcroFields(); form.addSubstitutionFont(BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED)); // 通過域名獲取所在頁和坐標,左下角為起點 int pageNo = form.getFieldPositions(fieldName).get(0).page; Rectangle signRect = form.getFieldPositions(fieldName).get(0).position; float x = signRect.getLeft(); float y = signRect.getBottom(); // 讀圖片 Image image = Image.getInstance(imagePath); // 獲取操作的頁面 PdfContentByte under = stamper.getOverContent(pageNo); // 根據(jù)域的大小縮放圖片 image.scaleToFit(signRect.getWidth(), signRect.getHeight()); // 添加圖片 image.setAbsolutePosition(x, y); under.addImage(image); stamper.close(); reader.close(); }
參考
How to show an image at a text field position?
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。
相關文章
SpringBoot整合新版SpringSecurity完整過程
Spring Security是保障Spring應用程序安全的強大框架,而新版的Spring Security引入了lambda表達式來配置,使得安全配置更加簡潔、優(yōu)雅,本文將介紹如何在Spring Boot項目中整合新版Spring Security,需要的朋友可以參考下2024-02-02Mybatis-plus常見的坑@TableField不生效問題
這篇文章主要介紹了Mybatis-plus常見的坑@TableField不生效問題,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01