>

하고 싶다

  • 현재 페이지 pdf를 보유한 각 캔버스에 정확한 모양 추가
  • 각 페이지의 모양은 n 번이 될 수 있습니다.

문제

  • 왜 내 도형이 PDF를 대체합니까?
  • 현재 페이지를 보유한 각 캔버스에 rect 모양을 추가 할 수 없습니다 pdf

아래는 내가 시도한 것입니다. https://jsfiddle.net/goteL3hn/

코드 :

// Adding a rectangle
jQuery(function($) {
    $("#addRectangle").click(function() {
    fCanvas = new fabric.Canvas("the-canvas", {
        selection: false
    });
        fCanvas.add(new fabric.Rect({
            left: 100,
            top: 100,
            fill: 'red',
            width: 20,
            height: 20
        }));
    });
});

  • 답변 # 1

    캔버스 the-canvas 에서 PDF를 렌더링하고있었습니다  요소이지만 rect 객체를 추가하는 동안 동일한 요소를 사용하여 fabricjs 캔버스 the-canvas 를 만들었습니다.  요소를 제거하여 캔버스를 지우고 rect 객체 만 그렸습니다.

    fabricjs 캔버스 상단 컨텍스트에서 pdf 페이지 데이터를 렌더링해야하며 이미지가로드 된 후 하위 캔버스 요소의 이미지 객체로 추가하십시오.

    데모

    // If absolute URL from the remote server is provided, configure the CORS
    // header on that server.
    var url = 'https://raw.githubusercontent.com/mozilla/pdf.js/ba2edeae/web/compressed.tracemonkey-pldi-09.pdf';
    // Loaded via <script> tag, create shortcut to access PDF.js exports.
    var pdfjsLib = window['pdfjs-dist/build/pdf'];
    // The workerSrc property shall be specified.
    pdfjsLib.GlobalWorkerOptions.workerSrc = '//mozilla.github.io/pdf.js/build/pdf.worker.js';
    var pdfDoc = null,
      pageNum = 1,
      prevPageNum = 1,
      pageRendering = false,
      pageNumPending = null,
      scale = 0.8,
      fCanvas = new fabric.Canvas("the-canvas", {
        selection: false
      });
    /**
     * Get page info from document, resize canvas accordingly, and render page.
     * @param num Page number.
     */
    var pageHistory = {};
    function renderPage(num) {
      pageHistory[prevPageNum] = fCanvas.toJSON();
      var jsonData = pageHistory[num];
      fCanvas.discardActiveObject(); //if you have any object selected, then it will deselect
      if (jsonData) {
        fCanvas.loadFromJSON(jsonData, function() {
          renderPdfData(num);
          fCanvas.renderAll.bind(fCanvas)
        });
      } else {
        pageHistory[num] = fCanvas.toJSON();
        fCanvas.clear();
        renderPdfData(num);
      }
    }
    function renderPdfData(num) {
      pageRendering = true;
      // Using promise to fetch the page
      pdfDoc.getPage(num).then(function(page) {
        var viewport = page.getViewport(scale);
        fCanvas.setDimensions({
          height: viewport.height,
          width: viewport.width
        })
        // Render PDF page into canvas context, use fabricjs top canvas element context
        var renderContext = {
          canvasContext: fCanvas.contextTop,
          viewport: viewport
        };
        var renderTask = page.render(renderContext);
        // Wait for rendering to finish
        renderTask.promise.then(function() {
          pageRendering = false;
          var imageData = fCanvas.upperCanvasEl.toDataURL(); //create an image from top context and put it in lower canvas element
          fabric.Image.fromURL(imageData, function(img) {
            img.set({
              left: 0,
              top: 0,
              evented: false,
              selectable: false,
              excludeFromExport:true
            });
            fCanvas.add(img).sendToBack(img);
            fCanvas.clearContext(fCanvas.contextTop);
            if (pageNumPending !== null) {
              // New page rendering is pending
              renderPage(pageNumPending);
              pageNumPending = null;
            }
          });
        });
      });
      // Update page counters
      document.getElementById('page_num').textContent = num;
    }
    /**
     * If another page rendering in progress, waits until the rendering is
     * finised. Otherwise, executes rendering immediately.
     */
    function queueRenderPage(num) {
      if (pageRendering) {
        pageNumPending = num;
      } else {
        renderPage(num);
      }
    }
    /**
     * Displays previous page.
     */
    function onPrevPage() {
      if (pageNum <= 1) {
        return;
      }
      prevPageNum = pageNum;
      pageNum--;
      queueRenderPage(pageNum);
    }
    document.getElementById('prev').addEventListener('click', onPrevPage);
    /**
     * Displays next page.
     */
    function onNextPage() {
      if (pageNum >= pdfDoc.numPages) {
        return;
      }
      prevPageNum = pageNum;
      pageNum++;
      queueRenderPage(pageNum);
    }
    document.getElementById('next').addEventListener('click', onNextPage);
    /**
     * Asynchronously downloads PDF.
     */
    pdfjsLib.getDocument(url).then(function(pdfDoc_) {
      pdfDoc = pdfDoc_;
      document.getElementById('page_count').textContent = pdfDoc.numPages;
      // Initial/first page rendering
      renderPage(pageNum);
    });
    // Adding a rectangle
    jQuery(function($) {
      $("#addRectangle").click(function() {
        fCanvas.add(new fabric.Rect({
          left: 100,
          top: 100,
          fill: 'red',
          width: 20,
          height: 20
        }));
      });
    });
    
    

    #the-canvas {
      border:1px solid black;
    }
    
    

    <script src="//mozilla.github.io/pdf.js/build/pdf.js"></script>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
    <script src="https://rawgit.com/kangax/fabric.js/master/dist/fabric.js"></script>
    <h1>PDF.js Previous/Next example</h1>
    <div>
      <input type="button" id="addRectangle" value="Add Signature">
      <button id="prev">Previous</button>
      <button id="next">Next</button>
      &nbsp; &nbsp;
      <span>Page: <span id="page_num"></span> / <span id="page_count"></span></span>
    </div>
    <canvas id="the-canvas"></canvas>
    
    

  • 이전 python : YouTube 믹스 재생 목록을 얻는 방법?
  • 다음 adafruit - Python/Micropython에서 ADS1114와 함께 ADS1x15 라이브러리 사용