Java replaces the word document text, inserts an image at a specified position, and inserts an image at a word.

Source: Internet
Author: User

Java replaces the word document text, inserts an image at a specified position, and inserts an image at a word.

First, describe the dependent package.

<Dependency> <groupId> org. apache. poi </groupId> <artifactId> poi-excelant </artifactId> <version> 3.12 </version> </dependency> <groupId> org. apache. poi </groupId> <artifactId> poi-scratchpad </artifactId> <version> 3.12 </version> </dependency> <groupId> org. apache. poi </groupId> <artifactId> poi-ooxml </artifactId> <version> 3.8 </version> </dependency> <groupId> org. apache. p Oi </groupId> <artifactId> poi-ooxml-schemas </artifactId> <version> 3.8 </version> </dependency> <! -- Generate an image --> <dependency> <groupId> org. jfree </groupId> <artifactId> jfreechart </artifactId> <version> 1.0.19 </version> </dependency> <! -- Images can be inserted --> <groupId> org.docx 4j </groupId> <artifactId> docx4j </artifactId> <version> 3.3.1 </version> </dependency>

 

Example,

 

For example, if "$1" is "1231" in the string to be replaced, insert a bookmark at the specified position and name it "test". The inserted image is as follows:

 

I am not doing too much research. It is valid for my tests.

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. openx Ml4j. 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.docx 4j. traversalUtil; import org.docx 4j. dml. wordprocessingDrawing. inline; import org.docx 4j. finders. rangeFinder; import org.docx 4j. openpackaging. packages. wordprocessingMLPackage; import org. do Cx4j. openpackaging. parts. wordprocessingML. binaryPartAbstractImage; import org.docx 4j. openpackaging. parts. wordprocessingML. mainDocumentPart; import org.docx 4j. wml. body; import org.docx 4j. wml. booleanDefaultTrue; import org.docx 4j. wml. CTBookmark; import org.docx 4j. wml. color; import org.docx 4j. wml. document; import org.docx 4j. wml. drawing; import org.docx 4j. wml. hpsMeasure; import org.docx 4j. wml. objectFactory; imp Ort org.docx 4j. wml. p; import org.docx 4j. wml. r; import org.docx 4j. 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. cons Tant. 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 \ te St.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. equal S (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 = new DefaultPieDataset (); dataset. setValue (" Modify class ", 1); dataset. setValue ("prompt class", 1); dataset. setValue ("Verification Failed", 3); dataset. setValue ("normal class", 3); JFreeChart chart = ChartFactory. createPieChart3D (null, dataset, true, false, false); chart. getLegend (). setItemFont (new Font ("", Font. BOLD, 15); // set the font of the legend category // TextTitle title = new TextTitle (titleString); // title. setFont (new Font ("", Font. ITALIC, 20); // set the title Font // chart. setTitle (title); PiePlot pie Plot = (PiePlot) chart. getPlot (); DecimalFormat df = new DecimalFormat ("0.00%"); NumberFormat nf = NumberFormat. getInstance (); StandardPieSectionLabelGenerator generator = new StandardPieSectionLabelGenerator ("{0} {2}", nf, df); // obtain the StandardPieSectionLabelGenerator object and the generated format, // {0} indicates the section name, {1} indicates the section value, and {2} indicates the percentage. You can customize piePlot. setLabelGenerator (generator); // sets the percentage of piePlot. setLabelFont (new Font ("", Font. ITALIC, 15); // set the category font piePlot in the pie chart. setNoDataMessage ("no data is available now"); piePlot. setCircular (false); piePlot. setLabelGap (0.02D); piePlot. setIgnoreNullValues (true); // you can specify true to indicate that no piePlot is displayed. setIgnoreZeroValues (true); // set String fName = "pie.png"; File file = new File ("D: \ tp", fName ); if (file. exists () {file. d Elete ();} 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 Body = wmlDoc. getBody (); // extract the List of all paragraphs in the body <Object> par Agraphs = body. getContent (); // The cursor RangeFinder rt = new RangeFinder ("CTBookmark", "CTMarkupRange"); new TraversalUtil (paragraphs, rt ); for (CTBookmark bm: rt. getStarts () {if (bm. getName (). equals ("test") {// here, test is the default bookmarks in the Word documents. Name: InputStream inputStream = new FileInputStream (file); byte [] bytes = IOUtils. toByteArray (inputStream); BinaryPartAbstractImage imagePart = BinaryPartAbstrac TImage. createImagePart (wPackage, bytes); Inline inline = imagePart. createImageInline (null, null, 0, 1, false, 10000); // 100000 is not the normal screen size, used to set the size of the inserted image P = (p) (bm. getParent (); ObjectFactory factory = new ObjectFactory (); // The R object is an anonymous complex type. However, I don't know what it means, it is estimated that this should take a good look at ooxml to know R run = factory. createR (); // is drawing understood as a canvas? 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 ){}}}

 

The final steps are as follows:

 

It's too late to get to know a lot of things.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.