1. 程式人生 > 其它 >使用word生成PDF模版,Java操作生成保單或合同

使用word生成PDF模版,Java操作生成保單或合同

依賴

<dependency>
	<groupId>org.apache.pdfbox</groupId>
	 <artifactId>pdfbox</artifactId>
	 <version>2.0.13</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itext-asian</artifactId>
	<version>5.2.0</version>
</dependency>
<dependency>
	<groupId>com.itextpdf</groupId>
	<artifactId>itextpdf</artifactId>
	<version>5.5.10</version>
</dependency>

程式碼參考

/**
 * 根據模板生成pdf
 *@param pdfName 檔名
 * @param data Map(String,Object)
 * @return 檔案儲存全路徑檔案
 */
public String createPDF(String pdfName, Map<String, Object> data) {
    PdfReader reader = null;
    AcroFields s = null;
    PdfStamper ps = null;
    ByteArrayOutputStream bos = null;

    String realPath = ResourceBundle.getBundle("systemconfig").getString("upLoadFolder") + File.separator + "comfirmationDoc";
    String dateFolder = DateFormatUtils.format(new Date(), "yyyyMMdd");
    String folderPath = realPath + File.separator + dateFolder;
    //建立上傳檔案目錄
    File folder = new File(folderPath);
    if (!folder.exists()) {
        folder.mkdirs();
    }
    //設定檔名
    String fileName = pdfName + "_" + DateFormatUtils.format(new Date(), "yyyyMMddhhmmss") + ".pdf";
    String savePath = folderPath + File.separator + fileName;

    try {
        String file = this.getClass().getClassLoader().getResource("comfirmTemplate.pdf").getPath();
        //設定字型
        String font = this.getClass().getClassLoader().getResource("YaHei.ttf").getPath();
        reader = new PdfReader(file);
        bos = new ByteArrayOutputStream();
        ps = new PdfStamper(reader, bos);
        s = ps.getAcroFields();
        //使用中文字型 使用 AcroFields填充值的不需要在程式中設定字型,在模板檔案中設定字型為中文字型 Adobe 宋體 std L
        BaseFont bfChinese = BaseFont.createFont(font, BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
        //設定編碼格式
        s.addSubstitutionFont(bfChinese);
        // 遍歷data 給pdf表單表格賦值
        for (String key : data.keySet()) {
            if (data.get(key) != null) {
                s.setField(key, data.get(key).toString());
            }
        }

        // 如果為false那麼生成的PDF檔案還能編輯,一定要設為true
        ps.setFormFlattening(true);
        ps.close();

        FileOutputStream fos = new FileOutputStream(savePath);

        fos.write(bos.toByteArray());
        fos.flush();
        fos.close();
        return savePath;
    } catch (IOException | DocumentException e) {
        logger.error("讀取檔案異常");
        e.printStackTrace();
        return "";
    } finally {
        try {
            bos.close();
            reader.close();
        } catch (IOException e) {
            logger.error("關閉流異常");
            e.printStackTrace();
        }
    }
}

[========]