Java 替換word文檔文字,指定位置插入圖片,word插入圖片

來源:互聯網
上載者:User

Java 替換word文檔文字,指定位置插入圖片,word插入圖片

先說下 需要的依賴包

<dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-excelant</artifactId>            <version>3.12</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-scratchpad</artifactId>            <version>3.12</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml</artifactId>            <version>3.8</version>        </dependency>        <dependency>            <groupId>org.apache.poi</groupId>            <artifactId>poi-ooxml-schemas</artifactId>            <version>3.8</version>        </dependency><!-- 產生圖片-->  <dependency>        <groupId>org.jfree</groupId>        <artifactId>jfreechart</artifactId>        <version>1.0.19</version>    </dependency>    <dependency><!--支援插入圖片-->        <groupId>org.docx4j</groupId>        <artifactId>docx4j</artifactId>        <version>3.3.1</version>    </dependency>

 

樣本,

 

 如,需要替換的字串地方“$1”為“1231”,在指定位置插入書籤,並命名“test”    ,插入的圖片如下

 

本人也沒太過多去研究,親測通過有效,在這分享下

1.demo

import java.awt.Font;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.math.BigInteger;import java.text.DecimalFormat;import java.text.NumberFormat;import java.util.Iterator;import java.util.List;import java.util.Map;import java.util.Set;import org.apache.poi.POIXMLDocument;import org.apache.poi.openxml4j.opc.OPCPackage;import org.apache.poi.util.IOUtils;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.apache.poi.xwpf.usermodel.XWPFParagraph;import org.apache.poi.xwpf.usermodel.XWPFRun;import org.docx4j.TraversalUtil;import org.docx4j.dml.wordprocessingDrawing.Inline;import org.docx4j.finders.RangeFinder;import org.docx4j.openpackaging.packages.WordprocessingMLPackage;import org.docx4j.openpackaging.parts.WordprocessingML.BinaryPartAbstractImage;import org.docx4j.openpackaging.parts.WordprocessingML.MainDocumentPart;import org.docx4j.wml.Body;import org.docx4j.wml.BooleanDefaultTrue;import org.docx4j.wml.CTBookmark;import org.docx4j.wml.Color;import org.docx4j.wml.Document;import org.docx4j.wml.Drawing;import org.docx4j.wml.HpsMeasure;import org.docx4j.wml.ObjectFactory;import org.docx4j.wml.P;import org.docx4j.wml.R;import org.docx4j.wml.RPr;import org.jfree.chart.ChartFactory;import org.jfree.chart.ChartUtilities;import org.jfree.chart.JFreeChart;import org.jfree.chart.labels.StandardPieSectionLabelGenerator;import org.jfree.chart.plot.PiePlot;import org.jfree.chart.title.TextTitle;import org.jfree.data.general.DefaultPieDataset;import com.aisino.qysds.common.constant.ERRORConstants;import com.aisino.qysds.common.exception.SysException;import com.aisino.qysds.service.IExportBgService;import com.google.common.collect.Maps;public class ExportBgServiceImpl {public static void main(String[] args) throws Exception {        Map<String, String> map = Maps.newHashMap();        map.put("$1", "1231");        XWPFDocument document = new XWPFDocument(POIXMLDocument.openPackage("D:\\tp\\test.docx"));        Iterator<XWPFParagraph> itPara = document.getParagraphsIterator();        while (itPara.hasNext()) {            XWPFParagraph paragraph = (XWPFParagraph) itPara.next();            List<XWPFRun> runs = paragraph.getRuns();            for (int i = 0; i < runs.size(); i++) {                String oneparaString = runs.get(i).getText(runs.get(i).getTextPosition());                for (Map.Entry<String, String> entry : map.entrySet()) {                    if (oneparaString.equals(entry.getKey())) {                        oneparaString = oneparaString.replace(entry.getKey(), entry.getValue());                    }                }                runs.get(i).setText(oneparaString, 0);            }        }        FileOutputStream outStream = null;        outStream = new FileOutputStream("D:\\tp\\test1.docx");        document.write(outStream);        outStream.close();//-----------------------------------這塊為產生圖片 和 插入圖片        DefaultPieDataset dataset = new DefaultPieDataset();        dataset.setValue("修改類", 1);        dataset.setValue("提示類", 1);        dataset.setValue("校正不通過", 3);        dataset.setValue("正常類", 3);        JFreeChart chart = ChartFactory.createPieChart3D(null, dataset, true, false, false);        chart.getLegend().setItemFont(new Font("黑體", Font.BOLD, 15)); // 設定圖例類別字型        // TextTitle title = new TextTitle(titleString);        // title.setFont(new Font("黑體", Font.ITALIC, 20));//設定標題字型        // chart.setTitle(title);        PiePlot piePlot = (PiePlot) chart.getPlot();        DecimalFormat df = new DecimalFormat("0.00%");        NumberFormat nf = NumberFormat.getInstance();        StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator("{0} {2}", nf, df);// 獲得StandardPieSectionLabelGenerator對象,產生的格式,        // {0}表示section名,{1}表示section的值,{2}表示百分比。可以自訂        piePlot.setLabelGenerator(generator);// 設定百分比        piePlot.setLabelFont(new Font("黑體", Font.ITALIC, 15));// 設定餅圖中類別字型        piePlot.setNoDataMessage("此時並沒有任何資料可用");        piePlot.setCircular(false);        piePlot.setLabelGap(0.02D);        piePlot.setIgnoreNullValues(true);// 設定不顯示空位        piePlot.setIgnoreZeroValues(true);// 設定不顯示負值或零值        String fName = "pie.png";        File file = new File("D:\\tp", fName);        if (file.exists()) {            file.delete();        }        try {            ChartUtilities.saveChartAsPNG(file, chart, 800, 500);            File file2 = new File("D:\\tp\\test1.docx");            WordprocessingMLPackage wPackage = WordprocessingMLPackage.load(new FileInputStream(file2));            MainDocumentPart mainDocumentPart = wPackage.getMainDocumentPart();            Document wmlDoc = (Document) mainDocumentPart.getJaxbElement();            Body body = wmlDoc.getBody();            // 提取本文中所有段落            List<Object> paragraphs = body.getContent();            // 提取書籤並建立書籤的遊標            RangeFinder rt = new RangeFinder("CTBookmark", "CTMarkupRange");            new TraversalUtil(paragraphs, rt);            for (CTBookmark bm : rt.getStarts()) {                if (bm.getName().equals("test")) {//  這裡的test為  word文檔中預設的 書籤名                    InputStream inputStream = new FileInputStream(file);                    byte[] bytes = IOUtils.toByteArray(inputStream);                    BinaryPartAbstractImage imagePart = BinaryPartAbstractImage.createImagePart(wPackage, bytes);                    Inline inline = imagePart.createImageInline(null, null, 0, 1, false, 10000);//這裡的100000不是正常螢幕大小,用於設定插入圖片的大小                    P p = (P) (bm.getParent());                    ObjectFactory factory = new ObjectFactory();                    // R對象是匿名的複雜類型,然而我並不知道具體啥意思,估計這個要好好去看看ooxml才知道                    R run = factory.createR();                    // drawing理解為畫布?                    Drawing drawing = factory.createDrawing();                    drawing.getAnchorOrInline().add(inline);                    run.getContent().add(drawing);                    p.getContent().add(run);                }            }            wPackage.save(new FileOutputStream(new File("D:\\tp\\test1.docx")));        } catch (IOException e) {                    }    }}

 

最後如下:

 

很多地方還來不及去瞭解,粗糙了些

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.