将图片打印到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();
}
}
}
}
将图片打印到word中的更多相关文章
- 基于MVC框架Aspose.Words打印到Word中写法
控件bin文件下载地址:https://download.csdn.net/download/u012949335/10610726 //前端打印写法 @{ ViewBag.Title = " ...
- 在word中粘贴的图片为什么显示不完整
一.背景 整理系统测试说明文档,截得图片粘贴到word中显示不完整. 二.错误问题 问题:在word中粘贴的图片为什么显示不完整,如图所示: 三.分析问题: 原因是原来设置的行间距是固定值,图片也作一 ...
- 如何删除word中多余的空格和空行
去除word中多余的空格及空行 一.去掉表格和格式 为了版面的整齐,网页文档都是以表格的形式存在的,只是一般情况下表格的颜色被设为无色或表格宽度被设为0,所以我们在网页上看不到表格.另外,网 页文档中 ...
- [Word]中批量修改图片大小和缩放比例方法
最近小编遇到一个问题:需要将一篇厘米.打开.宏名起好了,单击"创建"进入.返回word,工具-宏-宏(或者直接按Alt+F8),再次进入宏的界面,选择刚才编辑好的宏,并单击&quo ...
- C# 利用占位符替换word中的字符串和添加图片
利用占位符替换word中的字符串和添加图片 ///<summary> /// 替换word模板文件内容,包括表格中内容 /// 调用如下:WordStr ...
- 从word中提取图片的三种方法
方法1:使用截图方法来提取并保存图片,如果你安装了QQ并且运行了的话,你可以使用Ctrl+Alt+A来截图,然后在QQ聊天框中按CTRL+V来保存图片,当然你可以在PS新建文档按CTRL+V来粘贴图片 ...
- 提取WORD中的所有InlineShape图片并保存成文件
InlineShape表示的类型其实不只是图片,还包括OLE, ACTIVE X等. 下面是MSDN中的定义:Represents an object in the text layer of a d ...
- js生成word中图片处理
首先功能是要求前台导出word,但是前后台是分离的,图片存在后台,所以就存在跨域问题. 导出文字都是没有问题的(jquery.wordexport.js),但是导出图片就存在问题了: 图片是以链接形式 ...
- 如何把word中的图片怎么导出来呢?
在办公使用word的过程中你可能经常会遇到这个问题:插入到word中的图片找不到导出来的方法,是不是很郁闷呢,别急,今天咱们研究一下把word中的图片导出来的方法(把"我的"变成你 ...
随机推荐
- celery kill task
from celery.task.control import revokerevoke(task_id, terminate=True) https://stackoverflow.com/ques ...
- 求求你们了,别再写满屏的 if/ else 了!
为什么我们写的代码都是 if-else? 程序员想必都经历过这样的场景:刚开始自己写的代码很简洁,逻辑清晰,函数精简,没有一个 if-else,可随着代码逻辑不断完善和业务的瞬息万变:比如需要对入参进 ...
- Python进阶(上下文管理器与with语句)
/*上下文管理器必须有__enter__和__exit__方法*/ class MyResource: def __enter__(self): print('链接资源') return self / ...
- 菜鸡的Java笔记 第二十一 final 关键字
使用final定义类,属性,方法 final在一些书中被称为终结器,意思是:利用final定义的类不能够有子类,利用final定义的方法不能够被覆写,利用final定义的变量就成 ...
- 第二次SQLServer试验解
1 --给BookInfo表的BookId建立主键约束,给BookInfo表的BookName建立非空约束 2 create table BookInfo( 3 BookId int primary ...
- 1、使用ValueOperations操作redis(String字符串)
文章来源:https://www.cnblogs.com/shiguotao-com/p/10559997.html 方法 c参数 s说明 void set(K key, V value); ke ...
- [省选联考 2021 A/B 卷] 卡牌游戏
垃圾福建垫底选手来看看这题. 大家怎么都写带 \(log\) 的. 我来说一个线性做法好了. 那么我们考虑枚举 \(k\) 作为翻转完的最小值. 那么构造出一个满足条件的操作,我们在 \(a_i\) ...
- LOJ #6207 - 米缇(杜教筛+拉格朗日插值)
LOJ 题面传送门 首先将 \(\sigma_k(ij)\) 展开: \[\sigma_k(ij)=\sum\limits_{x\mid i}\sum\limits_{y\mid j}[x\perp ...
- 如何根据fasta快速统计基因组大小及其各染色体长度?
基因组长度 利用seqkit统计长度 seqkit stat test.fa 结果如下: file format type num_seqs sum_len min_len avg_len max_l ...
- 【软连接已存在,如何覆盖】ln: failed to create symbolic link ‘file.txt’: File exists
ln -s 改成 ln -sf f在很多软件的参数中意味着force ln -sf /usr/bin/bazel-1.0.0 /usr/bin/bazel