1. 程式人生 > >將圖片列印到word中

將圖片列印到word中

1.生成模板檔案

工具類:

package com.sfec.snmgr.track.utils;

import com.alibam.core.wechat.util.QRCodeUtil;
import org.apache.poi.xwpf.model.XWPFHeaderFooterPolicy;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;

import java.awt.image.BufferedImage;
import java.io.*;
import java.math.BigInteger;
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;

public class WordExportUtils {

/**
* 替換段落裡面的變數
*
* @param doc 要替換的文件
* @param params 引數
*/
public void replaceInPara(XWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params);
}
}

/**
* 替換段落裡面的變數
*
* @param para 要替換的段落
* @param params 引數
*/
public void replaceInPara(XWPFParagraph para, Map<String, Object> params) {
List<XWPFRun> runs;
Matcher matcher;
if (this.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();
System.out.println("------>>>>>>>>>" + runText);
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;
}
}
}
System.out.println("start--->"+start);
System.out.println("end--->"+end);

System.out.println("str---->>>" + str);

for (int i = start; i <= end; i++) {
para.removeRun(i);
i--;
end--;
System.out.println("remove i="+i);
}

for (String key : params.keySet()) {
if (str.equals(key)) {
para.createRun().setText((String) params.get(key));
break;
}
}


}
}

/**
* 替換表格裡面的變數
*
* @param doc 要替換的文件
* @param params 引數
*/
public void replaceInTable(XWPFDocument 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();
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params);
}
}
}
}
}

/**
* 正則匹配字串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}

/**
* 關閉輸入流
*
* @param is
*/
public void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 關閉輸出流
*
* @param os
*/
public void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}


public void exportApplyForm(String code) throws Exception {

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

params.put("${name}", "1");
params.put("${sex}","1");
params.put("${political}", "1");
params.put("${place}", "1");
params.put("${classes}", "1");
params.put("${id}", "1");
params.put("${qq}", "1");
params.put("${tel}", "1");
params.put("${oldJob}", "1");
params.put("${swap}", "1");
params.put("${first}", "1");
params.put("${second}", "1");
params.put("${award}", "1");
params.put("${achievement}", "1");
params.put("${advice}", "1");
params.put("${attach}", "1");

XWPFDocument doc;
String fileNameInResource = "E:/poi/in.docx";
//InputStream is= new FileInputStream(fileNameInResource);

//doc = new XWPFDocument(is);

//replaceInPara(doc, params);
//替換表格裡面的變數
//replaceInTable(doc, params);

OutputStream os = new FileOutputStream(new File("E:/poi/poi.docx"));
String codeUrl = "http://pangtun.silver-fortune.com.cn/h5/track/" + code;
QRCodeUtil.encode(codeUrl, os);
//doc.write(os);

close(os);
//close(is);

os.flush();
os.close();
}

