需求是一个导出pdf的功能,多方奔走终于实现了,走了不少弯路,而且怀疑现在这个方法仍是弯的。
有个jsPDF 插件可以在前端直接生成pdf,很简便,但不支持IE。
前端:
首先引入
html2canvas.js
//将以base64的图片url数据转换为Blob
function convertBase64UrlToBlob(urlData){
//去掉url的头,并转换为byte
var bytes=window.atob(urlData.split(',')[1]);
//处理异常,将ascii码小于0的转换为大于0
var ab = new ArrayBuffer(bytes.length);
var ia = new Uint8Array(ab);
for (var i = 0; i < bytes.length; i++) {
ia[i] = bytes.charCodeAt(i);
}
return new Blob( [ab],{type : 'image/png'});
}
兼容性:Firefox 3.5+,Chrome,Opera,IE10+
access-control-allow-origin: * access-control-allow-credentials: true
IE9不支持FormData数据格式,也不支持Blob,这种情况下将canvas生成的64base字符串去掉url头之后直接传给后台,后台接收之后:
后端:
导入 itext jar包
<div class="jb51code">
<pre class="brush:js;">
@RequestMapping("/exportPdf")
public @ResponseBody void exportPdf(MultipartHttpServletRequest request,HttpServletResponse response)throws ServletException,IOException {
ResultData result = new ResultData(); //自定义结果格式
String filePath = "c:\exportPdf2.pdf";
String imagePath = "c:\exportImg2.bmp";
Document document = new Document();
try{
Map getMap = request.getFileMap();
MultipartFile mfile = (MultipartFile) getMap.get("imgData"); //获取数据
InputStream file = mfile.getInputStream();
byte[] fileByte = FileCopyUtils.copyToByteArray(file);
FileImageOutputStream imageOutput = new FileImageOutputStream(new File(imagePath));//打开输入流
imageOutput.write(fileByte,fileByte.length);//<a href="https://www.jb51.cc/tag/shengcheng/" target="_blank" class="keywords">生成</a>本地<a href="https://www.jb51.cc/tag/tupian/" target="_blank" class="keywords">图片</a><a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>
imageOutput.close();
PdfWriter.getInstance(document,new FileOutputStream(filePath)); //itextpdf<a href="https://www.jb51.cc/tag/wenjian/" target="_blank" class="keywords">文件</a>
// document.setPageSize(PageSize.A2);
document.open();
document.add(new Paragraph("JUST TEST ..."));
Image image = Image.getInstance(imagePath); //itext-pdf-image
float heigth = image.getHeight();
float width = image.getWidth();
int percent = getPercent2(heigth,width); //按比例缩小图片
image.setAlignment(Image.MIDDLE);
image.scalePercent(percent+3);
document.add(image);
document.close();
result.setSuccess(true);
operatelogService.addOperateLogInfo(request,"导出成功:成功导出简报Pdf");
}catch (DocumentException de) {
System.err.println(de.getMessage());
}
catch (Exception e) {
e.printStackTrace();
result.setSuccess(false);
result.setErrorMessage(e.toString());
try {
operatelogService.addOperateLogError(request,"导出失败:服务器异常");
} catch (Exception e1) {
e1.printStackTrace();
}
}
response.getWriter().print(JSONObject.fromObject(result).toString());
}
private static int getPercent2(float h,float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}