Load PDF into fabricjs canvas

别来无恙 提交于 2021-01-01 03:32:33

问题


I have a fabricjs canvas that I need to input a PDF, similar to how images are loaded. I expect that I'd need to convert the PDF to a PNG via PDFjs before loading onto canvas?

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

I'm just not sure how to go about it.


回答1:


To solve this I converted the PDF to PNG with PDF.js and stored toDataURL, then retreived the PNG image fromURL and set as background.

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>


来源:https://stackoverflow.com/questions/57027267/load-pdf-into-fabricjs-canvas

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!