javascript 使用 PDF.JS 和 AngularJS 从字节数组渲染 PDF
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28461238/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Render PDF using PDF.JS and AngularJS from byte array
提问by Jeremy Wagner
I've been following the following links to try to render a byte stream returned from an API to a PDF in browser using PDF.JS:
我一直在关注以下链接,以尝试使用 PDF.JS 将从 API 返回的字节流呈现为浏览器中的 PDF:
- http://codingcrazy87.blogspot.com/2014/05/view-pdf-files-directly-within-browser.html
- https://gist.github.com/fcingolani/3300351
- http://codingcrazy87.blogspot.com/2014/05/view-pdf-files-directly-within-browser.html
- https://gist.github.com/fcingolani/3300351
Here is the JavaScriptused to run render. Note:streamis a byte array returned from an API.
这是用于运行渲染的JavaScript。注意:stream是从 API 返回的字节数组。
var file = new Blob([stream], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$scope.renderPDF(fileURL, document.getElementById('pdf-holder'));
Here is $scope.renderPDF:
这是$scope.renderPDF:
$scope.renderPDF = function(url, canvasContainer) {
var scale= 1.5; //"zoom" factor for the PDF
function renderPage(page) {
var viewport = page.getViewport(scale);
var canvas = document.createElement('canvas');
var ctx = canvas.getContext('2d');
var renderContext = {
canvasContext: ctx,
viewport: viewport
};
canvas.height = viewport.height;
canvas.width = viewport.width;
canvasContainer.appendChild(canvas);
page.render(renderContext);
}
function renderPages(pdfDoc) {
for(var num = 1; num <= pdfDoc.numPages; num++)
pdfDoc.getPage(num).then(renderPage);
}
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(renderPages);
}
Here is the HTMLin my template page:
这是我的模板页面中的HTML:
<script type="text/javascript" src="https://cdn.rawgit.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<div id="pdf-holder">
</div>
When the code runs
代码运行时
PDFJS.getDocument(url).then(renderPages);
I get a 404 Not Found error on worker.js, which makes sense because I'm following these examples and disabling worker so I shouldn't need it. Does anyone have any advice or an easy way around this that I can render a pdf in browser from a byte stream?
我在worker.js上收到 404 Not Found 错误,这是有道理的,因为我正在关注这些示例并禁用了 worker,所以我不需要它。有没有人有任何建议或简单的方法来解决这个问题,我可以从字节流在浏览器中呈现 pdf?
采纳答案by FlowPaper Team
You still need pdf.worker.js even if you have disabled it. Disabling it means that PDFJS will use faked workers for which it is also using the worker library. Just set it in the following way:
即使您已禁用它,您仍然需要 pdf.worker.js。禁用它意味着 PDFJS 将使用伪造的工作人员,它也使用工作人员库。只需按以下方式设置:
PDFJS.workerSrc = 'pdf.worker.js';