java實(shí)現(xiàn)在pdf模板的指定位置插入圖片

本文實(shí)例為大家分享了java在pdf模板的指定位置插入圖片的具體代碼,供大家參考,具體內(nèi)容如下

創(chuàng)新互聯(lián)主要從事成都做網(wǎng)站、網(wǎng)站制作、成都外貿(mào)網(wǎng)站建設(shè)、網(wǎng)頁設(shè)計、企業(yè)做網(wǎng)站、公司建網(wǎng)站等業(yè)務(wù)。立足成都服務(wù)普洱,10余年網(wǎng)站建設(shè)經(jīng)驗(yàn),價格優(yōu)惠、服務(wù)專業(yè),歡迎來電咨詢建站服務(wù):028-86922220

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í)有所幫助,也希望大家多多支持創(chuàng)新互聯(lián)。

本文名稱:java實(shí)現(xiàn)在pdf模板的指定位置插入圖片
文章網(wǎng)址:http://muchs.cn/article48/ipjshp.html

成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供品牌網(wǎng)站設(shè)計App設(shè)計、軟件開發(fā)、建站公司、品牌網(wǎng)站制作

廣告

聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)

成都網(wǎng)站建設(shè)