Java 使用 itext 向PDF插入数据和图片
一、下载Adobe Acrobat DC
二、制作模板
1、准备一个word模板,并转换成PDF格式
2、使用Adobe Acrobat DC打开PDF文档,并在右侧搜索框搜索表单,点击准备表单
3、点击开始,制作PDF表单
4、扫描完成后如下图,蓝白色框就是可编辑表单
5、点击表单编辑表单名称以及插入时的字体大小样式等,如果没有设置字体大小,数据写入时会将字体会根据表单的高度自适应大小
6、编辑完成后保存PDF模板
三、在Java中使用
import com.itextpdf.text.DocumentException;import com.itextpdf.text.Image;import com.itextpdf.text.Rectangle;import com.itextpdf.text.pdf.*;import java.io.*;import java.nio.file.Files;import java.util.Calendar;import java.util.HashMap;import java.util.Map;public class PDFUtil {private static void insertImage(AcroFields form, PdfStamper stamper, String filedName, String url) throws IOException, DocumentException {int pageNo = form.getFieldPositions(filedName).get(0).page;Rectangle signRect = form.getFieldPositions(filedName).get(0).position;float x = signRect.getLeft();float y = signRect.getBottom();Image image = Image.getInstance(url);// 获取操作的页面PdfContentByte under = stamper.getOverContent(pageNo);// 根据域的大小缩放图片image.scaleToFit(signRect.getWidth(), signRect.getHeight());// 添加图片image.setAbsolutePosition(x, y);under.addImage(image);}public static Boolean pdfTemplateInsert(String templateUrl, String outputFileUrl, Map<String, Object> templateValueMap, Map<String, String> templateImageMap) {boolean success = true;OutputStream os = null;PdfStamper ps = null;PdfReader reader = null;try {os = Files.newOutputStream(new File(outputFileUrl).toPath());//读取pdf表单reader = new PdfReader(templateUrl);//根据表单生成一个新的pdf文件ps = new PdfStamper(reader, os);//获取pdf表单AcroFields form = ps.getAcroFields();//给表单中添加中文字体BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);form.addSubstitutionFont(bf);if (null != templateValueMap && !templateValueMap.isEmpty()) {for (String key : templateValueMap.keySet()) {form.setField(key, String.valueOf(templateValueMap.get(key)));}}if (null != templateImageMap && !templateImageMap.isEmpty()) {for (String key : templateImageMap.keySet()) {insertImage(form, ps, key, templateImageMap.get(key));}}ps.setFormFlattening(true);} catch (Exception e) {success = false;} finally {try {ps.close();reader.close();os.close();} catch (Exception e) {e.printStackTrace();}}return success;}public static void main(String[] args) {//模板路径String inputUrl = "E:/Desktop/test/demo/itext-demo.pdf";//生成的文件路径String outputUrl = "E:/Desktop/test/demo/itext-demo-output.pdf";Map<String, Object> data = new HashMap<>();data.put("name", "张山");data.put("year", "2000年10月");data.put("phone", "13032451234");data.put("gangwei", "Java开发");data.put("introduceOneself", "熟练使用Java常用框架:Spring 、mybatis等");//图片地址String imageUrl = "E:/Desktop/test/demo/1.jpeg";Map<String, String> templateImageMap = new HashMap<>();templateImageMap.put("image", imageUrl);PDFUtil.pdfTemplateInsert(inputUrl, outputUrl, data, templateImageMap);}}