public ResponseEntity exportWord(HttpServletRequest request, HttpServletResponse response) {
// 标题
String title = "封面标题";
try {
XWPFdocument document= new XWPFdocument();
//业务代码,主要是大纲集合
fafzbxCatalogList.forEach(item->{
//添加标题
XWPFParagraph titleParagraph = document.createParagraph();
// 获取新建文档样式
XWPFStyles docStyle = document.createStyles();
// 老外自定义了一个名字,中文版的最好还是按照word给的标题名来,否则级别上可能会乱
WordTools.addCustomHeadingStyle(document, item.getName(), item.getLevel());
// 关键行// 大纲
titleParagraph.setStyle(item.getName());
XWPFRun titleParagraphRun = titleParagraph.createRun();
titleParagraphRun.setText(item.getName());
titleParagraphRun.setColor("000000");
if("1".equals(item.getLevel().toString())){
titleParagraphRun.setFontSize(22);
}else if("2".equals(item.getLevel().toString()) || "3".equals(item.getLevel().toString())){
titleParagraphRun.setFontSize(16);
}else if("4".equals(item.getLevel().toString()) || "5".equals(item.getLevel().toString())){
titleParagraphRun.setFontSize(14);
}else {
titleParagraphRun.setFontSize(12);
}
//业务代码主要是内容
FafzbxChapters fafzbxChapters = fafzbxChaptersRepository.findByDeletedAndCatalogId("0",item.getId());
if(Objects.nonNull(fafzbxChapters)){
//段落
XWPFParagraph firstParagraph = document.createParagraph();
XWPFRun run = firstParagraph.createRun();
String content = fafzbxChapters.getFzbxContent();
run = img(content,run);
//
run.setColor("000000");
run.setFontSize(11);
}
});
//输出路径
String path = System.getProperty("user.dir");
String filePath = path + "/" + title + ".docx";
//document转字节数组
ByteArrayOutputStream out = new ByteArrayOutputStream();
document.write(out);
out.close();
document.close();
byte[] xwpfdocumentBytes = out.toByteArray();
WordTools.creatFile(filePath,xwpfdocumentBytes);
//目錄
WordTools.creat(filePath);
document doc = new document(filePath);
doc.updateFields();// 更新域
doc.save(filePath);
WordTools.coverFile(filePath,title);
byte[] bytes = WordTools.fileToBytes(filePath);
//删除文件 "\"
DelFile.deleteFile(filePath);
HttpHeaders headers = new HttpHeaders();
headers.add(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + fafzbxMain.getName() + ".docx" + ";filename*=utf-8''" + URLEncoder.encode(fafzbxMain.getName() + ".docx" , "UTF-8"));
return ResponseEntity
.ok()
.headers(headers)
.contentLength(bytes.length)
.contentType(MediaType.valueOf("multipart/form-data;charset=UTF-8"))
.body(new ByteArrayResource(bytes));
}catch (Exception e){
e.printStackTrace();
}
return null;
}
package cn.com.bmsmart.util;
import com.aspose.words.*;
import org.apache.poi.util.LocaleUtil;
import org.apache.poi.xwpf.usermodel.XWPFdocument;
import org.apache.poi.xwpf.usermodel.XWPFStyle;
import org.apache.poi.xwpf.usermodel.XWPFStyles;
import org.apache.xmlbeans.impl.xb.xmlschema.SpaceAttribute;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.*;
import java.io.*;
import java.math.BigInteger;
public class WordTools {
public static void addCustomHeadingStyle(XWPFdocument docxdocument, String strStyleId, int headingLevel) {
CTStyle ctStyle = CTStyle.Factory.newInstance();
ctStyle.setStyleId(strStyleId);
CTString styleName = CTString.Factory.newInstance();
styleName.setVal(strStyleId);
ctStyle.setName(styleName);
CTDecimalNumber indentNumber = CTDecimalNumber.Factory.newInstance();
indentNumber.setVal(BigInteger.valueOf(headingLevel));
// lower number > style is more prominent in the formats bar
ctStyle.setUiPriority(indentNumber);
CTonOff onoffnull = CTOnOff.Factory.newInstance();
ctStyle.setUnhideWhenUsed(onoffnull);
// style shows up in the formats bar
ctStyle.setQFormat(onoffnull);
// style defines a heading of the given level
CTPPr ppr = CTPPr.Factory.newInstance();
ppr.setOutlineLvl(indentNumber);
ctStyle.setPPr(ppr);
XWPFStyle style = new XWPFStyle(ctStyle);
// is a null op if already defined
XWPFStyles styles = docxdocument.createStyles();
style.setType(STStyleType.PARAGRAPH);
styles.addStyle(style);
}
public static byte[] fileToBytes(String filePath) {
byte[] buffer = null;
File file = new File(filePath);
FileInputStream fis = null;
ByteArrayOutputStream bos = null;
try {
fis = new FileInputStream(file);
bos = new ByteArrayOutputStream();
byte[] b = new byte[1024];
int n;
while ((n = fis.read(b)) != -1) {
bos.write(b, 0, n);
}
buffer = bos.toByteArray();
} catch (FileNotFoundException ex) {
ex.printStackTrace();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
if (null != bos) {
bos.close();
}
} catch (IOException ex) {
ex.printStackTrace();
} finally{
try {
if(null!=fis){
fis.close();
}
} catch (IOException ex) {
}
}
}
return buffer;
}
public static void creatFile(String filePath, byte[] xwpfdocumentBytes){
InputStream inputStream = new ByteArrayInputStream(xwpfdocumentBytes);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filePath);
byte[] b = new byte[1024];
while ((inputStream.read(b)) != -1) {
fos.write(b);// 写入数据
}
inputStream.close();
fos.close();// 保存数据
}catch (Exception e){
e.printStackTrace();
}finally {
if(fos!=null){
try{fos.close();fos=null;}catch(Exception e){e.printStackTrace();}
}
}
}
public static void addHeaderFooter(document doc){
}
public static void creat(String path){
try {
document doc = new document(path);
addHeaderFooter(doc);
documentBuilder builder =new documentBuilder(doc);
doc.getFirstSection().getBody().prependChild(new Paragraph(doc));
builder.moveTodocumentStart();
//设置目录的格式
//“目录”两个字居中显示、加粗、搜宋体
builder.getCurrentParagraph().getParagraphFormat().setAlignment(com.aspose.words.ParagraphAlignment.CENTER);
builder.setBold(true);
builder.getFont().setName("宋体");
builder.writeln("目录");
//清清除所有样式设置
builder.getParagraphFormat().clearFormatting();
//目录居左
builder.getParagraphFormat().setAlignment(ParagraphAlignment.LEFT);
//插入目录,这是固定的
builder.insertTableOfContents("\o "1-3" \h \z \u");
builder.insertBreak(BreakType.PAGE_BREAK);
doc.updateFields();// 更新域
doc.save(path);
}catch (Exception e) {
e.printStackTrace();
}
}
public static void coverFile(String path,String title){
try {
document doc = new document(path);
addHeaderFooter(doc);
documentBuilder builder =new documentBuilder(doc);
doc.getFirstSection().getBody().prependChild(new Paragraph(doc));
builder.moveTodocumentStart();
//设置目录的格式
//“目录”两个字居中显示、加粗、搜宋体
builder.getCurrentParagraph().getParagraphFormat().setAlignment(com.aspose.words.ParagraphAlignment.CENTER);
builder.setBold(true);
builder.getFont().setName("黑体");
builder.getFont().setSize(24);
//先空出三行
for(int i=0;i<5;i++){
builder.writeln("");
}
builder.writeln(title);
//空出十行
for(int i=0;i<8;i++){
builder.writeln("");
}
//清清除所有样式设置
builder.getParagraphFormat().clearFormatting();
doc.save(path);
}catch (Exception e) {
e.printStackTrace();
}
}
}
package cn.com.bmsmart.util;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;
public class Imagebase64Utils {
public static String bytesTobase64(byte[] bytes) {
return org.apache.commons.codec.binary.base64.encodebase64String(bytes);// 返回base64编码过的字节数组字符串
}
public static String imageTobase64(String path) throws IOException {// 将图片文件转化为字节数组字符串,并对其进行base64编码处理
byte[] data = null;
// 读取图片字节数组
InputStream in = null;
try {
in = new FileInputStream(path);
data = new byte[in.available()];
in.read(data);
} finally {
if (in != null) {
try {
in.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return org.apache.commons.codec.binary.base64.encodebase64String(data);// 返回base64编码过的字节数组字符串
}
public static boolean base64ToImageFile(String base64, String path) throws IOException {// 对字节数组字符串进行base64解码并生成图片
// 生成jpeg图片
try {
OutputStream out = new FileOutputStream(path);
return base64ToImageOutput(base64, out);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
return false;
}
public static boolean base64ToImageOutput(String base64, OutputStream out) throws IOException {
if (base64 == null) { // 图像数据为空
return false;
}
try {
// base64解码
byte[] bytes = org.apache.commons.codec.binary.base64.decodebase64(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
// 生成jpeg图片
out.write(bytes);
out.flush();
return true;
} finally {
try {
out.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
public static byte[] base64ToByte(String base64) throws IOException {
if (base64 == null) { // 图像数据为空
return null;
}
// base64解码
byte[] bytes = org.apache.commons.codec.binary.base64.decodebase64(base64);
for (int i = 0; i < bytes.length; ++i) {
if (bytes[i] < 0) {// 调整异常数据
bytes[i] += 256;
}
}
return bytes;
}
}