java實(shí)現(xiàn)在pdf模板的指定位置插入圖片
更新時(shí)間:2018年10月30日 11:53:41 作者:yieku
這篇文章主要為大家詳細(xì)介紹了java如何實(shí)現(xiàn)在pdf模板的指定位置插入圖片,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下
本文實(shí)例為大家分享了java在pdf模板的指定位置插入圖片的具體代碼,供大家參考,具體內(nèi)容如下
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進(jìn)行編輯,在文檔中插入域,這個插入的域就是圖片的位置。這兒有關(guān)于域的介紹,但是這不重要,我們只是把域作為一個占位符用;
- 利用itextpdf得到目標(biāo)域所在的頁面、位置、大小;
- 利用域的坐標(biāo),把圖片以絕對位置的方式插入到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)); // 通過域名獲取所在頁和坐標(biāo),左下角為起點(diǎn) 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?
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
您可能感興趣的文章:
- java實(shí)現(xiàn)PDF轉(zhuǎn)圖片的方法
- java中pdf轉(zhuǎn)圖片的實(shí)現(xiàn)方法
- Java 讀取PDF中的文本和圖片的方法
- Java實(shí)現(xiàn)圖片轉(zhuǎn)換PDF文件的示例代碼
- Java實(shí)現(xiàn)將PDF轉(zhuǎn)為圖片格式的方法詳解
- Java將圖片組合成PDF文件的方法
- Java實(shí)現(xiàn)PDF轉(zhuǎn)圖片的三種方法
- JAVA基于PDF box將PDF轉(zhuǎn)為圖片的實(shí)現(xiàn)方法
- Java使用icepdf將pdf文件按頁轉(zhuǎn)成圖片
- Java神操作:圖片快速轉(zhuǎn)換PDF秘籍
相關(guān)文章
SpringBoot整合新版SpringSecurity完整過程
Spring Security是保障Spring應(yīng)用程序安全的強(qiáng)大框架,而新版的Spring Security引入了lambda表達(dá)式來配置,使得安全配置更加簡潔、優(yōu)雅,本文將介紹如何在Spring Boot項(xiàng)目中整合新版Spring Security,需要的朋友可以參考下2024-02-02spring?retry方法調(diào)用失敗重試機(jī)制示例解析
這篇文章主要為大家介紹了spring?retry方法調(diào)用失敗重試機(jī)制的示例解析,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步2022-03-03Mybatis-plus常見的坑@TableField不生效問題
這篇文章主要介紹了Mybatis-plus常見的坑@TableField不生效問題,具有很好的參考價(jià)值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2022-01-01