拓展知识点,合并pddf元素,依据pdf编辑元素数据合并输出pdf文件,在开发过程中的发散思维,记录一下
代码逻辑:
/**
* 依据pdf编辑元素数据合并输出pdf文件
*/
@RequestMapping(value = "/v1/pdfEdit/mergeImageOutPdf/{fileInfoId}", method = RequestMethod.GET)
public void mergeImageOutPdf(HttpServletRequest request, HttpServletResponse response, @PathVariable("fileInfoId") String fileInfoId) {
try {
//准备
Map<String, Object> qmap = new HashMap<>();
qmap.clear();
qmap.put("fileInfoId", fileInfoId);
qmap.put("isDelete", Constants.NO_INT);
FileAttachmentPo fileAttachmentPo = null;
List<FileAttachmentPo> fileAttachmentPoList = fileAttachmentFacade.queryByMap(qmap);
if (fileAttachmentPoList != null && !fileAttachmentPoList.isEmpty()) {
fileAttachmentPo = fileAttachmentPoList.get(0);
}
//
qmap.clear();
qmap.put("fileInfoId", fileInfoId);
qmap.put("isDelete", Constants.NO_INT);
List<PdfEditPo> pdfEditPoList = pdfEditFacade.queryByMap(qmap);
Map<String, String> listMapKeyPageNo = new HashMap<>();
for (int i = 0; i < pdfEditPoList.size(); i++) {
PdfEditPo item = pdfEditPoList.get(i);
listMapKeyPageNo.put(item.getPageNo(), item.getBase64Decoder());
}
List<String> base64DecoderList = new ArrayList<>();
for (int i = 1; i < pdfEditPoList.size() + 1; i++) {
base64DecoderList.add(listMapKeyPageNo.get(i + ""));
}
//开始合并
PDDocument pdDocument = new PDDocument();
PDPageContentStream contentStream = null;
ByteArrayInputStream byteIn = null;
for (int i = 0; i < base64DecoderList.size(); i++) {
//base64Decoder 解析为图片
BASE64Decoder decoder = new BASE64Decoder();
String base64Decoder = base64DecoderList.get(i);
byte[] decoderBytes = decoder.decodeBuffer(base64Decoder.split(",")[1]);
byteIn = new ByteArrayInputStream(decoderBytes); //将b作为输入流;
BufferedImage image = ImageIO.read(byteIn);
//图片格式化为 pdf文档页面
PDPage pdPage = new PDPage(new PDRectangle(image.getWidth(), image.getHeight()));
pdDocument.addPage(pdPage);
//输出为pdf数据
contentStream = new PDPageContentStream(pdDocument, pdPage);
PDImageXObject pdImageXObject = LosslessFactory.createFromImage(pdDocument, image);
contentStream.drawImage(pdImageXObject, 0, 0, image.getWidth(), image.getHeight());
//
contentStream.close();
byteIn.close();
}
//设置MIME类型
response.setContentType("application/octet-stream");
//或者为response.setContentType("application/x-msdownload");
String fileName = fileAttachmentPo.getFileName();
//设置头信息,设置文件下载时的默认文件名,同时解决中文名乱码问题
response.addHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes(), "ISO-8859-1"));
//保存文件 或则 字节流
//pdDocument.save(filename);
pdDocument.save(response.getOutputStream());
pdDocument.close();
} catch (Exception e) {
logger.error("依据pdf编辑元素数据合并输出pdf文件服务器出现异常", e);
//return AjaxResult.error(AjaxResult.ERROR_CODE, messageSource.getMessage("server.error", null, "服务器出现异常,请联系管理员", getLocal()));
}
}