将PDF加载到fabricjs画布

时间:2019-07-14 12:10:06

标签: fabricjs pdf.js

我有一个fabricjs画布,我需要输入PDF,类似于如何加载图像。我希望在加载到画布上之前需要通过PDFjs将PDF转换为PNG吗?

    document.getElementById('imgLoader').onchange = function handleImage(e) {
    var reader = new FileReader();
    reader.onload = function (event) {
        console.log('fdsf');
        var imgObj = new Image();
        imgObj.src = event.target.result;
        imgObj.onload = function () {
            var image = new fabric.Image(imgObj);
            image.set({
                left: 320,
                top: 5,
            });
            canvas.add(image);
        }
    }
    reader.readAsDataURL(e.target.files[0]);
}

我只是不确定该怎么做。

1 个答案:

答案 0 :(得分:1)

为解决这个问题,我用PDFjs将PDF转换为PNG并存储了toDataURL,然后检索了PNG图像fromURL并设置为背景。

document.querySelector("#pdf-upload").addEventListener("change", function(e) {
  var file = e.target.files[0]
  if (file.type != "application/pdf") {
    console.error(file.name, "is not a pdf file.")
    return
  }

  var fileReader = new FileReader();

  fileReader.onload = function() {
    var typedarray = new Uint8Array(this.result);

    PDFJS.getDocument(typedarray).then(function(pdf) {
      // you can now use *pdf* here
      console.log("the pdf has ", pdf.numPages, "page(s).")
      pdf.getPage(pdf.numPages).then(function(page) {
        // you can now use *page* here
        var viewport = page.getViewport(2.0);
        var canvasEl = document.querySelector("canvas")
        canvasEl.height = viewport.height;
        canvasEl.width = viewport.width;

        page.render({
          canvasContext: canvasEl.getContext('2d'),
          viewport: viewport
        }).then(function() {

          var bg = canvasEl.toDataURL("image/png");

          fabric.Image.fromURL(bg, function(img) {
            img.scaleToHeight(1123);
            canvas.setHeight(1123);
            canvas.setWidth(1588);
            canvas.setBackgroundImage(img);
          });
          canvas.renderAll();
        });
      });

    });
  };
  fileReader.readAsArrayBuffer(file);
});
<head>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/fabric.js/1.6.3/fabric.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/pdf.js/1.8.349/pdf.min.js"></script>
</head>

<body>
  <span style="font-size: 14px"><b>Load PDF</b></span>
  <input id="pdf-upload" type="file">

  <canvas id="pdfcanvas"></canvas>
</body>