public static void main(String[] args) throws Exception {
/*try {
new WordExportUtils().exportApplyForm("9be4606d-cd6c-4a5d-8b7e-72fc17b152d8");
} catch (Exception e) {
e.printStackTrace();
}*/

//Blank Document
CustomXWPFDocument document= new CustomXWPFDocument();

//Write the Document in file system
OutputStream out = new FileOutputStream(new File("E:/poi/create_table2018.docx"));

//段落
XWPFParagraph firstParagraph = document.createParagraph();
XWPFRun run = firstParagraph.createRun();

run.setColor("696969");
run.setFontSize(16);

//設定段落背景顏色
CTShd cTShd = run.getCTR().addNewRPr().addNewShd();
cTShd.setVal(STShd.CLEAR);
cTShd.setFill("97FFFF");

 

//表格第一行
/*XWPFTableRow infoTableRowOne = infoTable.getRow(0);
infoTableRowOne.getCell(0).setText("職位");
infoTableRowOne.addNewTableCell().setText(": Java 開發工程師");

//表格第二行
XWPFTableRow infoTableRowTwo = infoTable.createRow();
infoTableRowTwo.getCell(0).setText("姓名");
infoTableRowTwo.getCell(1).setText(": seawater");

//表格第三行
XWPFTableRow infoTableRowThree = infoTable.createRow();
infoTableRowThree.getCell(0).setText("生日");
infoTableRowThree.getCell(1).setText(": xxx-xx-xx");

//表格第四行
XWPFTableRow infoTableRowFour = infoTable.createRow();
infoTableRowFour.getCell(0).setText("性別");
infoTableRowFour.getCell(1).setText(": 男");

//表格第五行
XWPFTableRow infoTableRowFive = infoTable.createRow();
infoTableRowFive.getCell(0).setText("現居地");
infoTableRowFive.getCell(1).setText(": xx");*/


//兩個表格之間加個換行
XWPFParagraph paragraph = document.createParagraph();
XWPFRun paragraphRun = paragraph.createRun();
paragraphRun.setText("\r");

 

//工作經歷表格
XWPFTable ComTable = document.createTable();


//列寬自動分割
CTTblWidth comTableWidth = ComTable.getCTTbl().addNewTblPr().addNewTblW();
comTableWidth.setType(STTblWidth.DXA);
comTableWidth.setW(BigInteger.valueOf(9072));
XWPFTableRow comTableRowOne = ComTable.getRow(0);
comTableRowOne.getCell(0).setText("${header1}");
comTableRowOne.addNewTableCell().setText("${header2}");
comTableRowOne.addNewTableCell().setText("${header3}");
comTableRowOne.addNewTableCell().setText("${header4}");
XWPFTableRow comTableRowTwo1 = ComTable.createRow();

// comTableRowTwo1.getCell(0).setText("");
// comTableRowTwo1.addNewTableCell().setText("");
// comTableRowTwo1.addNewTableCell().setText("");
// comTableRowTwo1.addNewTableCell().setText("");

/*//表格第一行
XWPFTableRow comTableRowOne = ComTable.getRow(0);
comTableRowOne.getCell(0).setText("開始時間");
comTableRowOne.addNewTableCell().setText("結束時間");
comTableRowOne.addNewTableCell().setText("公司名稱");
comTableRowOne.addNewTableCell().setText("title");

//表格第二行
XWPFTableRow comTableRowTwo = ComTable.createRow();
comTableRowTwo.getCell(0).setText("2016-09-06");
comTableRowTwo.getCell(1).setText("至今");
comTableRowTwo.getCell(2).setText("seawater");
comTableRowTwo.getCell(3).setText("Java開發工程師");

//表格第三行
XWPFTableRow comTableRowThree = ComTable.createRow();
comTableRowThree.getCell(0).setText("2016-09-06");
comTableRowThree.getCell(1).setText("至今");
comTableRowThree.getCell(2).setText("seawater");
comTableRowThree.getCell(3).setText("Java開發工程師");*/
int count = 3;
for (int i = 4; i < 1500;i++) {
XWPFTableRow comTableRowTwo = ComTable.createRow();
if (i % 2 == 0) {
for (int j = 0; j < 4; j++) {

count++;
comTableRowTwo.getCell(j).setText("${header" + (count + 1) + "}");

}

}
/*count = i / 2;
if (i % 2 == 1) {
*//*comTableRowTwo.getCell(0).setText("${sn" + count +"}");
comTableRowTwo.getCell(1).setText("${sn" + count +"}");
comTableRowTwo.getCell(2).setText("${sn" + count +"}");
comTableRowTwo.getCell(3).setText("${sn" + count +"}");*//*
} else {

comTableRowTwo.getCell(0).setText("${header" + count +"}");
comTableRowTwo.getCell(1).setText("${header" + count++ +"}");
comTableRowTwo.getCell(2).setText("${header" + count +"}");
comTableRowTwo.getCell(3).setText("${header" + count++ +"}");
}*/
}


CTSectPr sectPr = document.getDocument().getBody().addNewSectPr();
XWPFHeaderFooterPolicy policy = new XWPFHeaderFooterPolicy(document, sectPr);

//新增頁首
CTP ctpHeader = CTP.Factory.newInstance();
CTR ctrHeader = ctpHeader.addNewR();
CTText ctHeader = ctrHeader.addNewT();
String headerText = "";
ctHeader.setStringValue(headerText);
XWPFParagraph headerParagraph = new XWPFParagraph(ctpHeader, document);
//設定為右對齊
headerParagraph.setAlignment(ParagraphAlignment.RIGHT);
XWPFParagraph[] parsHeader = new XWPFParagraph[1];
parsHeader[0] = headerParagraph;
policy.createHeader(XWPFHeaderFooterPolicy.DEFAULT, parsHeader);


//新增頁尾
CTP ctpFooter = CTP.Factory.newInstance();
CTR ctrFooter = ctpFooter.addNewR();
CTText ctFooter = ctrFooter.addNewT();
String footerText = "";
ctFooter.setStringValue(footerText);
XWPFParagraph footerParagraph = new XWPFParagraph(ctpFooter, document);
headerParagraph.setAlignment(ParagraphAlignment.CENTER);
XWPFParagraph[] parsFooter = new XWPFParagraph[1];
parsFooter[0] = footerParagraph;
policy.createFooter(XWPFHeaderFooterPolicy.DEFAULT, parsFooter);

String content = "http://pangtun.silver-fortune.com.cn/h5/track/";
BufferedImage image = QRCodeUtil.createImage(content, null, false);

document.createParagraph();
document.write(out);
out.close();
System.out.println("create_table document written success.");
}

}
執行main方法
3.根據模板檔案生成word。
public void exportWord() {
//List<SN> snList = (List<SN>) snRepository.findAll();

Map<String, Object> params = new LinkedHashMap<String, Object>();
int count = 1;
try {
long num = 1;
for (int i=1;i<=1000;i++) {
/*params.put("${sn" + count + "}", sn.getId());
params.put("${img" + count + "}", "E:/test/img/" + sn.getId() + ".png");*/
Map<String,Object> header = new HashMap<String, Object>();
header.put("width", 140);
header.put("height", 140);
header.put("type", "png");
//System.out.println(sn.getId());
//long numTemp = num + sn.getId();
String imgPath = "D:/Pic/picture/" + num + ".png";
header.put("content", WordUtil.inputStream2ByteArray(new FileInputStream(imgPath), true));
params.put("${header" + count + "}",header);

/*Map<String,Object> header1 = new HashMap<String, Object>();
header1.put("width", 140);
header1.put("height", 140);
header1.put("type", "png");
header1.put("sn", sn.getId().toString());
String imgPath1 = "E:/test/img/" + sn.getId() + ".png";
header1.put("content", sn.getId().toString());
params.put("${sn" + count + "}", header1);*/
count++;
num++;
}



} catch (Exception e) {
e.printStackTrace();
}


String path="E:/poi/create_table2018.docx"; //模板檔案位置
List<String[]> testList = new ArrayList<String[]>();
testList.add(new String[]{"1","1AA","1BB","1CC"});
testList.add(new String[]{"2","2AA","2BB","2CC"});
testList.add(new String[]{"3","3AA","3BB","3CC"});
testList.add(new String[]{"4","4AA","4BB","4CC"});
try {
String fileName = new String("E:/poi/測試文件.docx".getBytes("UTF-8"), "iso-8859-1"); //生成word檔案的檔名
new WordUtil().getWord(path, params, testList, fileName);
} catch (Exception e) {
e.printStackTrace();
}
}

