后台代码:
public static void base64StringToPdf(String base64Content,String filePath){
File file = new File(filePath);// 将原来参数修改为字符串
BASE64Decoder decoder = new BASE64Decoder();
BufferedInputStream bin = null;
FileOutputStream fout = null;
BufferedOutputStream bout = null;
try {
//将base64编码的字符串解码成字节数组
byte[] bytes = decoder.decodeBuffer(base64Content);
//创建一个将bytes作为其缓冲区的ByteArrayInputStream对象
ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
//创建从底层输入流中读取数据的缓冲输入流对象
bin = new BufferedInputStream(bais);
//创建到指定文件的输出流
fout = new FileOutputStream(file);
//为文件输出流对接缓冲输出流对象
bout = new BufferedOutputStream(fout);
byte[] buffers = new byte[1024];
int len = bin.read(buffers);
while(len != -1){
bout.write(buffers, 0, len);
len = bin.read(buffers);
}
//刷新此输出流并强制写出所有缓冲的输出字节,必须这行代码,否则有可能有问题
bout.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
bout.close();
fout.close();
bin.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
前台是将页面展示的数据图标什么的生成PDF
前台代码:
function downloadofpdf(){
var varname = $("#taskid").text();
if(confirm("您确认下载该PDF文件吗?")){
var target = document.getElementById("bodyid");
target.style.background = "#FFFFFF";
// if(pdfName==''||pdfName==undefined) pdfName= getNowFormatDate();
html2canvas(target, {
onrendered:function(canvas) {
var contentWidth = canvas.width;
var contentHeight = canvas.height;
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth /1592.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 595.28;
var imgHeight = 592.28/contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0);
var pdf = new jsPDF('', 'pt', 'a4');
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight );
} else {
while(leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight);
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if(leftHeight > 0) {
pdf.addPage();
}
}
}
pdf.save(varname+".pdf");
// 将pdf输入为base格式的字符串
var buffer = pdf.output("datauristring");
// // 将base64格式的字符串转换为file文件
// var myfile = dataURLtoFile(buffer, varname);
// var formdata = new FormData();
// formdata.append(name, myfile);
$.post("/riskManage/uploadpdf",{data:JSON.stringify({formdata:buffer})},function(result){
//alert("hao");
})
//sc();
},
background: "#fff"
})
}
}