首页 > 编程 > Java > 正文

java通过PDF模板填写PDF表单

2019-11-26 09:34:00
字体:
来源:转载
供稿:网友

本文实例为大家分享了java通过PDF模板填写PDF表单的具体代码,包括图片,供大家参考,具体内容如下

需要用到的java包:

 itext.jar、iTextAsian.jar的JAR包。这个包里面定义了与中文输出相关的一些文件。

编写的表单如下:

import java.io.ByteArrayOutputStream;import java.io.FileOutputStream;import java.io.IOException;import java.util.HashMap;import java.util.Map; import com.itextpdf.text.DocumentException;import com.itextpdf.text.Image;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.AcroFields;import com.itextpdf.text.pdf.BaseFont;import com.itextpdf.text.pdf.PdfContentByte;import com.itextpdf.text.pdf.PdfReader;import com.itextpdf.text.pdf.PdfStamper; /** * pdf工具类 * @author MOSHUNWEI * @since 2018-02-01 */public class PDFUtil {  /** * 根据模板生成pdf * @param data Map(String,Object) * @return */ public static boolean createPDF(String path,Map<String, Object> data) { PdfReader reader = null; AcroFields s = null; PdfStamper ps = null; ByteArrayOutputStream bos = null; try { reader = new PdfReader("D://test.pdf"); bos = new ByteArrayOutputStream(); ps = new PdfStamper(reader, bos); s = ps.getAcroFields();  /** * 使用中文字体 使用 AcroFields填充值的不需要在程序中设置字体,在模板文件中设置字体为中文字体 Adobe 宋体 std L */ BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", false); /** * 设置编码格式 */ s.addSubstitutionFont(bfChinese);   // 遍历data 给pdf表单表格赋值 for (String key : data.keySet()) { s.setField(key,data.get(key).toString()); }  // 如果为false那么生成的PDF文件还能编辑,一定要设为true ps.setFormFlattening(true); /** * 添加图片 */ String imgpath="D:/n5.jpg"; int pageNo = s.getFieldPositions("img").get(0).page; Rectangle signRect = s.getFieldPositions("img").get(0).position; float x = signRect.getLeft(); float y = signRect.getBottom(); // 读图片 Image image = Image.getInstance(imgpath); // 获取操作的页面 PdfContentByte under = ps.getOverContent(pageNo); // 根据域的大小缩放图片 image.scaleToFit(signRect.getWidth(), signRect.getHeight()); // 添加图片 image.setAbsolutePosition(x, y); under.addImage(image);  @SuppressWarnings("resource") FileOutputStream fos = new FileOutputStream("d://shouju_fb.pdf"); fos.write(bos.toByteArray()); return true; } catch (IOException | DocumentException e) { System.out.println("读取文件异常"); e.printStackTrace(); return false; }finally { try { bos.close(); ps.close(); reader.close(); } catch (IOException | DocumentException e) { System.out.println("关闭流异常"); e.printStackTrace(); } }  }  public static void main(String[] args) { Map<String, Object> data = new HashMap<String, Object>(); data.put("id", "12312321"); data.put("name", "小帅哥"); data.put("sex", "男"); data.put("age", "21"); PDFUtil.createPDF("D:/n5.jpg",data); }} 

还有相应的编辑pdf表单的工具,默认用Adobe Acrobat。

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持武林网。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表