4.更新表格中的資料
public void updateSn() throws  Exception {
String path = "E:/poi/imgWord.docx";
File file = new File(path);
InputStream is = new FileInputStream(file);
CustomXWPFDocument doc = new CustomXWPFDocument(is);
//基本資訊表格
List<XWPFTable> infoTables = doc.getTables();
System.out.println(infoTables.size()+"================");
XWPFTable table = infoTables.get(0);
//去表格邊框
//infoTable.getCTTbl().getTblPr().unsetTblBorders();
// List<SN> snList = (List<SN>) snRepository.findAll();

int count = 0;
int num=1;
for (int i = 1; i <1000; i=i+2) {
for (int j = 0; j < 4; j++) {
table.getRow(i).getCell(j).setText(num+"");
num++;
}

}

OutputStream os = new FileOutputStream("E:/poi/imgWord-ok2018.doc");
doc.write(os);
//this.replaceInPara(doc, params); //替換文本里面的變數
//this.replaceInTable(doc, params, tableList); //替換表格裡面的變數


}










附錄:
生成二維碼工具類
QRCodeUtil 
package com.sfec.snmgr.track.utils;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Hashtable;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.sfec.snmgr.track.vo.QRCodeParams;


public class QRCodeUtil {
private static int width = 120; //二維碼寬度
private static int height = 120; //二維碼高度
private static int onColor = 0xFF000000; //前景色
private static int offColor = 0xFFFFFFFF; //背景色
private static int margin = 1; //白邊大小,取值範圍0~4
private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L; //二維碼容錯率

/**
* 生成二維碼
* @param params
* QRCodeParams屬性:txt、fileName、filePath不得為空;
*/
public static void generateQRImage(QRCodeParams params)throws Exception{
if(params == null
|| params.getFileName() == null
|| params.getFilePath() == null
|| params.getTxt() == null){

throw new Exception("引數錯誤");
}
try{
initData(params);

String imgPath = params.getFilePath();
String imgName = params.getFileName();
String txt = params.getTxt();

if(params.getLogoPath() != null && !"".equals(params.getLogoPath().trim())){
generateQRImage(txt, params.getLogoPath(), imgPath, imgName, params.getSuffixName());
}else{
generateQRImage(txt, imgPath, imgName, params.getSuffixName());
}
}catch(Exception e){
e.printStackTrace();
}

}

/**
* 生成二維碼
* @param txt //二維碼內容
* @param imgPath //二維碼儲存物理路徑
* @param imgName //二維碼檔名稱
* @param suffix //圖片字尾名
*/
public static void generateQRImage(String txt, String imgPath, String imgName, String suffix){

File filePath = new File(imgPath);
if(!filePath.exists()){
filePath.mkdirs();
}

File imageFile = new File(imgPath,imgName);
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
// 指定糾錯等級
hints.put(EncodeHintType.ERROR_CORRECTION, level);
// 指定編碼格式
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, margin); //設定白邊
try {
MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
BitMatrix bitMatrix = new MultiFormatWriter().encode(txt,BarcodeFormat.QR_CODE, width, height, hints);
// bitMatrix = deleteWhite(bitMatrix);
MatrixToImageWriter.writeToPath(bitMatrix, suffix, imageFile.toPath(), config);
} catch (Exception e) {
e.printStackTrace();
}
}

