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

前言

该需求就是在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() {
                    @Override
                    public 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);
                        }
                    }

                    @Override
                    public void renderImage(ImageRenderInfo arg0) {
                    }
                    @Override
                    public void endTextBlock() {
                    }
                    @Override
                    public 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路径");
    }

}

来源: 半末の博客

  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值