前言
该需求就是在pdf/word中,根据定义的关键字标识,进行插入图片。不多说直接上代码。
工具类都是参照网上的进行小改一番
1、引入依赖
com.itextpdf itextpdf 5.5.6
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 {
public static Map getKeyWords(String filePath, final List keyWords) {
final Map result = new HashMap();
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() {
@Override
public void renderText(TextRenderInfo textRenderInfo) {
String text = textRenderInfo.getText(); // 整页内容
if (null != text && keyWords.contains(text)) {
Rectangle2D.Float boundingRectange = textRenderInfo
.getbaseline().getBoundingRectange();
List
注意:
1、PDF设置关键字时,转Word设置再转PDF是无法正确识别关键字,这边建议比较好用的PDF编辑器:迅捷PDF编辑器。
2、pdfover和copyFileUsingStream方法自行选择,用不到可以自行删除。
3、代码有的考虑的不是很全,各位大佬可以自行优化。
Word根据关键字插入图片Word插入我这有两种,可自行选择,都是从网上搜索然后小改
1、方式一1.1、导入依赖
org.apache.poi ooxml-schemas 1.4 cn.afterturn easypoi-base 4.3.0 cn.afterturn easypoi-web 4.3.0
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 {
public static boolean PoiDown(Map 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;
}
public static boolean WordPhoto( XWPFdocument word, Map 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;
}
public static void exportWord(InputStream is, String temDir, String fileName, Map 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 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、引入依赖
net.sf.jacob-project jacob 1.14.3
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;
public WordUtil_img(boolean visible) {
word = new ActiveXComponent("Word.Application");
word.setProperty("Visible", new Variant(visible));
documents = word.getProperty("documents").toDispatch();
}
public void opendocument(String docPath) {
doc = Dispatch.call(documents, "Open", docPath).toDispatch();
selection = Dispatch.get(word, "Selection").toDispatch();
}
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));
}
public Dispatch getSelection(){
if (selection == null)
selection = Dispatch.get(word, "Selection").toDispatch();
return selection;
}
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();
}
public void saveAs(String savePath){
Dispatch.call(doc, "SaveAs", savePath);
}
public void closedocument(){
if (doc != null) {
Dispatch.call(doc, "Close", new Variant(saveOnExit));
doc = null;
}
}
public static void WordInsertImg(String WordPath, String ImgPaht, List 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 keyword = new ArrayList<>();
keyword.add("$sign$");
WordInsertImg("读取的word路径",
"插入的图片路径",
keyword,
"生成的word路径");
}
}
来源: 半末の博客



