<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0">
<meta name="description" content="PDF Viewer" />
<title>Convert PDF To Image</title>
</head>
<body>
<div class="stats">
<div class="box">
<span class="value">大小</span>
<span class="parameter" id="sizeText"></span>
</div>
<div class="box">
<span class="value">页数</span>
<span class="parameter" id="pagesText"></span>
</div>
</div>
<div id="imgDiv" style="width: 320px; height:160px; border: 1px solid rgba(30, 135, 240, 1); border-radius: 8px; overflow: hidden;" ></div>
</body>
<!-- 引入jq -->
<script type="text/javascript" src="./jq.js"></script>
<!-- 引入pdf.js -->
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.288/build/pdf.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.288/build/pdf.worker.min.js"></script>
<script>
//文件地址
var pdfUrl = './dengjipai.pdf';
var xhr = new XMLHttpRequest();
xhr.open("get", pdfUrl, true);
//至关重要
xhr.responseType = 'arraybuffer'; //'blob'也可以,如果是'Blob'需要用FileReader转换为'arraybuffer'
xhr.onload = function () {
if (this.status == 200) {
console.log(this.response ,'123');
var oArrayBuffer = this.response;
console.log(oArrayBuffer);
var fileSize = oArrayBuffer.byteLength;
var mb = fileSize / 1048576;
if(fileSize) {
mb = fileSize / 1048576;
if(mb > 2) {
alert("文件大小不能>2M");
return;
}
}
$("#sizeText").text(mb.toFixed(2) + "Mb");
var typedarray = new Uint8Array(oArrayBuffer);
//中文字体缺失
PDFJS.cMapUrl = 'https://cdn.jsdelivr.net/npm/pdfjs-dist@2.0.288/cmaps/';
PDFJS.cMapPacked = true;
PDFJS.getDocument(typedarray).then(function(pdf) { //PDF转换为canvas
if(pdf) {
console.log(pdf.numPages);
var pageNum = pdf.numPages;
$("#pagesText").text(pageNum);
var canvas = document.createElement('canvas');
canvas.id = "pageNum" + i;
$("#imgDiv").append(canvas);
var context = canvas.getContext('2d');
openPage(pdf, pageNum, context);
for(var i = 1; i <= pageNum; i++) {
var canvas = document.createElement('canvas');
canvas.id = "pageNum" + i;
$("#imgDiv").append(canvas);
var context = canvas.getContext('2d');
openPage(pdf, i, context);
}
}
});
}
}
xhr.send();
function openPage(pdfFile, pageNumber, context) {
var scale = 2; //如果清晰度模糊,可以将值调大
pdfFile.getPage(pageNumber).then(function(page) {
viewport = page.getViewport(scale); // reference canvas via context
var canvas = context.canvas;
canvas.width = viewport.width;
canvas.height = viewport.height;
canvas.style.width = "100%";
canvas.style.height = "100%";
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
};
</script>
</html>
前端PDF文件显示到页面
最后编辑于 :
©著作权归作者所有,转载或内容合作请联系作者
- 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
- 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
- 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...