POI 处理导出Word图片问题

2022-06-03  本文已影响0人  十二找十三
<!-- poi dependency-->
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml</artifactId>
    <version>3.15</version>
</dependency>
<dependency>
    <groupId>org.apache.poi</groupId>
    <artifactId>poi-ooxml-schemas</artifactId>
    <version>3.15</version>
</dependency>
package com.ccbckj.common.controller.Export;


import org.apache.poi.xwpf.usermodel.*;
import org.apache.xmlbeans.XmlException;
import org.apache.xmlbeans.XmlToken;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

// 演示 图片写入word
public class POIDemo extends XWPFDocument {
    public static void main(String[] args) throws Exception {
        String sourceFile = "E:\\ccbckj\\download\\poi\\wfryzdjktjb.docx";
        String targetFile = "E:\\ccbckj\\download\\poi\\1.docx";
        String imageFile = "E:\\ccbckj\\download\\poi\\test.png";
        String httpImageFile = "http://172.16.1.54:3001/ftpworkdir/test/1iWJ4BVVBvs3YFuM-1646356334552.jpeg";

        Map<String, Object> params = new HashMap<>();

        Map<String, Object> header = new HashMap<String, Object>();
        header.put("width", 100);
        header.put("height", 150);
        header.put("type", "jpg");
//        header.put("content", imageFileToByteArray(new FileInputStream(imageFile))); // 本地图片
        header.put("content", getImageFromNetByUrl(httpImageFile));  // 远程网络图片

        params.put("${wfzdgkFtp}", header);

        getWord(sourceFile, params, targetFile);

    }

    public static byte[] getImageFromNetByUrl(String strUrl) {
        try {
            URL url = new URL(strUrl);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.setRequestMethod("GET");
            conn.setConnectTimeout(10 * 1000);
            if(conn.getInputStream()!=null){
                InputStream inStream = conn.getInputStream();
                byte[] btImg = readInputStream(inStream);
                return btImg;
            }
            return null;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    public static byte[] readInputStream(InputStream inStream) throws Exception {
        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] buffer = new byte[10240];
        int len = 0;
        while ((len = inStream.read(buffer)) != -1) {
            outStream.write(buffer, 0, len);
        }
        inStream.close();
        return outStream.toByteArray();
    }

    public static void getWord(String path, Map<String, Object> params, String targetFile) throws Exception {
        File file = new File(path);
        InputStream is = new FileInputStream(file);

        CcbckjXWPFDocument doc = new CcbckjXWPFDocument(is);

        replaceInTable(doc, params);

        FileOutputStream fileOutputStream = new FileOutputStream(targetFile);

        doc.write(fileOutputStream);

        fileOutputStream.close();
        is.close();

    }

    private static Matcher matcher(String str) {
        Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher = pattern.matcher(str);
        return matcher;
    }

    private static void replaceInTable(CcbckjXWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph> paras;
        while (iterator.hasNext()) {
            table = iterator.next();
            if (table.getRows().size() > 1) {
                // 判断表格是需要替换还是需要插入,判断逻辑有$为替换,表格无$为插入
                if (matcher(table.getText()).find()) {
                    rows = table.getRows();
                    for (XWPFTableRow row : rows) {
                        cells = row.getTableCells();
                        for (XWPFTableCell cell : cells) {
                            paras = cell.getParagraphs();
                            for (XWPFParagraph para : paras) {
                                replaceInParams(para, params, doc);
                            }
                        }
                    }
                }
            }
        }
    }

    private static void replaceInParams(XWPFParagraph para, Map<String, Object> params, CcbckjXWPFDocument doc) {
        List<XWPFRun> runs;
        if (matcher(para.getParagraphText()).find()) {
            runs = para.getRuns();
            int start = -1;
            int end = -1;
            String str = "";
            for (int i = 0; i < runs.size(); i++) {
                XWPFRun run = runs.get(i);
                String runText = run.toString();
                if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start != -1)) {
                    str += runText;
                }
                if ('}' == runText.charAt(runText.length() - 1)) {
                    if (start != -1) {
                        end = i;
                        break;
                    }
                }
            }

            for (int i = start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
            }

            for (Map.Entry<String, Object> entry : params.entrySet()) {
                String key = entry.getKey();
                if (str.indexOf(key) != -1) {
                    Object value = entry.getValue();
                    if (value instanceof String) {
                        str = str.replace(key, value.toString());
                        para.createRun().setText(str, 0);
                        break;
                    } else if (value instanceof Map) {
                        str = str.replace(key, "");
                        Map pic = (Map) value;
                        int width = Integer.parseInt(pic.get("width").toString());
                        int height = Integer.parseInt(pic.get("height").toString());
                        int picType = getPictureType(pic.get("type").toString());
                        byte[] byteArray = (byte[]) pic.get("content");
                        ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
                        try {
                            // int ind = doc.addPicture(byteInputStream,picType);
                            // doc.createPicture(ind, width , height,para);
                            doc.addPictureData(byteInputStream, picType);
                            doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
                            para.createRun().setText(str, 0);
                            break;
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            }
        }
    }

    private static int getPictureType(String picType) {
        int res = CcbckjXWPFDocument.PICTURE_TYPE_PICT;
        if (picType != null) {
            if (picType.equalsIgnoreCase("png")) {
                res = CcbckjXWPFDocument.PICTURE_TYPE_PNG;
            } else if (picType.equalsIgnoreCase("dib")) {
                res = CcbckjXWPFDocument.PICTURE_TYPE_DIB;
            } else if (picType.equalsIgnoreCase("emf")) {
                res = CcbckjXWPFDocument.PICTURE_TYPE_EMF;
            } else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
                res = CcbckjXWPFDocument.PICTURE_TYPE_JPEG;
            } else if (picType.equalsIgnoreCase("wmf")) {
                res = CcbckjXWPFDocument.PICTURE_TYPE_WMF;
            }
        }
        return res;
    }

    public static byte[] imageFileToByteArray(InputStream in) {
        byte[] byteArray = null;
        try {
            int total = in.available();
            byteArray = new byte[total];
            in.read(byteArray);
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                in.close();
            } catch (Exception e2) {
                e2.getStackTrace();
            }
        }
        return byteArray;
    }
}


