Pdf.js and viewer.js. Pass a stream or blob to the viewer

前端 未结 5 1605
一个人的身影
一个人的身影 2020-11-27 15:40

I\'m having troubles in finding a solution for this: I retrieve a PDF blob from a SQL filestream field using Javascript in this way (it\'s a lightswitch project)

<         


        
5条回答
  •  日久生厌
    2020-11-27 16:20

    I'm using PDFJS.version = '1.0.1040'; PDFJS.build = '997096f';

    The code that worked for me to get base64 pdf data loaded was this:

    function (base64Data) {
      var pdfData = base64ToUint8Array(base64Data);
      PDFJS.getDocument(pdfData).then(function (pdf) {
        pdf.getPage(1).then(function (page) {
          var scale = 1;
          var viewport = page.getViewport(scale);
          var canvas = document.getElementById('myCanvas');
          var context = canvas.getContext('2d');
          canvas.height = viewport.height;
          canvas.width = viewport.width;
          page.render({ canvasContext: context, viewport: viewport });
        });
      });
    
      function base64ToUint8Array(base64) {
        var raw = atob(base64);
        var uint8Array = new Uint8Array(raw.length);
        for (var i = 0; i < raw.length; i++) {
          uint8Array[i] = raw.charCodeAt(i);
        }
        return uint8Array;
      }
    }
    

    This function could be the success function of an api call promise. What I'm doing here is rendering the pdf onto a canvas element myCanvas.

    
    

    This shows the first page of the pdf but has no functionality. I can see why the viewer is desirable. If I get this hooked up to the viewer (viewer.html / viewer.js) I will edit my answer.

    EDIT: How to hook up the viewer

    1 In bower.json, add "pdfjs-viewer": "1.0.1040"

    2 Html:

    
    

    3 Change the stupid default document in the viewer.js file:

    var DEFAULT_URL = '';

    4 Controller:

    var pdfjsframe = document.getElementById('pdfViewer');
    pdfjsframe.onload = function() {
      LoadPdfDocument();
    };
    
    $scope.myApiCallThatReturnsBase64PdfData.then(
      function(base64Data) {
        $scope.base64Data = base64Data;
        LoadPdfDocument();
      },
      function(failure) {
    
        //NotificationService.error(failure.Message);
    
      });
    
    function LoadPdfDocument() {
      if ($scope.PdfDocumentLoaded)
        return;
      if (!$scope.base64Data)
        return;
    
      var pdfData = base64ToUint8Array($scope.base64Data);
      pdfjsframe.contentWindow.PDFViewerApplication.open(pdfData);
    
      $scope.PdfDocumentLoaded = true;
    }
    
    function base64ToUint8Array(base64) {
      var raw = atob(base64);
      var uint8Array = new Uint8Array(raw.length);
      for (var i = 0; i < raw.length; i++) {
        uint8Array[i] = raw.charCodeAt(i);
      }
      return uint8Array;
    }
    

提交回复
热议问题