前言

该需求就是在pdf/word中,根据定义的关键字标识,进行插入图片。不多说直接上代码。
工具类都是参照网上的进行小改一番

PDF根据关键字插入图片

1、引入依赖

<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.6</version>
</dependency>

2、插入图片工具类

import java.awt.*;
import java.io.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;import antlr.ANTLRError;
import com.itextpdf.awt.geom.Rectangle2D;
import com.itextpdf.text.BadElementException;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.parser.ImageRenderInfo;
import com.itextpdf.text.pdf.parser.PdfReaderContentParser;
import com.itextpdf.text.pdf.parser.RenderListener;
import com.itextpdf.text.pdf.parser.TextRenderInfo;
import com.landray.elasticsearch.rest.error.Error;
import com.landray.kmss.sys.log.util.F;public class PDFUtil_img {/*** filepath:文件路径加文件名* KEY_WORD:关键字 要求:(报表中关键字不能加粗,宋体,字号9)*    编辑PDF可使用迅捷PDF编辑器*/public static Map<String, Object> getKeyWords(String filePath, final List<String> keyWords) {final Map<String, Object> result = new HashMap<String, Object>();try {PdfReader pdfReader = new PdfReader(filePath);//获取PDF的页数int pageNum = pdfReader.getNumberOfPages();PdfReaderContentParser pdfReaderContentParser = new PdfReaderContentParser(pdfReader);for (int i = 1; i <= pageNum; i++) {final int currIndex = i;pdfReaderContentParser.processContent(currIndex, new RenderListener() {@Overridepublic void renderText(TextRenderInfo textRenderInfo) {String text = textRenderInfo.getText(); // 整页内容if (null != text && keyWords.contains(text)) {Rectangle2D.Float boundingRectange = textRenderInfo.getBaseline().getBoundingRectange();List<Map<String, Object>> locationList = (List<Map<String, Object>>) result.get(text);if (locationList == null) {locationList = new ArrayList<Map<String, Object>>();result.put(text, locationList);}Map<String, Object> location = new HashMap<String, Object>();location.put("x", boundingRectange.x);location.put("y", boundingRectange.y);location.put("width", boundingRectange.width);location.put("height", boundingRectange.height);location.put("pageNo", currIndex);locationList.add(location);}}@Overridepublic void renderImage(ImageRenderInfo arg0) {}@Overridepublic void endTextBlock() {}@Overridepublic void beginTextBlock() {}});}pdfReader.close();} catch (IOException e) {e.printStackTrace();}return result;}public static void addImg(PdfStamper stamper, Map<String, Object> location, String imagePath) {for (int i = 0; i < 1; i++) {Image image = null;try {image = Image.getInstance(imagePath, false);float imgWidth = image.getWidth() * 0.05f + 3;float imgHeight = image.getHeight() * 0.05f - 3;PdfContentByte pdfContentByte = stamper.getOverContent((int) location.get("pageNo"));//设置图片大小image.scaleAbsolute(imgWidth, imgHeight);//设置图片位置image.setAbsolutePosition((Float) location.get("x"), (Float) location.get("y") - 4);// X Y的位置System.out.println("x:" + (Float) location.get("x"));System.out.println("y:" + ((Float) location.get("y") - 4));pdfContentByte.addImage(image);System.out.println("插入成功");} catch (Exception e) {e.printStackTrace();}}}public static void main(String[] args) throws Exception {//模板的路径String templatePath = "D:\\用户\\***.pdf";//生成的新文件路径String newPDFPath = "D:\\用户\\***_update.pdf";//解析文件PdfReader reader = new PdfReader(templatePath);FileOutputStream fOut = new FileOutputStream(newPDFPath);PdfStamper stamper = new PdfStamper(reader, fOut);//关键字集合List<String> keyWords = new ArrayList<>();keyWords.add("$sign$");keyWords.add("$sh$");keyWords.add("$gy$");Map<String, Object> result = getKeyWords(templatePath, keyWords);System.out.println(result);for (Map.Entry<String, Object> entry : result.entrySet()) {String key = entry.getKey();List<Map<String, Object>> locationList = (List<Map<String, Object>>) entry.getValue();if (!locationList.isEmpty()) {addImg(stamper, locationList.get(0), "D:\\用户\\sign.png");//图片路径}}//设置不可编辑stamper.setFormFlattening(true);stamper.close();// 将输出流关闭fOut.close();reader.close();}//拷贝文件的方法(根据自身需求选择)private static void copyFileUsingStream(File file, File newFile) throws IOException {InputStream is = null;OutputStream os = null;try {is = new FileInputStream(file);os = new FileOutputStream(newFile);byte[] buffer = new byte[1024];int length;while ((length = is.read(buffer)) > 0) {os.write(buffer, 0, length);}} finally {if (is != null)is.close();if (os != null)os.close();}}/*** @param tmp       临时文件路径* @param PDFPath   PDF全路径* @param keyWords  关键字* @param imagePath 图片路径* @throws Exception*/   //该方法是插入图片且文件名不变,从而实现"原文件"上进行插入。(根据自身需求选择)public static void pdfover(String tmp, String PDFPath, List<String> keyWords, String imagePath) throws Exception {File file = new File(PDFPath);File tempFile = null;//过滤不合规路径名String tempPath = tmp.replaceAll("[^\\u4e00-\\u9fa5\\u4e00-\\u9fa5a-zA-Z0-9~!@#$%^&( )_\\-{}’]", "");if (file != null && file.exists()) {copyFileUsingStream(file, new File(tempPath));file.delete();PdfReader reader = new PdfReader(tempPath);FileOutputStream fOut = new FileOutputStream(PDFPath);PdfStamper stamper = new PdfStamper(reader, fOut);Map<String, Object> result = getKeyWords(tempPath, keyWords);if (result.size() > 0) {for (Map.Entry<String, Object> entry : result.entrySet()) {String key = entry.getKey();List<Map<String, Object>> locationList = (List<Map<String, Object>>) entry.getValue();if (!locationList.isEmpty()) {for (int i = 0; i < locationList.size(); i++) {addImg(stamper, locationList.get(i), imagePath);}}}}if (result.size() == 0) {copyFileUsingStream(new File(tempPath), new File(PDFPath));}//设置不可编辑stamper.setFormFlattening(true);stamper.close();// 将输出流关闭fOut.close();reader.close();//删除临时文件tempFile = new File(tempPath);if (tempFile.exists()) {tempFile.delete();}}}
}

注意:

1、PDF设置关键字时,转Word设置再转PDF是无法正确识别关键字,这边建议比较好用的PDF编辑器:迅捷PDF编辑器。

2、pdfover和copyFileUsingStream方法自行选择,用不到可以自行删除。

3、代码有的考虑的不是很全,各位大佬可以自行优化。

Word根据关键字插入图片

Word插入我这有两种,可自行选择,都是从网上搜索然后小改

1、方式一

1.1、导入依赖

<!--注意:word中要使用循环等标签必须单独导入以下依赖-->
<dependency><groupId>org.apache.poi</groupId><artifactId>ooxml-schemas</artifactId><version>1.4</version>
</dependency>
<!-- word导出  方式:easypoi-->
<dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-base</artifactId><version>4.3.0</version>
</dependency>
<dependency><groupId>cn.afterturn</groupId><artifactId>easypoi-web</artifactId><version>4.3.0</version>
</dependency>

1.2、工具类

import java.io.*;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;import cn.afterturn.easypoi.entity.ImageEntity;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.springframework.util.Assert;import cn.afterturn.easypoi.word.WordExportUtil;
import org.springframework.web.multipart.MultipartFile;public class WordUtil {/*** 生成Word** @param map* @param outputStream* @return*/public static boolean PoiDown(Map<String, Object> map, OutputStream outputStream) {//导入模板XWPFDocument xwpfDocument = null;try {xwpfDocument = WordExportUtil.exportWord07("templates/template.docx", map);//使用流写出xwpfDocument.write(outputStream);//刷新关闭流outputStream.flush();outputStream.close();System.out.println("work is over !");} catch (Exception exception) {exception.printStackTrace();return false;}return true;}/*** 根据用户模板替换 {{photo}} 图片* @param word* @param map* @param outputStream* @return*/public static boolean WordPhoto( XWPFDocument word, Map<String, Object> map, OutputStream outputStream) {try {WordExportUtil.exportWord07(word, map);//使用流写出word.write(outputStream);outputStream.flush();outputStream.close();System.out.println("work is over !");} catch (Exception exception) {exception.printStackTrace();return false;}return true;}/*** 导出word* <p>第一步生成替换后的word文件,只支持docx</p>* <p>第二步下载生成的文件</p>* <p>第三步删除生成的临时文件</p>* 模版变量中变量格式:{{foo}}** @param is       word模板文件流* @param temDir   生成临时文件存放地址* @param fileName 文件名* @param params   替换的参数* @param request  HttpServletRequest* @param response HttpServletResponse*/public static void exportWord(InputStream is, String temDir, String fileName, Map<String, Object> params, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {Assert.notNull(is, "模板不能为空");Assert.notNull(temDir, "临时文件路径不能为空 ");Assert.notNull(fileName, "导出文件名不能为空 ");Assert.isTrue(fileName.endsWith(".docx"), "word导出请使用docx格式");if (!temDir.endsWith("/")) {temDir = temDir + File.separator;}File dir = new File(temDir);if (!dir.exists()) {dir.mkdirs();}try {String userAgent = request.getHeader("user-agent").toLowerCase();if (userAgent.contains("msie") || userAgent.contains("like gecko")) {fileName = URLEncoder.encode(fileName, "UTF-8");} else {fileName = new String(fileName.getBytes("utf-8"), "ISO-8859-1");}MyXWPFDocument doc = new MyXWPFDocument(is);WordExportUtil.exportWord07(doc, params);String tmpPath = temDir + fileName;FileOutputStream fos = new FileOutputStream(tmpPath);doc.write(fos);// 设置强制下载不打开response.setContentType("application/force-download");// 设置文件名response.addHeader("Content-Disposition", "attachment;fileName=" + fileName);OutputStream out = response.getOutputStream();doc.write(out);out.close();} catch (Exception e) {e.printStackTrace();} finally {delFileWord(temDir, fileName);//这一步看具体需求,要不要删}}/*** 删除零时生成的文件*/public static void delFileWord(String filePath, String fileName) {File file = new File(filePath + fileName);File file1 = new File(filePath);file.delete();file1.delete();}public static void main(String[] args) throws Exception {//存放关键字映射的数据// key:word中的关键字  value:映射的数据Map<String,Object> map = new HashMap();//存放基本数据map.put("name","张三");map.put("sex","男");map.put("mz","汉族");//存放照片ImageEntity img = new ImageEntity();img.setHeight(100);//高img.setWidth(130);//宽//图片路径、类型img.setUrl("图片路径\\Saved Pictures\\avatar.jpg");img.setType(ImageEntity.URL);map.put("photo",img);//导入模板,模板中是写有关键字的XWPFDocument xwpfDocument = WordExportUtil.exportWord07("模板路径\\template.docx", map);//使用流写出到OutputStream os = new FileOutputStream("生成路径\\test.docx");xwpfDocument.write(os);//刷新关闭流os.flush();os.close();System.out.println("work is over !");}
}

2、方式二

2.1、引入依赖

<dependency><groupId>net.sf.jacob-project</groupId><artifactId>jacob</artifactId><version>1.14.3</version>
</dependency>

2.2、工具类

package com.landray.kmss.lszn.knowledge.util;import java.io.*;
import java.util.ArrayList;
import java.util.List;import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.landray.kmss.sys.log.util.F;public class WordUtil_img {// word运行程序对象private ActiveXComponent word;// 所有word文档集合private Dispatch documents;// word文档private Dispatch doc;// 选定的范围或插入点private Dispatch selection;// 保存退出private boolean saveOnExit;/*** 是否可见word程序* @param visible true-可见word程序,false-后台默默执行。*/public WordUtil_img(boolean visible) {word = new ActiveXComponent("Word.Application");word.setProperty("Visible", new Variant(visible));documents = word.getProperty("Documents").toDispatch();}/*** 打开一个已经存在的Word文档* @param docPath 文件的路径*/public void openDocument(String docPath) {doc = Dispatch.call(documents, "Open", docPath).toDispatch();selection = Dispatch.get(word, "Selection").toDispatch();}/*** 全局将指定的文本替换成图片* @param findText* @param imagePath*/public void replaceAllImage(String findText, String imagePath, int width, int height){moveStart();while (find(findText)){Dispatch picture = Dispatch.call(Dispatch.get(getSelection(), "InLineShapes").toDispatch(), "AddPicture", imagePath).toDispatch();Dispatch.call(picture, "Select");Dispatch.put(picture, "Width", new Variant(width));Dispatch.put(picture, "Height", new Variant(height));moveStart();}}/*** 把插入点移动到文件首位置*/public void moveStart(){Dispatch.call(getSelection(), "HomeKey", new Variant(6));}/*** 获取当前的选定的内容或者插入点* @return 当前的选定的内容或者插入点*/public Dispatch getSelection(){if (selection == null)selection = Dispatch.get(word, "Selection").toDispatch();return selection;}/*** 从选定内容或插入点开始查找文本* @param findText 要查找的文本* @return boolean true-查找到并选中该文本,false-未查找到文本*/public boolean find(String findText){if(findText == null || findText.equals("")){return false;}// 从selection所在位置开始查询Dispatch find = Dispatch.call(getSelection(), "Find").toDispatch();// 设置要查找的内容Dispatch.put(find, "Text", findText);// 向前查找Dispatch.put(find, "Forward", "True");// 设置格式Dispatch.put(find, "Format", "True");// 大小写匹配Dispatch.put(find, "MatchCase", "True");// 全字匹配Dispatch.put(find, "MatchWholeWord", "True");// 查找并选中return Dispatch.call(find, "Execute").getBoolean();}/*** 文档另存为* @param savePath*/public void saveAs(String savePath){Dispatch.call(doc, "SaveAs", savePath);}/*** 关闭word文档*/public void closeDocument(){if (doc != null) {Dispatch.call(doc, "Close", new Variant(saveOnExit));doc = null;}}/*** * @param WordPath 读取的word路径* @param ImgPaht 图片路径* @param keyWord 关键字集合* @param NewPath 生成的word路径*/public static void WordInsertImg(String WordPath, String ImgPaht, List<String> keyWord,String NewPath) throws IOException {WordUtil_img demo = new WordUtil_img(false);//获取工具类对象demo.openDocument(WordPath);//打开word// 在指定位置插入指定的图片for (String key : keyWord) {demo.replaceAllImage(key,ImgPaht,100,50);//图片位置。长和宽。demo.saveAs(NewPath);//插入成功后生成的新word.doc/docx,//注意:生成的Word会带doc/docx后缀。demo.closeDocument();//关闭对象。System.out.println("插入成功");}}public static void main(String[] args) throws IOException {//关键字集合List<String> keyword = new ArrayList<>();keyword.add("$sign$");WordInsertImg("读取的word路径","插入的图片路径",keyword,"生成的word路径");}}

来源: 半末の博客

Java根据关键字在PDF/Word插入图片相关推荐

  1. java中生成pdf,插入图片,页眉、页脚、表格

    全栈工程师开发手册 (作者:栾鹏) java教程全解 java中生成pdf,插入图片,页眉.页脚.表格 import com.lowagie.text.*; import com.lowagie.te ...

  2. 解决 Java poi 3.8 等版本 操作 word 插入 图片 不成功的问题

    解决 Java poi 3.8等版本操作word插入图片不成功的问题 问题: 最近有一个需求是将Excel中的数据转换到word中,其中包括了文字和图片, 在使用 poi 3.8 向word中写入图片 ...

  3. Java Poi word 插入图片并添加边框

    Java Poi word 插入图片并添加边框 //得到Picture的Base64编码 Base64Picture p1; //打开Word文件 Resource resource = new Cl ...

  4. word插入图片不能打印出来,转成PDF后才能打印成功

    环景: word365 WPS windows 10专业版 问题描述: word插入图片不能直接打印,打印发送文件秒结束,没有任何提示,换个wps打印也是一样 原因分析: word格式估计有问题 解决 ...

  5. 使用poi-tl向word插入图片、文本、表格行循环

    使用poi-tl向word插入图片.文本.表格行循环 工作中难免会向word中操作数据,本文主要介绍poi-tl的使用,先来看效果图 核心介绍: 标签 1.插入文本标签 : {{var}} 2.插入图 ...

  6. PDF编辑器哪个好,如何在PDF中插入图片背景

    由于PDF文档不像Word那么容易编辑,并且具有较强的保密性,所以PDF文档的编辑需要借助其他第三方的PDF编辑器才能对PDF文件进行编辑,下面,我就教大家如何利用PDF编辑器在PDF中插入图片背景, ...

  7. PHP下使用FPDF在PDF中插入图片

    Cell函数,该函数主要用于向PDF 文档中插入文本. 通常,PDF 文档是由文本和图片共同组成的. FPDF 中使用Image函数向PDF中插入图片,其语法格式如下所示: Image(string ...

  8. word插入图片显示不全

    word插入图片,显示不全,只有部分. 调整步骤 图片尾部 光标定位到图片的尾部 单倍行距 右键,选择"段落",行间距选择"单倍行距" 图片就完成显示了

  9. wps office word 插入图片显示异常 只显示一个长条

    wps office word插入图片显示异常 只显示一个长条 如图: 原因: 可能是网络复制文字的时候含有了某些格式. 建议复制的文字, 复制到网页的地址框里, 再复制到word文档里,可以很好的消 ...

  10. word中图片为嵌入式格式时显示不全_word嵌入图片显示不全,教您word插入图片显示不全怎么办...

    相信大家在使用Word进行编辑文档过程中,经常都会遇到需要插入图片情况吧.然后有些时候是不是还会遇到图片显示不全或只显示图片一部分的,或者只显示图片的边框之类的情况呢?所以今天小编将给讲讲word插入 ...

最新文章

  1. 上海交大、华为海思提出X-volution,发力网络核心基础架构创新
  2. python编程在哪里写-Python自带的IDE在哪里
  3. Parallel Query Bitmap
  4. POI导出excel日期格式
  5. 直接进入ORACLE12C插件数据库
  6. python socket发送数组_利用pyprocessing初步探索数组排序算法可视化
  7. 牛客网(剑指offer) 第三题 输入一个链表,从尾到头打印链表每个节点的值。
  8. 介绍python修饰器的书_python修饰器
  9. 购物网站注册页面html,电商购物网站 - 实现注册
  10. CYYMysql 源码解读 4
  11. nodejs操作mysql查询返回的数据_nodejs连接mysql进行数据库查询返回前台数据的坑...
  12. 编译Android指定JDK/OpenJdk版本
  13. python中lstrip函数_python中strip(),lstrip(),rstrip()函数的使用讲解
  14. 权重的计算方法,主要有两种:1.线性加权法; 2.层次分析法
  15. Node.js 实现远程桌面监控
  16. 微信公众号内推送模板消息
  17. 浏览器主页被更改成7654主页
  18. 如何防止亚马逊账户关联?
  19. 软件项目估算永远不准怎么办?钱少时间紧未必是坏事
  20. 云服务器体验——搭建简单私人网盘

热门文章

  1. CSDN账号找回密码的解决方法(原手机号不能使用)
  2. alin的学习之路(Qt篇:三)(常用控件,自定义控件,事件捕捉)
  3. Mac上好用且免费的远程桌面SSH工具(FinalShell)
  4. jks转换 p12、keystore、pk8、x509.pem 命令
  5. 统计Java源代码中关键字的数目(每个关键字的数目)
  6. 学校网站模板s1_中学学校网站源码_学校网站管理系统
  7. 第八课 实战重启验证注册机制
  8. [图文教程]智学网电脑版下载_电脑上看智学网直播的几种方法
  9. vb mysql 查询_VB数据库记录查询四法
  10. 使用jQuery高效制作网页特效 第六章习题