栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

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

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

前言

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

PDF根据关键字插入图片

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> locationList = (List>) result.get(text);
                            if (locationList == null) {
                                locationList = new ArrayList>();
                                result.put(text, locationList);
                            }

                            Map location = new HashMap();
                            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 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 keyWords = new ArrayList<>();
        keyWords.add("$sign$");
        keyWords.add("$sh$");
        keyWords.add("$gy$");

        Map result = getKeyWords(templatePath, keyWords);
        System.out.println(result);
        for (Map.Entry entry : result.entrySet()) {
            String key = entry.getKey();
            List> locationList = (List>) 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();
        }
    }
    	//该方法是插入图片且文件名不变,从而实现"原文件"上进行插入。(根据自身需求选择)
    public static void pdfover(String tmp, String PDFPath, List 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 result = getKeyWords(tempPath, keyWords);
            if (result.size() > 0) {
                for (Map.Entry entry : result.entrySet()) {
                    String key = entry.getKey();
                    List> locationList = (List>) 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、导入依赖


    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路径");
    }

}

来源: 半末の博客

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/722509.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号