java中将表单转换为PDF
经过⽹上搜索⼤概有三种⽅式:PDF模板数据填充,html代码转换pdf,借⽤wkhtmltopdf⼯具
⼀ .PDF模板数据填充
1.新建word,在word中做出和表单⼀样的布局的空表单,然后另存为pdf;
2.⽤pdf编辑⼯具,⽤准备表单这个⼯具在需要填充动态数据的地⽅设置⽂本框或图像框,起好标签名。
3.根据标签名向pdf中插⼊数据,并将PDF导出在指定位置。
String rootPath="d:/";
String path=rootPath+"dzyjjsdjd.pdf";
System.out.println("电⼦⽂件移交与接收登记单模板位置:"+path);
SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");//设置⽇期格式
String newPath=rootPath+df.format(new Date())+"dzyjjsdjd.pdf";
/
/读⼊pdf表单
PdfReader reader = new PdfReader(path);
//根据表单⽣成⼀个新的pdf
PdfStamper ps = new PdfStamper(reader,new FileOutputStream(newPath));
//获取pdf表单
AcroFields s = ps.getAcroFields();
//给表单添加中⽂字体这⾥采⽤系统字体。不设置的话,中⽂可能⽆法显⽰
BaseFont bf = ateFont("C:/WINDOWS/Fonts/SIMSUN.TTC,1",BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
s.addSubstitutionFont(bf);
//遍历pdf表单表格,同时给表格赋值
Map<String,String> paraMap=getMapData(accept);//⾃⼰的数据,按模板中设置的表单标签封装进map
for (String key : paraMap.keySet()) {
if(key.equals("yz1")){//获取标签为yz1的pdf标签,设置其值
String value = (key);
tempImgPath1=rootPath+"yz1.png";
insertImage(ps, tempImgPath1,"yz1",s);
//图⽚插⼊后需要去除掉设置的这个图⽚框,否则会遮当前插⼊的图⽚
pdf转html
}else{
String value = (key);
s.setField(key, value); // 为字段赋值,注意字段名称是区分⼤⼩写的
}
}
ps.setFormFlattening(true); // 这句不能少
ps.close();
reader.close();
/**
* 向pdf中插⼊图⽚
* @param ps pdf对象
* @param img 需要插⼊的图⽚路径
* @param col 需要插⼊图⽚的pdf字段标签名
* @param s  pdf字段
*/
public void insertImage(PdfStamper ps, String img,String col,AcroFields s){
try{
List<AcroFields.FieldPosition> list = s.getFieldPositions(col);
Rectangle signRect = (0).position;
Image image = Instance(img);
PdfContentByte under = ps.getOverContent(1); //要插⼊图⽚的页数,现在只有1页
float x = Left();
float y = Bottom();
System.out.println(x);
System.out.println(y);
image.setAbsolutePosition(x, y);
image.Width(), Height());
under.addImage(image);
}
catch (Exception e){
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 插⼊⽂本
*
* @return
* @author WangMeng
* @date 2016年6⽉16⽇
*/
public static void insertText(PdfStamper ps, AcroFields s)
{
List<AcroFields.FieldPosition> list = s.getFieldPositions("CONNECT_NAME");
Rectangle rect = (0).position;
PdfContentByte cb = ps.getOverContent(1);
PdfPTable table = new PdfPTable(1);
float tatalWidth = Right() - Left() - 1;
table.setTotalWidth(tatalWidth);
PdfPCell cell = new PdfPCell(new Phrase(CreateChunk()));
cell.Top() - Bottom() - 1);
cell.setBorderWidth(0);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setLeading(0, (float) 1.1);
table.addCell(cell);
table.writeSelectedRows(0, -1, Left(), Top(), cb);
}
第⼆种:将html代码转换为pdf
import java.io.ByteArrayInputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import Document;
import PageSize;
import pdf.PdfWriter;
import l.xml.XMLWorkerHelper;
public class HtmlToPDF {
public static void main(String[] args) {
try {
Document document = new Document(PageSize.LETTER);
PdfWriter pdfWriter = Instance(document,
new FileOutputStream("c://temp//testpdf.pdf"));
document.open();
document.addAuthor("ysjiang");
document.addCreator("ysjiang");
document.addSubject("test");
document.addCreationDate();
document.addTitle("XHTML to PDF");
XMLWorkerHelper worker = Instance();
String str = "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"/TR/xhtml1/DTD/xhtml1-transitional.dtd\">"
+ "<html xmlns=\"/1999/xhtml\">"
+ "<head>"
+ "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />"
+ "<title>HTML 2 PDF</title>"
+ "<style type=\"text/css\">"
+ "<!--"
+ "body {"
+ "    margin: 20px;"
+ "}"
+ "-->"
+ "</style>"
+ "</head>"
+ "<body>"
+ "<div style=\"width:90%; height:160px;\">多情浪漫的⼈,其实内⼼的情感是⾮常脆弱的,感情的末梢,有那么⼀点⼉敏感,还有那么⼀点⼉想⼊⾮⾮。所以和浪漫多情的⼈在⼀起,⾔语⼀定要斯⽂,说话不能像⽕炮,态度⼀定要温柔                    + "</div>"
+ "<hr/>"
+ "<table cellspacing=\"0\" cellpadding=\"0\" style=\"width:100%; border:1px;\">"
+ "  <tr>"
+ "  <td style=\"width:30%\">table中的中⽂显⽰及换⾏"
+ "  </td>"
+ "  <td>多情浪漫的⼈,其实内⼼的情感是⾮常脆弱的,感情的末梢,有那么⼀点⼉敏感,还有那么⼀点⼉想⼊⾮⾮。所以和浪漫多情的⼈在⼀起,⾔语⼀定要斯⽂,说话不能像⽕炮,态度⼀定要温柔、语⽓也要婉转。遇到对⽅的⼀个                    + "  </td>"
+ "  </tr>"
+ "  <tr>"
+ "  <td colspan=\"2\">"
+ "      <img src=\"0.jpg\" />"
+ "  </td>"
+ "  </tr>"
+ "</table>" + "</body>" + "</html>";
// worker.parseXHtml(pdfWriter, document, new FileInputStream("C:\\tmp\\a.htm"), null, new AsianFontProvider());
String url="G:/workProject_ces/zjdzyjjsxt/WebRoot/module/receive/register/input.jsp?pid=4&sign=0&tagg=undo&workitemId=149982394754705&activityName=rk&returnReason=&activityId=receive&time=Mon Jul 17 2017 14:25:49 GMT+            worker.parseXHtml(pdfWriter, document, new Bytes()), null, new AsianFontProvider());
new FileInputStream(url));
document.close();
System.out.println("Done.");
} catch (Exception e) {
e.printStackTrace();
}
}
}
第三种参照blog.csdn/zhangkezhi_471885889/article/details/52184700,因为要借助外部⼯具,所以部署时候会稍微⿇烦点,根据需要选⾃⼰的⽅式