java 生成PDF文件
制作pdf模板文件
工具:Adobe Acrobat;
1、选择准备表单
2、设置表单
依赖jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13</version>
</dependency>
<!-- 解决中文字符问题 -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
JAVA代码:
// 定义一个与模板表单中名称对应的bean
class ContentBean {
private String realAmount;
private String payType;
private String teacherNickName;
private String courseName;
}
public class PDFUtils {
// 模板文件
private static final String INPUT_FILE_NAME = "E:\\templat.pdf";
//生成的pdf文件
private static final String OUTPUT_FILE_NAME = "E:\\create.pdf";
/**
* @param inputFileName 模板文件
* @param outFileName 生成的文件
* @param content 转换的bean
*/
public static void convertByTemplate(String inputFileName,
String outFileName,
Object content) throws IOException, DocumentException, IllegalAccessException {
PdfStamper ps = null;
OutputStream fos = null;
ByteArrayOutputStream bos = null;
try {
PdfReader reader = new PdfReader(inputFileName);
bos = new ByteArrayOutputStream();
// 将要生成的目标PDF文件名称
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, getData(content));
//更改jdk的默认xml解析器
//System.setProperty("javax.xml.parsers.DocumentBuilderFactory", "com.sun.org.apache.xerces.internal.jaxp.DocumentBuilderFactoryImpl");
// 必须要调用这个,否则文档不会生成的
ps.setFormFlattening(true);
ps.close();
fos = new FileOutputStream(outFileName);
fos.write(bos.toByteArray());
fos.flush();
fos.close();
bos.close();
} finally {
//关流 ...
}
}
/** 填充表单 */
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(Object o) throws IllegalAccessException {
Map<String, String> data = new HashMap<>();
Field[] fields = o.getClass().getDeclaredFields();
for (Field field : fields) {
field.setAccessible(true);
data.put(field.getName(), field.get(o).toString());
}
return data;
}
public static void main(String[] args) throws DocumentException, IllegalAccessException, IOException {
ContentBean bean = new ContentBean();
bean.setPayType("支付宝");
bean.setTeacherNickName("小学英语老师");
bean.setCourseName("英语");
bean.setTotalCourseNum(30);
convertByTemplate(INPUT_FILE_NAME, OUTPUT_FILE_NAME, bean);
}
}