PDF.JS: Render PDF using an ArrayBuffer or Blob instead of URL

后端 未结 1 821
夕颜
夕颜 2020-12-09 20:03

I know of a similar question to this one: Pdf.js: rendering a pdf file using a base64 file source instead of url. That question was awesomely answered by Codetoffel but my q

相关标签:
1条回答
  • 2020-12-09 20:30

    You're not passing the response data to PDF.js, but an instance of the resource:

    var myPdf = myService.$getPdf({ Id: 123 });
    myPdf.$promise.then(function() {
        var docInitParams = {
            data: myPdf
    

    You haven't shown your code for $getPdf, but I guess that it is something equivalent to

    var myService = $resource('/foo', {}, {$getPdf:{responseType: 'arraybuffer'}});
    var myPdf = myService.$getPdf();
    

    By default, an AngularJS $resource treats the response as an object (deserialized from JSON) and copies any properties from the object to the resource instance (myPdf in the previous snippet).

    Obviously, since your response is an array buffer (or Blob, typed array or whatever), this is not going to work. One of the ways to get the desired response is to use transformResponse to wrap the response object in an object:

    var myService = $resource('/foo', {}, {
        $getPdf: {
            responseType: 'arraybuffer',
            transformResponse: function(data, headersGetter) {
                // Stores the ArrayBuffer object in a property called "data"
                return { data : data };
            }
        }
    });
    var myPdf = myService.$getPdf();
    myPdf.$promise.then(function() {
        var docInitParams = {
            data: myPdf.data
        };
    
        PDFJS.getDocument(docInitParams).then(function (pdf) {
            // ...
        });
    });
    

    Or simply the following (avoided unnecessary local variables):

    myService.$getPdf().$promise.then(function(myPdf) {
        PDFJS.getDocument({
            data: myPdf.data
        }).then(function (pdf) {
            // ...
        });
    });
    
    0 讨论(0)
提交回复
热议问题