pdf格式到img/canvas,只适用于FireFox



我使用PDF .js库从客户端的PDF页面制作图像/画布。但它只能在FireFox上运行,而不能在Chrome或IE10+上运行。我环顾四周,但找不到一个好的答案或解决方案。

我读到IE或Chrome上的pdf.js需要一个web服务器,但当我在JSFiddle上尝试代码时,它仍然不起作用。

下面是一个例子:https://jsfiddle.net/aqxwsfjo/2/

var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/master/examples/helloworld/helloworld.pdf';
PDFJS.disableWorker = true;
PDFJS.getDocument(url).then(function getPdfHelloWorld(pdf) {
    pdf.getPage(1).then(function getPageHelloWorld(page) {
        var scale = 1.5;
        var viewport = page.getViewport(scale);
        var canvas = document.getElementById('the-canvas');
        var context = canvas.getContext('2d');
        canvas.height = viewport.height;
        canvas.width = viewport.width;
        page.render({canvasContext: context, viewport: viewport})
    });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/master/web/compatibility.js"></script>
<script src="https://raw.githubusercontent.com/mozilla/pdf.js/gh-pages/build/pdf.js"></script>
<canvas id="the-canvas" style="border:1px solid black"></canvas>

似乎GitHub在返回Content-Type: text/plain原始文件时添加了标题X-Content-Type-Options: nosniff。参见相关问题:链接并执行托管在GitHub上的外部JavaScript文件

如相关问题所述,解决方案是将https://raw.githubusercontent.com替换为https://rawgit.com/,从而返回具有正确内容类型的文件。

这里是更新的提琴:https://jsfiddle.net/aqxwsfjo/4/

最新更新