我创建了一个 html 文件,内容如下 index.html
<html>
<head>
<script type="text/javascript" src="./pdf.js"></script>
<script type="text/javascript" src="./hello.js"></script>
</head>
<body>
<canvas id="the-canvas" style="border:1px solid black;"/>
</body>
</html>
hello.js 内容
PDFJS.disableWorker = true;
var pf = PDFJS.getDocument('./helloworld.pdf')
pf.then(function(pdf) {
pdf.getPage(1).then(function(page) {
var scale = 1.5;
var viewport = page.getViewport(scale);
//
// Prepare canvas using PDF page dimensions
//
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
//
// Render PDF page into canvas context
//
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext);
});
});
但是当我将浏览器指向 index.html 时,pdf 显示不正确。 我希望用户能够在他的计算机上选择一个 pdf 文件并在浏览器窗口中显示该 pdf。
最佳答案
看起来您在使用 file:
协议(protocol)而不是 http:
或 https:
时遇到了这个问题。不同协议(protocol)之间存在不同的安全考虑因素。
这是 a blog post about using XMLHttpRequest
with local files , 和一个 discussion on a Mozilla Firefox ticket .
项目中有一些票证(包括 this one 和 this one )可以提供指导。来自 this ticket 的评论说:
Typical pdf.js use cases requires to use a web server and modern HTML5 browser.
我建议解决您的问题您只需通过网络服务器运行它以使用http
协议(protocol)。 Nginx 和 Apache 易于安装和设置。
如果这不起作用,请使用 this 为您的系统生成 pdf.js 和 pdf.worker.js如果上述步骤不起作用。
关于javascript - 如何使用 pdf.js 呈现 pdf 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22661794/