社区微信群开通啦,扫一扫抢先加入社区官方微信群
社区微信群
废话不多说,还得废话一句 :太菜了 一个坑爬另一个坑,差点放弃了,还好实现了
思路
实现也比较简单 ,但我在jspdf 转 base64的时候遇到了麻烦 ,官网 http://mrrio.github.io/上的例子转的 是
形如 data:application/pdf;base64,JVBERi0xLj…
而我 的是
形如 data:application/pdf;filename=generated.pdf;base64,JVBERi0xL…
而这也导致了转的码用PDFjs无法正常解码,然后就开始搞,之前以为是版本问题 虽引入旧版测试 ,果然 没fienname这个了 ,但还是打不开,这就是转码方式不对了。虽转变策略,用二进制文件终于能正常打开了 ,预览 、打印、下载等也没问题
效果如下
主要代码
var pdfDom = document.querySelector(id);//要转图片的html
html2Canvas(pdfDom, {
//相关参数 百度 帖子很多
useCORS: true,
allowTaint: true,
// 清晰度
dpi: window.devicePixelRatio,
scale:2
}).then(function (canvas) {
console.log(canvas)
const marginBottom = 34 // 项目页面显示微处理
let canvasWidth = canvas.width //页面生成canvas宽度
let canvasHeight = canvas.height + marginBottom //页面生成canvas高度
let pageHeight = canvasWidth / 592.28 * 841.89 + marginBottom //分页 每页的高度
let allPageHeight = canvasHeight // 所有页面的高度
let position = 0 //偏移量
let imgWidth = 595.28 //生成canvas 图片的宽度
let imgHeight = 592.28 / canvasWidth * canvasHeight //生成canvas 图片的高度
let pageData = canvas.toDataURL('image/jpeg', 3.0)
// console.log(pageData);
//将图片放入jspdf
let PDF = new JsPDF('', 'pt', 'a4')
if (allPageHeight < pageHeight) {
PDF.addImage(pageData, 'JPEG', 0, 0, imgWidth, imgHeight)
} else {
// 循环生成分页
while (allPageHeight > 0) {
PDF.addImage(pageData, 'JPEG', 0, position, imgWidth, imgHeight)
allPageHeight = allPageHeight - pageHeight - marginBottom
position = position - 841.89 - marginBottom
if (allPageHeight > 0) {
PDF.addPage() //添加新的一页
}
}
}
// PDF.output('datauri'); 调用这个就可以打印了 下载无格式,体验差点 (并不是打开新页面,这样返回时页面会刷新)
// var base = PDF.output('datauristring');
//以上内容帖子很多
// data:application/pdf;filename=generated.pdf;base64, -- 我的时这样 官网的没filename这些,我拿过来可以用PDFjs打开,但我的不行
/***
// var base = window.atob(base64) 解码
// var binaryData = [];
// binaryData.push(base);
// let url =window.URL.createObjectURL(new Blob(binaryData, {type:"application/zip"}));
之前写法,base合适可以用
*/
var blob = PDF.output( 'blob' )//输出为blob
console.log(blob);
//blob转url
var urll = window.URL.createObjectURL(new File( [blob], 'a_name.pdf', { type: 'application/pdf' } ))
//用PDFjs打开这个url能看到pdf 可以打印 /下载等
//viewer.html 时本地路径 具体看下面
window.open('../static/pdf/web/viewer.html?file='+encodeURIComponent(urll))
})
其他两个就不说了
PDFjs http://mozilla.github.io/pdf.js/
我这个也没改啥,解压后有11M 删除一些无关紧要的文件 剩余4.7M 勉强接受
剩下的基本都加载了或者太小,懒得找
完
如果觉得我的文章对您有用,请随意打赏。你的支持将鼓励我继续创作!