一,用Adobe Acrobat pro軟件制作模板
(1)先用word做出模板界面
(2)文件另存為pdf格式文件
(3)通過Adobe Acrobat pro軟件打開剛剛用word轉換成的pdf文件
(4)點擊右邊的"准備表單"按鈕,沒有請在更多里面找
選擇"xxx.pdf"選擇開始(選擇工具欄里面添加文本域,可以選擇在任意位置添加你想要的文本域。在文本域屬性框可以設置文本的屬性,例如文本的名稱、字體大小、位置等)
(5)做完上面的工作后,直接"另存為"將pdf存儲就可以
到此模板就制作完成啦!接下來就開始寫代碼啦
————————————————
public static void exportPdf(String templatePath, Map<String, Object> data) {
PdfReader reader = null;
AcroFields s = null;
PdfStamper ps = null;
ByteArrayOutputStream bos = null;
try {
//設置字體
String font = "src\\main\\resources\\pdf\\Microsoft-YaHei.ttf";
reader = new PdfReader(templatePath);
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) {
String s1 = data.get(key).toString();
s.setField(key, s1);
}
}
// 如果為false那么生成的PDF文件還能編輯,一定要設為true
ps.setFormFlattening(true);
ps.close();
HttpServletResponse response = ServletUtil.getResponse();
response.setCharacterEncoding("UTF-8");
response.setHeader("content-Type", "application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("car_bill.pdf", "UTF-8"));
//用流寫出
try{
/* 用流將數據寫給前端 */
OutputStream os = response.getOutputStream();
os.write(bos.toByteArray());
os.flush();
os.close();
}catch (IOException ioe){
ioe.printStackTrace();
}
// 用文件流寫出
// String savePath = "文件保存路徑";
// FileOutputStream fos = new FileOutputStream(savePath);
//
// fos.write(bos.toByteArray());
// fos.flush();
// fos.close();
} catch (IOException | DocumentException e) {
log.error("讀取文件異常");
throw new HwBusinessException(BasicCode.ERROR, "生成PDF失敗!");
} finally {
try {
bos.close();
reader.close();
} catch (IOException e) {
log.error("關閉流異常");
e.printStackTrace();
}
}
}
參考鏈接:https://blog.csdn.net/qq_33624558/java/article/details/82891411