/**
* 生成帶logo的二維碼圖片
* @param txt //二維碼內容
* @param logoPath //logo絕對物理路徑
* @param imgPath //二維碼儲存絕對物理路徑
* @param imgName //二維碼檔名稱
* @param suffix //圖片字尾名
* @throws Exception
*/
public static void generateQRImage(String txt, String logoPath, String imgPath, String imgName, String suffix) throws Exception{

File filePath = new File(imgPath);
if(!filePath.exists()){
filePath.mkdirs();
}

if(imgPath.endsWith("/")){
imgPath += imgName;
}else{
imgPath += "/"+imgName;
}

Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, level);
hints.put(EncodeHintType.MARGIN, margin); //設定白邊
BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);
File qrcodeFile = new File(imgPath);
writeToFile(bitMatrix, suffix, qrcodeFile, logoPath);
}

/**
*
* @param matrix 二維碼矩陣相關
* @param format 二維碼圖片格式
* @param file 二維碼圖片檔案
* @param logoPath logo路徑
* @throws IOException
*/
public static void writeToFile(BitMatrix matrix,String format,File file,String logoPath) throws IOException {
BufferedImage image = toBufferedImage(matrix);
Graphics2D gs = image.createGraphics();

int ratioWidth = image.getWidth()*2/10;
int ratioHeight = image.getHeight()*2/10;
//載入logo
Image img = ImageIO.read(new File(logoPath));
int logoWidth = img.getWidth(null)>ratioWidth?ratioWidth:img.getWidth(null);
int logoHeight = img.getHeight(null)>ratioHeight?ratioHeight:img.getHeight(null);

int x = (image.getWidth() - logoWidth) / 2;
int y = (image.getHeight() - logoHeight) / 2;

gs.drawImage(img, x, y, logoWidth, logoHeight, null);
gs.setColor(Color.black);
gs.setBackground(Color.WHITE);
gs.dispose();
img.flush();
if(!ImageIO.write(image, format, file)){
throw new IOException("Could not write an image of format " + format + " to " + file);
}
}

public static BufferedImage toBufferedImage(BitMatrix matrix){
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);

for(int x=0;x<width;x++){
for(int y=0;y<height;y++){
image.setRGB(x, y, matrix.get(x, y) ? onColor : offColor);
}
}
return image;
}

public static BitMatrix deleteWhite(BitMatrix matrix){
int[] rec = matrix.getEnclosingRectangle();
int resWidth = rec[2] + 1;
int resHeight = rec[3] + 1;

BitMatrix resMatrix = new BitMatrix(resWidth, resHeight);
resMatrix.clear();
for (int i = 0; i < resWidth; i++) {
for (int j = 0; j < resHeight; j++) {
if (matrix.get(i + rec[0], j + rec[1]))
resMatrix.set(i, j);
}
}
return resMatrix;
}

private static void initData(QRCodeParams params){
if(params.getWidth() != null){
width = params.getWidth();
}
if(params.getHeight() != null){
height = params.getHeight();
}
if(params.getOnColor() != null){
onColor = params.getOnColor();
}
if(params.getOffColor() != null){
offColor = params.getOffColor();
}
if(params.getLevel() != null){
level = params.getLevel();
}

}

