原生js实现pdf文件流转图片
// 在页面引入
<script src="https://mozilla.github.io/pdf.js/build/pdf.js"></script>
<script src="https://mozilla.github.io/pdf.js/build/pdf.worker.js"></script>
var oReq = new XMLHttpRequest();
oReq.open("GET", url, true);
oReq.setRequestHeader('X-Auth-token', token);
oReq.responseType = "blob";
oReq.onload = function () {
console.log(oReq.response)
console.log('------')
var file = new File([oReq.response], 'x.pdf', {
type: 'application/pdf'
});
// 拿到文件流字符串、手动生成url,如果直接给的是真是的pdf的url那就不需要走这一步
const fileURL = URL.createObjectURL(file)
let imgArr = [];
pdfjsLib.workerSrc = 'pdf.worker.js';
// 异步下载pdf
const loadingTask = pdfjsLib.getDocument(fileURL);
// 加载pdf
loadingTask.promise.then(function(pdf) {
let pageNum = pdf.numPages;
// console.log(pageNum);
for (let i=1; i<=pageNum; i++) {
pdf.getPage(i).then(function(page) {
console.log(page,'Page loaded');
let canvas = document.createElement("canvas");
let context = canvas.getContext('2d');
// 获取到屏幕倒是是几倍屏。
let getPixelRatio = function(context) {
var backingStore = context.backingStorePixelRatio ||
context.webkitBackingStorePixelRatio ||
context.mozBackingStorePixelRatio ||
context.msBackingStorePixelRatio ||
context.oBackingStorePixelRatio ||
context.backingStorePixelRatio || 1;
return (window.devicePixelRatio || 1) / backingStore;
};
// iphone6下得到是2
const pixelRatio = getPixelRatio(canvas)*2;
// 如果生成的图片是镜像颠倒的
/*
在 2.0.943 及更早版本中,它采用“常规”参数,即 格式为 getViewport(scale、rotate、dontFlip)。
在 2.1.266 及更高版本中,它需要一个对象,即格式化为 getViewport({ 缩放,旋转,dontFlip })
*/
let viewport = page.getViewport({scale: pixelRatio, rotate:'-180deg'});
canvas.height = pixelRatio * viewport.height;
canvas.width = pixelRatio * viewport.width;
let renderContext = {
canvasContext: context,
viewport: viewport
};
let renderTask = page.render(renderContext);
// 【重要】默认转化的格式为png,也可设置为其他格式 , 1mm = 3.7795 px转菜鸟尺寸
// 这里是渲染完毕
renderTask.promise.then(function (res) {
console.log(canvas,'Page rendered');
let imgUrl = canvas.toDataURL('image/jpeg'); //转换为base64
if (imgUrl) {
imgArr[i-1] = {}
imgArr[i-1]['src'] = imgUrl;
imgArr[i-1]['width'] = parseInt(viewport.width/3.7795);
imgArr[i-1]['height'] = parseInt(viewport.height/3.7795);
}
resolve(imgArr)
});
});
}
})
};
oReq.send();