本文使用java引入apache提供的pdf操做工具生成pdf文件,主要是根據需求開發了一個util類,記錄一下學習和開發過程。java
pdfBox是apache提供的免費,開源的pdf操做工具,這個jar裏面囊括了全部的pdfbox操做工具類,導入這一個就夠了 ,使用起來很方便。數據庫
這裏使用maven引入jar包:apache
<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox --> <dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>2.0.13</version> </dependency>
工具類有兩個必須的元素:pdf模板文件和從數據庫中抽出的數據。服務器
pdf模板文件放在指定的路徑,下圖爲部分pdf模板文件:maven
模板文件能夠有多張,這裏只截取一張當作參考。工具
入參和返回值,以下圖:學習
很少說,直接上代碼字體
/**
* 根據模板生成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();
}
}
}
通過實際使用,代碼可以正常生成pdf文件,在這裏就不上圖了this