使用PDF.js生成PDF文件的缩略图

13

我想使用 PDF.js 从一个 pdf 文件中生成缩略图,但它不像其他只有一个文件的 js 库,需要在项目中引入 js 的所有必需内容仅仅是写:

<script src="any.js"></script>

我怎样在我的项目中使用PDF.js?我在后端使用PHP。

如何在我的PHP项目中使用PDF.js?


你尝试过这个解决方案吗? https://dev59.com/6nRB5IYBdhLWcg3w6bYE - Antoine Bourlart
一个使用PDF.js创建缩略图的Angular 10服务示例。https://dev59.com/ZFUL5IYBdhLWcg3w88Ao#63982049 - ttugates
2个回答

26
根据helloworld示例:

function makeThumb(page) {
  // draw page to fit into 96x96 canvas
  var vp = page.getViewport(1);
  var canvas = document.createElement("canvas");
  canvas.width = canvas.height = 96;
  var scale = Math.min(canvas.width / vp.width, canvas.height / vp.height);
  return page.render({canvasContext: canvas.getContext("2d"), viewport: page.getViewport(scale)}).promise.then(function () {
    return canvas;
  });
}

pdfjsLib.getDocument("https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf").promise.then(function (doc) {
  var pages = []; while (pages.length < doc.numPages) pages.push(pages.length + 1);
  return Promise.all(pages.map(function (num) {
    // create a div for each page and build a small canvas for it
    var div = document.createElement("div");
    document.body.appendChild(div);
    return doc.getPage(num).then(makeThumb)
      .then(function (canvas) {
        div.appendChild(canvas);
    });
  }));
}).catch(console.error);
<script src="//npmcdn.com/pdfjs-dist/build/pdf.js"></script>


谢谢,但我已经尝试了另一个URL(http://www.shellgreenier.com/MGreenier-Resume.pdf),并遇到了这个问题:请求的资源上没有“Access-Control-Allow-Origin”头。因此,不允许来自“http://localhost”的访问。 - Andre Alvim
1
cdn.mozilla.net已启用CORS -- 您不能要求随机URL为不同的网站提供数据。下载PDF和您的网站上的代码以玩转脚本。另请参见https://github.com/mozilla/pdf.js/wiki/Frequently-Asked-Questions#faq-xhr。 - async5
您能帮我解决这个问题吗?链接为:https://stackoverflow.com/questions/49644356/image-appending-is-not-working-for-thumbnail-in-pdf-js - Vishnu
2
@async5:代码片段错误:“message”:“未捕获的引用错误:PDFJS未定义”,您认为您能修改您的答案/可运行的代码片段吗?提前感谢您。 - Basj

5

我明白了,比例尺不是一个参数。参数是一个具有需要设置比例尺字段的对象。

function makeThumb(page) {
    // draw page to fit into 96x96 canvas
    var vp = page.getViewport({ scale: 1, });
    var canvas = document.createElement("canvas");
    var scalesize = 1;
    canvas.width = vp.width * scalesize;
    canvas.height = vp.height * scalesize;
    var scale = Math.min(canvas.width / vp.width, canvas.height / vp.height);
    console.log(vp.width, vp.height, scale);
    return page.render({ canvasContext: canvas.getContext("2d"), viewport: page.getViewport({ scale: scale }) }).promise.then(function () {
        return canvas; 
    });
}

这不是一个独立的答案。选项作为一个对象的改变是在2.1版本中引入的,你所需要做的就是“编辑”async5的答案。你甚至没有提及他们的原始答案或者你的答案应该是对他们的修复。 - Gust van de Wal

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接