因需求所以要在页面显示PDF,查了很多都是使用标签去展示,可参考:【HTML】如何直接在网页中显示PDF文件?
以下为使用pdf.js预览PDF,话不多说,代码奉上
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html>
<head>
<%-- 主要是使用IE去显示 --%>
<meta name="renderer" content="ie-stand"/>
<%-- 但可能使用其他浏览器 --%>
<meta name="force-rendering" content="webkit"/>
<%-- 使用浏览器的最新内核 --%>
<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1"/>
<meta http-equiv="Content-Type" content="text/html; charset=Big5"/>
<script type="text/javascript" src="../js/pdf.js"></script>
<style type="text/css">
.PDF_showUi {
// 显示边框
#border:1px solid black;
padding: 0px;
// 控制 PDF 左边的空白不显示在元素内
margin-left: -60px;
}
canvas {
// 显示边框
#border:1px solid black;
padding: 0px;
// 控制 PDF 上边的空白不显示在元素内
margin-top: -20px;
}
</style>
<script type="text/javascript">
// 检查文件是否存在
function fileExists(url){
var isExists;
$.ajax({
url:url, // PDF路径
async:false,
type:'HEAD',
timeout:2000,
error:function(){
isExists=0;
},
success:function(){
isExists=1;
}
});
return (isExists==1);
}
/*
* 追加 PDF 显示在 元素
* showUi: 显示的元素位置
* pdf_Path_file:PDF路径
*/
function add_PDF(showUi, pdf_Path_file) {
// 检查文件是否存在
if (!fileExists(pdf_Path_file)){
// not found pdf_Path_file
return;
}
// pdf.worker.js
PDFJS.workerSrc = basePath+'/js/pdf.worker.js';
var loadingTask = PDFJS.getDocument({ url: pdf_Path_file });
loadingTask.promise.then(function(pdf) {
// pdfPages PDF总页数
var pdfPages = pdf.numPages;
for (var i = 0; i <= pdfPages; i++) {
// 获取PDF每1页去显示
pdf.getPage(i).then(function(page) {
// 获取PDF的当前页
var pageNum = page.pageNumber;
// 縮放,放大
var scale = 10;
// 像素比,越小顯示越大
var pixelRatio = 7.7;
var viewport = page.getViewport(scale);
// create canvas
var canvas=document.createElement('canvas');
canvas.align = "left";
canvas.id = "pageNum" + pageNum;
var context = canvas.getContext('2d');
var transform = [pixelRatio, 0, 0, pixelRatio, 0, 0];
var width = 730;
var height = 1080;
canvas.width = width * pixelRatio;
canvas.height = height * pixelRatio;
canvas.style.height = height+"px";
canvas.style.width = width+"px";
var renderContext = {
canvasContext: context,
viewport: viewport,
transform : transform
};
page.render(renderContext);
showUi.className = "PDF_showUi";
showUi.appendChild(canvas);
});
}
});
}
function onload(){
var pdf_Path_file = '../pdf/xxx.pdf; //pdf addr
add_PDF(document.getElementById("PDF_example1"), pdf_Path_file);
}
</script>
</head>
<body onLoad="onload();">
<div id="PDF_example1" align="left"></div>
</body>
</html>
以下为一些参考文章
另外有关显示时,不同浏览器兼容问题,可参考:【META 标签的 HTTP-EQUIV=“X-UA-COMPATIBLE“ 使用说明】
pdfjs和pdf.worker 可以在参考文章中下载
另外需要一个来判断显示的PDF是否存在
另外PDF预览可能会模糊 ,注意 scale & pixelRatio 的使用
参考:提高PDF预览的清晰度