AcroPro
使用AcroPro创建模板 先创建doc文件 编辑你想要生成pdf的模板 另存为.pdf格式的文件
用AcroPro打开文件点击右边最下方的 准备表单 点击开始 再点击上面Tt的图标编辑你要替换的内容 保存
基本内容准备完毕
代码
package com.example.demo.Test;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.*;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* @Author: wkg
* @Date: 2018/6/22 09:32
* @Description:
*/
@RestController
@RequestMapping("pdf")
public class PDFTemplate {
@RequestMapping("pdfDownload")
public void test(HttpServletResponse response) throws IOException, DocumentException {
response.setContentType("application/pdf");
response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode("实际导出的PDF名称", "UTF-8") + ".pdf");
//编码
response.setCharacterEncoding("UTF-8");
String fileName = "D:/1.pdf"; // pdf模板路径 可根据项目实际路径
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* 将要生成的目标PDF文件名称 */
PdfStamper ps = new PdfStamper(reader, bos);
/* 使用中文字体 */
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf);
/* 取出报表模板中的所有字段 */
AcroFields fields = ps.getAcroFields();
fields.setSubstitutionFonts(fontList);
fillData(fields, data());
/* 必须要调用这个,否则文档不会生成的 */
ps.setFormFlattening(true);
ps.close();
response.getOutputStream().write(bos.toByteArray());
bos.close();
}
private static void fillData(AcroFields fields, Map<String, String> data)
throws IOException, DocumentException {
for (String key : data.keySet()) {
String value = data.get(key);
fields.setField(key, value); // 为字段赋值,注意字段名称是区分大小写的
}
}
private static Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("qq", "test:");//qq ww就是在PDF中编辑的替换内容
data.put("ww", "xx第10000001号");
return data;
}
}
输入http://localhost:8080/pdf/pdfDownload