JAVA在PDF指定位置赋值
首先用world画好模版,给需要填值的地方留下空间,另存为:pdf……现在这种PDF存值是不行的!你还需要一个工具:Adobe LiveCycle Designer ES2
如下图:打开你生成的pdf模版
大家可以看到右上角是一些组件,有:TextField,CheckBox……等,你懂得!直接托到你指定的位置就可以啦!
然后用JAVA程序读取,赋值,生成新的有值的PDF就ok了
还需要一个jar包:itext-2.0.3.jar 网上一大把
个人封装了一个类,使得非常简单了,代码如下:
01
package com.sun;
02
03
import java.io.ByteArrayOutputStream;
04
import java.io.FileNotFoundException;
05
import java.io.FileOutputStream;
06
import java.io.IOException;
07
import java.util.HashMap;
08
import java.util.Iterator;
09
import java.util.Set;
10
11
import com.lowagie.text.Document;
12
import com.lowagie.text.DocumentException;
13
import com.lowagie.text.pdf.AcroFields;
14
import com.lowagie.text.pdf.PdfCopy;
15
import com.lowagie.text.pdf.PdfImportedPage;
16
import com.lowagie.text.pdf.PdfReader;
17
import com.lowagie.text.pdf.PdfStamper;
18
19
public class PdfTemplate {
20
/**
21
* 赋值并生成新的PDF文档
22
* @param templatePDF pdf模版
23
* @param outFile 输出的PDF Name
24
* @param hashMap templatePDF对应的数据
25
* <a href="http://my.oschina.net/arthor" class="referer" target="_blank">@author</a> JIA-G-Y
26
* 二〇一二年八月二十日 17:20:36
27
*/
28
public static void doSomeThing(String templatePDF,String outFile,HashMap<String,String> hashMap){
29
try {
30
FileOutputStream fos = new FileOutputStream(outFile);
31
PdfReader reader = new PdfReader(templatePDF);
32
ByteArrayOutputStream baos = new ByteArrayOutputStream();
33
PdfStamper stamp = new PdfStamper(reader,baos);
34
AcroFields form = stamp.getAcroFields();
35
form=setField(form,hashMap);
36
stamp.setFormFlattening(true);
37
stamp.close();
38
Document doc = new Document();
39
PdfCopy pdfCopy = new PdfCopy(doc, fos);
40
doc.open();
41
PdfImportedPage impPage = pdfCopy.getImportedPage(new PdfReader(baos.toByteArray()), 1);
42
pdfCopy.addPage(impPage);
43
doc.close();
44
} catch (FileNotFoundException e) {
45
e.printStackTrace();
46
} catch (IOException e) {
47
e.printStackTrace();
48
} catch (DocumentException e) {
49
e.printStackTrace();
50
}
51
52
}
53
@SuppressWarnings({ "unchecked", "unchecked" })
54
public static AcroFields setField(AcroFields form,HashMap<String,String> fieldMap) {
55
Set it=fieldMap.keySet();
56
Iterator itr=it.iterator();
57
while(itr.hasNext()){
58
try {
59
Object temp = itr.next();
60
form.setField(temp.toString(), fieldMap.get(temp.toString()));
61
} catch (IOException e) {
62
e.printStackTrace();
63
} catch (DocumentException e) {
64
e.printStackTrace();
65
}
66
}
67
return form;
68
}
69
}
测试:
01
package com.sun;
02
03
import java.util.HashMap;
04
05
public class Test {
06
public static void main(String[] args) {
07
HashMap<String, String> hashMap = new HashMap<String, String>();
08
hashMap.put("Code", "JIA-G-Y 2012-08-20");
09
10
hashMap.put("Tel", "400-8888888");
11
hashMap.put("Address", "1859101");
12
hashMap.put("GM", "2");
13
PdfTemplate.doSomeThing(".\\SUN.pdf","NewsPDF"+".pdf", hashMap);
14
}
15
}
模版:
结果:
补充:软件开发 , Java ,