添加pom依赖
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-export-fo</artifactId>
<version>8.2.4</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>4.1.0</version>
</dependency>
java代码:
package com.stylefeng.roses.report.modular.controller;
import cn.afterturn.easypoi.word.WordExportUtil;
import cn.afterturn.easypoi.word.entity.MyXWPFDocument;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.stylefeng.roses.core.base.controller.BaseController;
import com.stylefeng.roses.core.base.response.SuccessResponseData;
import com.stylefeng.roses.report.modular.model.Prescribe;
import com.stylefeng.roses.report.modular.model.PrescribeDetail;
import com.stylefeng.roses.report.modular.model.PrescribeNutrient;
import com.stylefeng.roses.report.modular.service.IPrescribeNutrientService;
import com.stylefeng.roses.report.modular.service.IPrescribeService;
import com.stylefeng.roses.report.modular.util.PdfUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.*;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;
/**
* 处方控制器
*/
@RestController
@RequestMapping("/prescribeNutrient")
public class PrescribeNutrientController extends BaseController {
private static final Log log = LogFactory.getLog(PrescribeNutrientController.class);
@Autowired
private IPrescribeNutrientService prescribeNutrientService;
@Autowired
private IPrescribeService prescribeService;
@PostMapping("/getDetail")
public Object getDetail(@RequestBody Map<String, String> param) {
String prescribeName = param.get("prescribeName");
List<PrescribeNutrient> prescribeNutrientList = new ArrayList<>();
if (StrUtil.isNotBlank(prescribeName)) {
EntityWrapper<PrescribeNutrient> wrapper = new EntityWrapper<>();
wrapper.eq("prescribe_name", prescribeName);
prescribeNutrientList = prescribeNutrientService.selectList(wrapper);
}
Map<String, List<PrescribeNutrient>> collect = prescribeNutrientList.stream().collect(Collectors.groupingBy(PrescribeNutrient::getPrescribeType));
return SuccessResponseData.success(collect);
}
@PostMapping("/getPreList")
public Object getPreList() {
List<PrescribeNutrient> prescribeNutrientList = prescribeNutrientService.getPreList();
return SuccessResponseData.success(prescribeNutrientList);
}
@GetMapping("/exportPdf")
public void exportPdf(@RequestParam(name = "id") String id, HttpServletRequest request, HttpServletResponse response) {
try {
//查询处方及详情
Map<String, Object> prescribeDetail = prescribeService.getPrescribeDetail(id);
if (ObjectUtil.isNull(prescribeDetail.get("prescribe"))) {
throw new Exception("处方不存在");
}
Prescribe prescribe = (Prescribe) prescribeDetail.get("prescribe");
List<PrescribeDetail> prescribeDetails = new ArrayList<>();
if (ObjectUtil.isNotNull(prescribeDetail.get("prescribe"))) {
prescribeDetails = (List<PrescribeDetail>) prescribeDetail.get("prescribeDetails");
}
Map<String, Object> form = new HashMap<>();
form.put("invoiceName", prescribe.getPatientName());
Date createTime = prescribe.getCreateTime();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
String dateStr = sdf.format(createTime);
form.put("invoiceDate", dateStr);
//查询营养素列表
EntityWrapper<PrescribeNutrient> wrapper = new EntityWrapper<>();
List<PrescribeNutrient> prescribeNutrientList = prescribeNutrientService.selectList(wrapper);
Map<String, Map<String, List<PrescribeNutrient>>> collect = prescribeNutrientList.stream().collect(Collectors.groupingBy(PrescribeNutrient::getPrescribeName, Collectors.groupingBy(PrescribeNutrient::getPrescribeType)));
List<Map<String, Object>> listMap = new ArrayList<>();
for (int i = 0; i < prescribeDetails.size(); i++) {
Map<String, Object> lm = new HashMap<>();
PrescribeDetail detail = prescribeDetails.get(i);
String prescribeName = detail.getPrescribeName();
lm.put("id", String.valueOf(i + 1));
lm.put("num", detail.getNumber());
//通过处方单详情营养素id,查询营养素详情
Map<String, List<PrescribeNutrient>> object1 = collect.get(detail.getPrescribeNutrientId().toString());
if (ObjectUtil.isNotNull(object1)) {
List<PrescribeNutrient> yfyl = object1.get("用法用量");
List<PrescribeNutrient> cfjs = object1.get("成分介绍");
List<PrescribeNutrient> gxjs = object1.get("功效介绍");
if (ObjectUtil.isNotNull(yfyl)) {
lm.put("name", prescribeName + "\n" + yfyl.get(0).getPrescribeNameEn());
lm.put("yfyl", StringUtils.join(yfyl.stream().map(PrescribeNutrient::getPrescribeContent).collect(Collectors.toList()), "\n"));
}
if (ObjectUtil.isNotNull(cfjs)) {
lm.put("cfjs", StringUtils.join(cfjs.stream().map(PrescribeNutrient::getPrescribeContent).collect(Collectors.toList()), "\n"));
}
if (ObjectUtil.isNotNull(gxjs)) {
List<String> gxjsList = gxjs.stream().map(PrescribeNutrient::getPrescribeContent).collect(Collectors.toList());
lm.put("gxjs", StringUtils.join(gxjsList, "\n"));
}
} else {
lm.put("yfyl", "");
lm.put("cfjs", "");
lm.put("gxjs", "");
}
listMap.add(lm);
}
form.put("mapList", listMap);
//导出word
ClassPathResource classPathResource = new ClassPathResource("templates/prescription_template.docx");
InputStream inputStream = classPathResource.getInputStream();
MyXWPFDocument document = new MyXWPFDocument(inputStream);
WordExportUtil.exportWord07(document, form);
//表格内容换行
PdfUtil.tableCells(document);
String realPath = request.getSession().getServletContext().getRealPath("/");
String sourcePath = realPath + "test.docx";
FileOutputStream fos = new FileOutputStream(sourcePath);
document.write(fos);
fos.close();
String targetPath = realPath + "test.pdf";
//word转pdf
PdfUtil.word2pdf(sourcePath, targetPath);
//下载
File file = new File(targetPath);
if (file.exists()) {
int fileLength = (int) file.length();
if (fileLength != 0) {
String suffix = targetPath.substring(targetPath.lastIndexOf("."));
//自定义文件名
String realFileName = System.currentTimeMillis() + suffix;
realFileName = new String(realFileName.getBytes(), "ISO-8859-1");
response.reset();
response.setContentType("application/octet-stream");
response.setHeader("Content-disposition", "attachment;filename=" + realFileName);
response.setContentLength(fileLength);
InputStream is = new FileInputStream(targetPath);
byte[] buffer = new byte[1024];
ServletOutputStream fosout = response.getOutputStream();
int len = 0;
while ((len = is.read(buffer)) != -1) {
fosout.write(buffer, 0, len);
}
is.close();
fosout.flush();
fosout.close();
}
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}
工具类
package com.stylefeng.roses.report.modular.util;
import org.apache.poi.xwpf.usermodel.*;
import org.docx4j.Docx4J;
import org.docx4j.fonts.IdentityPlusMapper;
import org.docx4j.fonts.Mapper;
import org.docx4j.fonts.PhysicalFonts;
import org.docx4j.openpackaging.exceptions.Docx4JException;
import org.docx4j.openpackaging.packages.WordprocessingMLPackage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
public class PdfUtil {
/**
* 表格处理
* */
public static void tableCells(XWPFDocument doc) {
for (XWPFTable table : doc.getTables()) {//表格
for (XWPFTableRow row : table.getRows()) {//行
for (XWPFTableCell cell : row.getTableCells()) {
addBreakInCell(cell);
}
}
}
}
/**
* 替换word换行符
*
* @param cell
*/
private static void addBreakInCell(XWPFTableCell cell) {
if (cell.getText() != null && cell.getText().contains("\n")) {
for (XWPFParagraph p : cell.getParagraphs()) {
for (XWPFRun run : p.getRuns()) {//XWPFRun对象定义具有一组公共属性的文本区域
if (run.getText(0) != null && run.getText(0).contains("\n")) {
String[] lines = run.getText(0).split("\n");
if (lines.length > 0) {
run.setText(lines[0], 0); // set first line into XWPFRun
for (int i = 1; i < lines.length; i++) {
// add break and insert new text
run.addBreak(BreakType.TEXT_WRAPPING);//中断
// run.addCarriageReturn();//回车符,但是不起作用
run.setText(lines[i]);
}
}
}
}
}
}
}
public static void word2pdf(String source, String target) {
try {
WordprocessingMLPackage pkg = Docx4J.load(new File(source));
// Mapper fontMapper = new IdentityPlusMapper();
// fontMapper.put("隶书", PhysicalFonts.get("LiSu"));
// fontMapper.put("宋体", PhysicalFonts.get("SimSun"));
// fontMapper.put("微软雅黑", PhysicalFonts.get("Microsoft Yahei"));
// fontMapper.put("黑体", PhysicalFonts.get("SimHei"));
// fontMapper.put("楷体", PhysicalFonts.get("KaiTi"));
// fontMapper.put("新宋体", PhysicalFonts.get("NSimSun"));
// fontMapper.put("华文行楷", PhysicalFonts.get("STXingkai"));
// fontMapper.put("华文仿宋", PhysicalFonts.get("STFangsong"));
// fontMapper.put("仿宋", PhysicalFonts.get("FangSong"));
// fontMapper.put("幼圆", PhysicalFonts.get("YouYuan"));
// fontMapper.put("华文宋体", PhysicalFonts.get("STSong"));
// fontMapper.put("华文中宋", PhysicalFonts.get("STZhongsong"));
// fontMapper.put("等线", PhysicalFonts.get("SimSun"));
// fontMapper.put("等线 Light", PhysicalFonts.get("SimSun"));
// fontMapper.put("华文琥珀", PhysicalFonts.get("STHupo"));
// fontMapper.put("华文隶书", PhysicalFonts.get("STLiti"));
// fontMapper.put("华文新魏", PhysicalFonts.get("STXinwei"));
// fontMapper.put("华文彩云", PhysicalFonts.get("STCaiyun"));
// fontMapper.put("方正姚体", PhysicalFonts.get("FZYaoti"));
// fontMapper.put("方正舒体", PhysicalFonts.get("FZShuTi"));
// fontMapper.put("华文细黑", PhysicalFonts.get("STXihei"));
// fontMapper.put("宋体扩展", PhysicalFonts.get("simsun-extB"));
// fontMapper.put("仿宋_GB2312", PhysicalFonts.get("FangSong_GB2312"));
// fontMapper.put("新細明體", PhysicalFonts.get("SimSun"));
// pkg.setFontMapper(fontMapper);
Docx4J.toPDF(pkg, new FileOutputStream(target));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (Docx4JException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}