doc与docx区别:97-2003的旧版本文件名后缀就是.doc
从2007版以后后缀名是.docx(由于版本问题我选则的是2003dox,poi对dox操操作有局限性,笔者在对doc图片替换没有找到相关资料,于是采用了Spire来替换图片)
POI中文API文档
poi+word模板生成word文档地址供参考
使用Spire.doc替换word中的文字内容
1、在pom.xml配置下载地址
com.e-iceblue
e-iceblue
http://repo.e-iceblue.com/nexus/content/groups/public/
2、引入doc 依赖SPIRE DOC 操作world
e-iceblue
spire.doc
2.2.0
二维码工具类
package com.ref.statis.util;
/**
* @author : LW
* @ClassName : BufferedImageLuminanceSource
* @remarks :二维码工具类
* @date : 2020-05-02 22:24
*/
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;
public class BufferedImageLuminanceSource extends LuminanceSource{
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left,
int top, int width, int height) {
super(width, height);
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException(
"Crop rectangle does not fit within image data.");
}
for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}
this.image = new BufferedImage(sourceWidth, sourceHeight,
BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException(
"Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
public boolean isCropSupported() {
return true;
}
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left,
this.top + top, width, height);
}
public boolean isRotateSupported() {
return true;
}
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0,
0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight,
sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top,
sourceWidth - (left + width), getHeight(), width);
}
}
生成二维码
package com.ref.statis.util;
/**
* @author : LW
* @ClassName : QRCodeUtil
* @remarks :二维码生成工具类
* @date : 2020-05-02 22:25
*/
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/*
*
* @Description: 生成二维码工具类
* @Author: LW
* @Param:
* @create: 2020/5/5 1:07
* @return:
*/
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "JPG";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath,
boolean needCompress) throws Exception {
@SuppressWarnings("rawtypes")
Hashtable<EncodeHintType, Comparable> hints = new Hashtable<EncodeHintType, Comparable>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content,
BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000
: 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 插入LOGO
*
* @param source
* 二维码图片
* @param imgPath
* LOGO图片地址
* @param needCompress
* 是否压缩
* @throws Exception
*/
private static void insertImage(BufferedImage source, String imgPath,
boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println(""+imgPath+" 该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height,
Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height,
BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存放目录
* @param needCompress
* 是否压缩LOGO
* @param imgName
* 二维码名称
* @throws Exception
*/
public static String encode(String content, String imgPath, String destPath,
boolean needCompress ,String imgName,String fileAddress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
String dirs=new SimpleDateFormat("yyyyMMdd").format(new Date()).toString()+"\\";
mkdirs(destPath,dirs);
// String file = new Random().nextInt(99999999)+".jpg";
String file =imgName+".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath+"\\"+dirs+file));
return fileAddress+dirs+file;
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* @param destPath 存放目录
*/
public static void mkdirs(String destPath, String dirs) {
File file =new File(destPath);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
File files =new File(destPath+"/"+dirs);
//当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!files.exists() && !files.isDirectory()) {
files.mkdirs();
}
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath ,String imgName,String fileAddress)
throws Exception {
QRCodeUtil.encode(content, imgPath, destPath, false,imgName,fileAddress);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static String encode(String content, String destPath,
boolean needCompress ,String imgName,String fileAddress) throws Exception {
return QRCodeUtil.encode(content, null, destPath, needCompress,imgName,fileAddress);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param destPath
* 存储地址
* @throws Exception
*/
public static void encode(String content, String destPath,String imgName,String fileAddress) throws Exception {
QRCodeUtil.encode(content, null, destPath, false,imgName,fileAddress);
}
/**
* 生成二维码(内嵌LOGO)
*
* @param content
* 内容
* @param imgPath
* LOGO地址
* @param output
* 输出流
* @param needCompress
* 是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath,
OutputStream output, boolean needCompress ) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath,
needCompress);
ImageIO.write(image, FORMAT_NAME, output);
}
/**
* 生成二维码
*
* @param content
* 内容
* @param output
* 输出流
* @throws Exception
*/
public static void encode(String content, OutputStream output)
throws Exception {
QRCodeUtil.encode(content, null, output, false);
}
/**
* 解析二维码
*
* @param file
* 二维码图片
* @return
* @throws Exception
*/
public static String decode(File file) throws Exception {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
return null;
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(
image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
return resultStr;
}
/**
* 解析二维码
*
* @param path
* 二维码图片地址
* @return
* @throws Exception
*/
public static String decode(String path) throws Exception {
return QRCodeUtil.decode(new File(path));
}
}
使用poi替换word模板、使用Spire来实现图片替换文字
package com.ref.statis.util;
import com.ref.statis.vo.ReferralUser;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;
import com.spire.doc.fields.DocPicture;
import com.spire.doc.fields.TextRange;
import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
/**
* @author : LW
* @ClassName : DocUtil world 2003
* @remarks :
* @date : 2020-05-03 22:03
*/
public class DocUtil {
public static String builderWorld () throws Exception{
//转诊单名称
String name ="小明明";
//转诊单信息实体
ReferralUser user = new ReferralUser();
//生成excle路径
String file ="E:\\HisWork\\His\\excleAndQRCode\\Excle\\";
//二维码跳转路径
String text = "https://gitee.com/about_a_wen/His";
//二维码生成路径
String fileAddress ="E:\\HisWork\\His\\excleAndQRCode\\QRCode\\";
//生成带LOGO的二维码
String img= QRCodeUtil.encode(text, "E:\\HisWork\\His\\excleAndQRCode\\QRCode\\default\\QrCodeImg.jpg", "E:\\HisWork\\His\\excleAndQRCode\\QRCode", true,name,fileAddress);
//小助手
user.setOperator("admin");
user.setReferralRemark("小助手转诊建议");
//转出信息
user.setReferralHospital("上海市东医院");
user.setReferraldepartmentName("小儿内科");
user.setReferraldoctor("宏利");
user.setAppointmentTime(CalendarDateUtil.bulidDate("2020-04-26 20:41:58"));
user.setChiefComplaint("这里是主诉");
user.setPhysicalExamination("这里是查体");
user.setProblemToBeSolved("这里是待解决问题");
//转入信息
user.setTransferHospital("上海新华医院");
user.setDepartmentName("小儿心内科");
user.setAttendingDoctor("力宏");
user.setOutpatientType("专家门诊");
user.setReferralTime(CalendarDateUtil.bulidDateApMp("2020-04-27 20:41:58"));
//患者信息
user.setSuffererName("刘佳");
user.setSuffererPhone("15645156541");
user.setSuffererAge("18");
user.setSuffererSex("女");
user.setSuffererHeight("156");
user.setSuffererWeight("55");
//二维码路径
user.setQRCodeImg(img);
Map map = new HashMap();
map.put("suffererName", user.getSuffererName());
map.put("suffererPhone", user.getSuffererPhone());
map.put("suffererAge", user.getSuffererAge());
map.put("suffererSex", user.getSuffererSex());
map.put("suffererHeight", user.getSuffererHeight());
map.put("suffererWeight", user.getSuffererWeight());
map.put("departmentName", user.getDepartmentName());
map.put("transferHospital",user.getTransferHospital());
map.put("attendingDoctor", user.getAttendingDoctor());
map.put("outpatientType", user.getOutpatientType());
map.put("referralTime", user.getReferralTime());
map.put("referralHospital",user.getReferralHospital());
map.put("referraldepartmentName", user.getReferraldepartmentName());
map.put("referraldoctor", user.getReferraldoctor());
map.put("appointmentTime",user.getAppointmentTime());
map.put("chiefComplaint",user.getChiefComplaint());
map.put("physicalExamination", user.getPhysicalExamination());
map.put("problemToBeSolved", user.getProblemToBeSolved());
map.put("operator", user.getOperator());
map.put("referralRemark",user.getReferralRemark());
map.put("time",new Date().toString());
map.put("QRCodeImg", user.getQRCodeImg());
map.put("reminderOne", user.getReminderOne());
map.put("reminderTow", user.getReminderTow());
map.put("reminderThree", user.getReminderThree());
map.put("reminderFour", user.getReminderFive());
map.put("reminderFive",user.getReminderFive());
map.put("reminderSix", user.getReminderSix());
//使用poi world 将数据替换
getBuild("static/doc/referralTemplate.doc", map, "E:\\HisWork\\His\\excleAndQRCode\\Doc\\"+name+".docx");
//使用spire doc 将二维码文字替换成二维码图片
return "";
}
/*
*
* @Description: 插入二维码 spire docx world
* @Author: LW
* @Param: []
* @create: 2020/5/5 0:31
* @return: java.lang.String
*/
public static String ReplaceTextWithImage(){
//加载示例文档
Document document = new Document();
document.loadFromFile("E:\\HisWork\\His\\excleAndQRCode\\Doc\\小明明.docx");
//查找文档中的字符串“成都冰蓝科技有限公司”
TextSelection[] selections = document.findAllString("绑定二维码", true, true);
//用图片替换文字
int index = 0;
TextRange range = null;
for (Object obj : selections) {
TextSelection textSelection = (TextSelection)obj;
DocPicture pic = new DocPicture(document);
pic.loadImage("E:\\HisWork\\His\\excleAndQRCode\\QRCode\\20200505\\小明明.jpg");
range = textSelection.getAsOneRange();
index = range.getOwnerParagraph().getChildObjects().indexOf(range);
range.getOwnerParagraph().getChildObjects().insert(index,pic);
range.getOwnerParagraph().getChildObjects().remove(range);
}
//保存文档
document.saveToFile("E:\\HisWork\\His\\excleAndQRCode\\Doc\\小明明.docx", FileFormat.Docx_2013);
return "";
}
public static void main (String[] args) throws Exception{
String doc= DocUtil.builderWorld();
DocUtil.ReplaceTextWithImage();
System.out.println(doc);
}
/*
*
* @Description: poi替换world中的${}
* @Author: LW
* @Param: [tmpFile, contentMap, exportFile]
* @create: 2020/5/4 10:58
* @return: void
*/
public static void getBuild (String tmpFile, Map<String, String> contentMap, String exportFile) {
InputStream inputStream = DocUtil.class.getClassLoader().getResourceAsStream(tmpFile);
// InputStream inputStream = Thread.currentThread().getContextClassLoader().getResourceAsStream(tmpFile);
HWPFDocument document = null;
try {
document = new HWPFDocument(inputStream);
} catch (IOException e) {
e.printStackTrace();
}
// 读取文本内容
Range bodyRange = document.getRange();
// 替换内容
for (Map.Entry<String, String> entry : contentMap.entrySet()) {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write(byteArrayOutputStream);
OutputStream outputStream = new FileOutputStream(exportFile);
outputStream.write(byteArrayOutputStream.toByteArray());
//关流
byteArrayOutputStream.close();
inputStream.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
实体
package com.ref.statis.vo;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
import lombok.Data;
import java.util.Date;
/**
* @author : LW
* @ClassName : ReferralUser
* @remarks :转诊单实体
* @date : 2020-05-03 00:28
*/
@ApiModel(value = "转诊单实体")
@Data
public class ReferralUser {
/*
*患者信息
*/
//患者姓名
private String suffererName;
//患者手机号码
private String suffererPhone;
//患者年龄(单位:岁) 转诊单上的年龄 在excel中判断是年还是月(根据升高体重)
private String suffererAge;
//患者性别
private String suffererSex;
//患者升高(单位:cm)
private String suffererHeight;
//患者体重(单位:kg)
private String suffererWeight;
/*
*转入信息
*/
//转入医院 如果数据库没有标名转入医院 则先用死的数据,在excle判断給值
private String transferHospital;
//转入科室
private String departmentName;
//转入医生 接诊医生
private String attendingDoctor;
//转入门诊类型
private String outpatientType;
//预约时间
@ApiModelProperty(value = "转诊时间")
private String referralTime;
/*
*转出信息
*/
//转出医院 这个可能需要更具申请医生编号查询医生所在医院(如果转诊实体没有)
private String referralHospital;
//转出科室(转出方科室数据库可能没有添加该字段 之前可能用的是预约转入科室)
private String referraldepartmentName;
//申请医生
private String referraldoctor;
//申请时间
@ApiModelProperty(value = "预约时间")
private String appointmentTime;
//主诉
private String chiefComplaint;
//查体
private String physicalExamination;
//待解决问题
private String problemToBeSolved;
/*
*联盟小助手
*/
//操作人(小助手审核后要将操作员改为联盟小助手的人)
@ApiModelProperty(value = "操作此条数据的人")
private String operator;
//建议(小助手审核通过后的建议)
private String referralRemark;
/*
*其他
*/
//二维码路径
private String QRCodeImg;
//温馨提示一
private String reminderOne = "1、转诊单一式两份,一份给挂号窗口,一份给科室护士台,请勿丢失;";
//温馨提示二
private String reminderTow = "2、根据当天就诊清空,医联体患者适当优先;";
//温馨提示三
private String reminderThree = "3、请核对转诊单信息,医保卡与转诊单不符合将不予挂号;";
//温馨提示四
private String reminderFour = "4、预约上午门诊请在就诊当天日10:00之前。在转诊挂号窗口进行现场挂号;";
//温馨提示五
private String reminderFive = "5、预约下午门诊庆祝就诊当日15:00之前,在转诊挂号窗口进行现场挂号;";
//温馨提示六
private String reminderSix = "6、就诊时,请携带身份证、医保卡、原医院病史、检验检查报告、放射影像胶片、病例报告等相关资料。";
}