本文所要用到的工具或jar主要有:
Adobe Acrobat 这个主要用来制作PDF模板、eclipse、 itext.jar、 解决中文的输出问题,需要多下载一个名为iTextAsian.jar的JAR包。这个包里面定义了与中文输出相关的一些文件。
pdf模板效果如下:
JAVA代码:
package com.yfli.iText;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import com.lowagie.text.DocumentException;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
public class Test {
public static void main(String[] args) throws Exception {
test();
System.out.println("success");
}
public static void test() throws IOException, DocumentException {
String fileName = "F:/zxing/zs/zsTemp.pdf"; // pdf模板
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
/* 将要生成的目标PDF文件名称 */
PdfStamper ps = new PdfStamper(reader, bos);
PdfContentByte under = ps.getUnderContent(1);
/* 使用中文字体 */
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();
OutputStream fos = new FileOutputStream("F:/zxing/zs/zsResult.pdf");
fos.write(bos.toByteArray());
fos.flush();
fos.close();
bos.close();
}
public 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); // 为字段赋值,注意字段名称是区分大小写的
}
}
public static Map<String, String> data() {
Map<String, String> data = new HashMap<String, String>();
data.put("name", "test:");
data.put("bianhao", "xx第10000001号");
data.put("amount", "1000");
data.put("date","2015年7月7日");
return data;
}
}