class CcbckjXWPFDocument extends XWPFDocument {

    public CcbckjXWPFDocument(InputStream in) throws IOException {
        super(in);
    }
    public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {
        final int EMU = 9525;
        width *= EMU;
        height *= EMU;
        String blipId = getAllPictures().get(id).getPackageRelationship().getId();
        CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
        String picXml = ""
                +"<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
                +"   <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                +"      <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
                +"         <pic:nvPicPr>" + "            <pic:cNvPr id=\""
                + id
                +"\" name=\"Generated\"/>"
                +"            <pic:cNvPicPr/>"
                +"         </pic:nvPicPr>"
                +"         <pic:blipFill>"
                +"            <a:blip r:embed=\""
                + blipId
                +"\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
                +"            <a:stretch>"
                +"               <a:fillRect/>"
                +"            </a:stretch>"
                +"         </pic:blipFill>"
                +"         <pic:spPr>"
                +"            <a:xfrm>"
                +"               <a:off x=\"0\" y=\"0\"/>"
                +"               <a:ext cx=\""
                + width
                +"\" cy=\""
                + height
                +"\"/>"
                +"            </a:xfrm>"
                +"            <a:prstGeom prst=\"rect\">"
                +"               <a:avLst/>"
                +"            </a:prstGeom>"
                +"         </pic:spPr>"
                +"      </pic:pic>"
                +"   </a:graphicData>" + "</a:graphic>";

        inline.addNewGraphic().addNewGraphicData();
        XmlToken xmlToken = null;
        try{
            xmlToken = XmlToken.Factory.parse(picXml);
        }catch(XmlException xe) {
            xe.printStackTrace();
        }
        inline.set(xmlToken);

        inline.setDistT(0);
        inline.setDistB(0);
        inline.setDistL(0);
        inline.setDistR(0);

        CTPositiveSize2D extent = inline.addNewExtent();
        extent.setCx(width);
        extent.setCy(height);

        CTNonVisualDrawingProps docPr = inline.addNewDocPr();
        docPr.setId(id);
        docPr.setName("图片"+ id);
        docPr.setDescr("测试");
    }

}
上一篇 下一篇

猜你喜欢

热点阅读