public static BufferedImage getBufferImage(String txt, String logoPath) throws Exception{
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
hints.put(EncodeHintType.ERROR_CORRECTION, level);
hints.put(EncodeHintType.MARGIN, margin); //設定白邊
BitMatrix bitMatrix = new MultiFormatWriter().encode(txt, BarcodeFormat.QR_CODE, width, height, hints);
BufferedImage image = toBufferedImage(bitMatrix);
Graphics2D gs = image.createGraphics();

int ratioWidth = image.getWidth()*2/10;
int ratioHeight = image.getHeight()*2/10;
//載入logo
Image img = ImageIO.read(new File(logoPath));
int logoWidth = img.getWidth(null)>ratioWidth?ratioWidth:img.getWidth(null);
int logoHeight = img.getHeight(null)>ratioHeight?ratioHeight:img.getHeight(null);

int x = (image.getWidth() - logoWidth) / 2;
int y = (image.getHeight() - logoHeight) / 2;

gs.drawImage(img, x, y, logoWidth, logoHeight, null);
gs.setColor(Color.black);
gs.setBackground(Color.WHITE);
gs.dispose();
return image;
}

}



package com.sfec.snmgr.track.utils;

import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
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.IOException;
import java.io.InputStream;


public class CustomXWPFDocument extends XWPFDocument {

public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}

public CustomXWPFDocument() {
super();
}

public CustomXWPFDocument(OPCPackage pkg) throws IOException {
super(pkg);
}

/**
* @param id
* @param width 寬
* @param height 高
* @param paragraph 段落
*/
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("測試");
}
}





package com.sfec.snmgr.track.utils;

import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;


public class WordUtil {

/**
* 根據模板生成word
* @param path 模板的路徑
* @param params 需要替換的引數
* @param tableList 需要插入的引數
* @param fileName 生成word檔案的檔名
*/
public void getWord(String path, Map<String, Object> params, List<String[]> tableList, String fileName) throws Exception {
File file = new File(path);
InputStream is = new FileInputStream(file);
CustomXWPFDocument doc = new CustomXWPFDocument(is);
//基本資訊表格
XWPFTable infoTable = doc.createTable();
//去表格邊框
infoTable.getCTTbl().getTblPr().unsetTblBorders();

//this.replaceInPara(doc, params); //替換文本里面的變數
this.replaceInTable(doc, params, tableList); //替換表格裡面的變數
OutputStream os = new FileOutputStream("E:/poi/imgWord.docx");
doc.write(os);
this.close(os);
this.close(is);

}

/**
* 替換段落裡面的變數
* @param doc 要替換的文件
* @param params 引數
*/
private void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params, doc);
}
}

/**
* 替換段落裡面的變數
*
* @param para 要替換的段落
* @param params 引數
*/
private void replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc) {
List<XWPFRun> runs;
Matcher matcher;
if (this.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();
}
}
}
}
}
}


/**
* 為表格插入資料,行數不夠新增新行
*
* @param table 需要插入資料的表格
* @param tableList 插入資料集合
*/
private static void insertTable(XWPFTable table, List<String[]> tableList) {
//建立行,根據需要插入的資料新增新行,不處理表頭
for (int i = 0; i < tableList.size(); i++) {
XWPFTableRow row = table.createRow();
}
//遍歷表格插入資料
List<XWPFTableRow> rows = table.getRows();
int length = table.getRows().size();
for (int i = 1; i < length - 1; i++) {
XWPFTableRow newRow = table.getRow(i);
List<XWPFTableCell> cells = newRow.getTableCells();
for (int j = 0; j < cells.size() - 1; j++) {
XWPFTableCell cell = cells.get(j);
//String s = tableList.get(i - 1)[j];
cell.setText("");
}
}
}

/**
* 替換表格裡面的變數
* @param doc 要替換的文件
* @param params 引數
*/
private void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params, List<String[]> tableList) {
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 (this.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) {
this.replaceInPara(para, params, doc);
}
}
}
} else {
insertTable(table, tableList); //插入資料
}
}
}
}


/**
* 正則匹配字串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}


/**
* 根據圖片型別,取得對應的圖片型別程式碼
*
* @param picType
* @return int
*/
private static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
}

/**
* 將輸入流中的資料寫入位元組陣列
*
* @param in
* @return
*/
public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
byte[] byteArray = null;
try {
int total = in.available();
byteArray = new byte[total];
in.read(byteArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isClose) {
try {
in.close();
} catch (Exception e2) {
e2.getStackTrace();
}
}
}
return byteArray;
}


/**
* 關閉輸入流
*
* @param is
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}

/**
* 關閉輸出流
*
* @param os
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}