【问题标题】:Generating thumbnail of a pdf using PDF.js使用 PDF.js 生成 pdf 的缩略图
【发布时间】:2017-11-16 18:31:31
【问题描述】:

我想使用 PDF.js 从 pdf 文件生成缩略图,但它不像其他 js 只有一个文件,并且在项目中包含 js 所需要的只是编写:

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

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

【问题讨论】:

标签: javascript php pdfjs


【解决方案1】:

基于helloworld example:

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);
&lt;script src="//npmcdn.com/pdfjs-dist/build/pdf.js"&gt;&lt;/script&gt;

【讨论】:

  • 谢谢,但我尝试使用另一个 URL (shellgreenier.com/MGreenier-Resume.pdf) 并遇到了这个问题:请求的资源上没有“Access-Control-Allow-Origin”标头。因此不允许访问 Origin 'localhost'。
  • cdn.mozilla.net 已启用 CORS——您不能要求随机 URL 为不同的网站提供数据。在您的网站上下载 PDF 和代码以使用该脚本。另见github.com/mozilla/pdf.js/wiki/…
  • stackoverflow.com/questions/49644356/… 你能帮我解决这个问题吗
  • @async5: 代码 sn-p 错误:"message": "Uncaught ReferenceError: PDFJS is not defined", 你认为你可以修改你的答案/可运行的 sn-p 吗?提前谢谢你。
【解决方案2】:

我想通了,比例不是参数。参数是需要设置的具有比例域的对象。

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; 
    });
}

【讨论】:

    猜你喜欢
    • 2018-01-08
    • 1970-01-01
    • 2011-11-28
    • 1970-01-01
    • 2012-04-22
    • 2016-12-14
    • 2011-04-27
    • 2010-09-16
    • 2016-05-03
    相关资源
    最近更新 更多