话不多说,直接上干货。
uniapp 部分
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
function downPdf(element) {
// window.scrollTo(0, 0) //首先滚动到顶部 如果要某一个元素 就滚动到元素位置
let that = this;
//document.querySelector('#toPDF')
html2canvas(element, { //对应的dom元素id(class也可以)
allowTaint: true, //是否允许跨域图像渲染画布
useCORS: true, //是否尝试使用 CORS 从服务器加载图像 解决图片跨域问题
}).then(function(canvas) {
//生成的canvas实例
var contentWidth = canvas.width; //所选元素宽度
var contentHeight = canvas.height; //所选元素高度
//一页pdf显示html页面生成的canvas高度;
var pageHeight = contentWidth / 595.28 * 841.89;
//未生成pdf的html页面高度
var leftHeight = contentHeight;
//pdf页面偏移
var position = 0;
//a4纸的尺寸[595.28,841.89],html页面生成的canvas在pdf中图片的宽高
var imgWidth = 555.28;
var imgHeight = 555.28 / contentWidth * contentHeight;
var pageData = canvas.toDataURL('image/jpeg', 1.0); //转成jpg格式
var pdf = new jspdf('', 'pt', 'a4'); //生成pdf实例
//有两个高度需要区分,一个是html页面的实际高度,和生成pdf的页面高度(841.89)
//当内容未超过pdf一页显示的范围,无需分页
if (leftHeight < pageHeight) {
pdf.addImage(pageData, 'JPEG', 20, 0, imgWidth, imgHeight);
} else {
while (leftHeight > 0) {
pdf.addImage(pageData, 'JPEG', 20, position, imgWidth, imgHeight)
leftHeight -= pageHeight;
position -= 841.89;
//避免添加空白页
if (leftHeight > 0) {
pdf.addPage();
}
}
}
//保存
// let s = pdf.save('贷前调查报告.pdf');
//可以吧生成的pdf转成其他格式 如 base64
let base64 = pdf.output('datauristring') //获取到base64 的pdf
window.JSInterface.html2Base64(base64.substr(51))
}).catch(err => {
console.log(JSON.stringify(err));
})
}
export default {
downPdf
}
至于说怎么引入
import html2canvas from 'html2canvas';
import jspdf from 'jspdf';
网上教程很多,自行搜索。
android 部分
private void readPdf(String result) {
// 将base64转成文件存到本地
byte[] buffer = Base64.decode(result, Base64.DEFAULT);
// 保存地址
path = Environment.getExternalStorageDirectory().getAbsolutePath() + "/报告.pdf";
Log.i(TAG, "readPdf: "+path);
if (FileUtils.isFileExists(path)) {
FileUtils.deleteFile(new File(path));
}
try {
FileOutputStream out = new FileOutputStream(path);
out.write(buffer);
out.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
// 保存完成后打开预览
if (!FileUtils.isFileExists(path)) {
return;
}
File file = new File(path);
pdf.fromFile(file)
.defaultPage(1)
.swipeVertical(true)
.enableSwipe(true)
.onPageChange(this)
.onLoad(new OnLoadCompleteListener() {
@Override
public void loadComplete(int nbPages) {
float pageWidth = pdf.getOptimalPageWidth();
float viewWidth = pdf.getWidth();
pdf.zoomTo(viewWidth/pageWidth);
pdf.loadPages();
}
}).load();
}
result 就是H5生成的base64. 记得此base64需要把头截取掉。