Java 使用 itext 向pdf插入数据和图片 一、下载Adobe Acrobat DC 二、制作模板 1、准备一个Word模板,并转换成PDF格式 2、使用Adobe Acrobat DC打
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); }}
--结束END--
本文标题: Java 使用 itext 向PDF插入数据和图片
本文链接: https://lsjlt.com/news/391998.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
2024-04-01
2024-04-03
2024-04-03
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0