轉載自:http://blog.csdn.net/leeyefang/article/details/46805617
本文所要用到的工具或jar主要有:
adobe acrobat 這個主要用來制作pdf模闆、eclipse、 itext.jar、 解決中文的輸出問題,需要多下載下傳一個名為itextasian.jar的jar包。這個包裡面定義了與中文輸出相關的一些檔案。
pdf模闆效果如下:
java代碼:
[java]
view plain
copy
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;
}