org.freemarker freemarker2.3.30
2、创建模板com.aspose aspose-words15.8.0
一种快捷创建模板的方式,将word样本打开,另存为xml文件
3、将生成好的xml模板文件放入resources下,新建一个templates文件夹将文件放入下面 4、导出worldpublic ByteArrayOutputStream createWord(Map5.word转pdfdataMap, String templateName,String fileName) { log.info("{}:产品要素表导出word开始生成...",fileName); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8); Writer out = new BufferedWriter(oWriter); try { InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName)); createWordTemplate(new String(IOUtils.toByteArray(inputStream))).process(dataMap, out); } catch (IOException | TemplateException e) { log.error("{}:产品要素表导出word失败:",fileName, e); } finally { try { out.flush(); out.close(); } catch (IOException e) { log.error("{}:产品要素表导出word关闭流失败", fileName,e); } } log.info("{}:产品要素表导出word生成完成...",fileName); return outputStream; }
public static ByteArrayOutputStream wordToPdf(ByteArrayOutputStream outputStream,String fileName) {
log.info("{}:产品要素表导出pdf开始生成...",fileName);
ByteArrayOutputStream byteArrayOutputStream = null;
// 验证License 若不验证则转化出的pdf文档会有水印产生:
// Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd
if (getLicense()) {
byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
try {
Document document = new Document(inputStream);
document.save(byteArrayOutputStream, SaveFormat.PDF);
} catch (Exception e) {
log.error("{}:产品要素表导出pdf,word转pdf失败",fileName, e);
}
}
log.info("{}:产品要素表导出pdf生成完成...",fileName);
return byteArrayOutputStream;
}
完成代码
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.manager.dto.product.rsp.ExportProductPdfAndWordRsp;
import com.manager.enums.ContentTypeEnum;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.io.IOUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;
import org.springframework.core.io.ClassPathResource;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
@Slf4j
public class HtmlToWordUtil {
private static AtomicInteger TEMPLATE_ID = new AtomicInteger(0);
private final static String DOC = ".doc";
private final static String PDF = ".pdf";
public HtmlToWordUtil() {
}
public ByteArrayOutputStream createWord(Map dataMap, String templateName,String fileName) {
log.info("{}:产品要素表导出word开始生成...",fileName);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
OutputStreamWriter oWriter = new OutputStreamWriter(outputStream, StandardCharsets.UTF_8);
Writer out = new BufferedWriter(oWriter);
try {
InputStream inputStream = this.getClass().getResourceAsStream("/templates/".concat(templateName));
createWordTemplate(new String(IOUtils.toByteArray(inputStream))).process(dataMap, out);
} catch (IOException | TemplateException e) {
log.error("{}:产品要素表导出word失败:",fileName, e);
} finally {
try {
out.flush();
out.close();
} catch (IOException e) {
log.error("{}:产品要素表导出word关闭流失败", fileName,e);
}
}
log.info("{}:产品要素表导出word生成完成...",fileName);
return outputStream;
}
private Template createWordTemplate(String templateString) throws IOException {
StringTemplateLoader stringLoader = new StringTemplateLoader();
String id = String.valueOf(TEMPLATE_ID.incrementAndGet());
stringLoader.putTemplate(id, templateString);
Configuration cfg = new Configuration(Configuration.VERSION_2_3_30);
cfg.setDefaultEncoding("utf-8");
cfg.setTemplateLoader(stringLoader);
return cfg.getTemplate(id);
}
public static ByteArrayOutputStream wordToPdf(ByteArrayOutputStream outputStream,String fileName) {
log.info("{}:产品要素表导出pdf开始生成...",fileName);
ByteArrayOutputStream byteArrayOutputStream = null;
// 验证License 若不验证则转化出的pdf文档会有水印产生:
// Evaluation Only. Created with Aspose.Words. Copyright 2003-2015 Aspose Pty Ltd
if (getLicense()) {
byteArrayOutputStream = new ByteArrayOutputStream();
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
try {
Document document = new Document(inputStream);
document.save(byteArrayOutputStream, SaveFormat.PDF);
} catch (Exception e) {
log.error("{}:产品要素表导出pdf,word转pdf失败",fileName, e);
}
}
log.info("{}:产品要素表导出pdf生成完成...",fileName);
return byteArrayOutputStream;
}
private static boolean getLicense() {
boolean result = false;
try {
InputStream inputStream = new ClassPathResource("license.xml").getInputStream();
License aposeLic = new License();
aposeLic.setLicense(inputStream);
result = true;
} catch (Exception e) {
log.error("产品要素表导出pdf,word转pdf去Aspose.Words水印失败", e);
}
return result;
}
public void zipPdfOrWord(String fileName, List importDtoList, Integer wordAndPdf, String templateName, HttpServletResponse response) throws IOException {
response.setContentType(ContentTypeEnum.STREAM.getCodeText());
response.setHeader("Content-disposition", "attachment; filename*=utf-8''" + URLEncoder.encode(fileName + ".zip", "UTF-8"));
ZipOutputStream zipOut = new ZipOutputStream(response.getOutputStream());
if (CollectionUtils.isEmpty(importDtoList)) {
return;
}
for (ExportProductPdfAndWordRsp dto : importDtoList) {
Map importData = getImportData(dto);
if (NumberUtils.INTEGER_ONE.equals(wordAndPdf)) {
ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
String name = ("word/") + dto.getProductFullName().concat(DOC);
zipOut.putNextEntry(new ZipEntry(name));
zipOut.write(word.toByteArray());
}
if (NumberUtils.INTEGER_TWO.equals(wordAndPdf)) {
ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
ByteArrayOutputStream pdf = wordToPdf(word,dto.getProductFullName());
String name = ("pdf/") + dto.getProductFullName().concat(PDF);
zipOut.putNextEntry(new ZipEntry(name));
zipOut.write(pdf.toByteArray());
}
if (NumberUtils.INTEGER_ZERO.equals(wordAndPdf)) {
ByteArrayOutputStream word = createWord(importData, templateName,dto.getProductFullName());
String wordName = ("word/") + dto.getProductFullName().concat(DOC);
zipOut.putNextEntry(new ZipEntry(wordName));
zipOut.write(word.toByteArray());
ByteArrayOutputStream pdf = wordToPdf(word,dto.getProductFullName());
String pdfName = ("pdf/") + dto.getProductFullName().concat(PDF);
zipOut.putNextEntry(new ZipEntry(pdfName));
zipOut.write(pdf.toByteArray());
}
}
zipOut.closeEntry();
response.flushBuffer();
zipOut.close();
}
private static Map getImportData(ExportProductPdfAndWord dto) {
Map dataMap = new HashMap<>();
dataMap.put("userName", dto.getUserName());
dataMap.put("age", dto.getAge());
return dataMap;
}
6.调用
new HtmlToWordUtil().zipPdfOrWord("导出",rspList,req.getWordAndPdf(), "导出.xml",response);



