Search code examples
angularjshtml2pdf

Create and download PDF using html2pdf with AngularJS


I'm doing the backend for a web application and I'm using the html2pdf class (http://html2pdf.fr/) to create a PDF file with existing data out of my database.

My frontend developer says he can not use that "stream" i deliver with the API using angular. I use the ->Output('D') method to provide the file.

Does anybody know how to use this class to download PDF files with angularjs?


Solution

  • To download the data for a PDF file, use responseType: "arraybuffer":

      var config = { responseType: "arraybuffer" };
    
      vm.fetch = function() {
        $http.get(url, config).then(function(response) {
          vm.result = "SUCCESS";
          vm.length = response.data.byteLength + " bytes";
          var blob = new Blob([response.data],
                              {type: "application/pdf"});
          vm.data = URL.createObjectURL(blob);
        }).catch(function(response) {
          vm.result = "ERROR "+response.status;
        });
      };
    });
    

    Convert the data to blob url and use a download button:

      <a download="{{name}}.pdf" xd-href="data">
          <button>Download data</button>
      </a>
    

    xd-href Directive

    app.module("myApp").directive("xdHref", function() {
      return function linkFn (scope, elem, attrs) {
         scope.$watch(attrs.xdHref, function(newVal) {
           newVal && elem.attr("href", newVal);
         });
      };
    });
    

    The DEMO on PLNKR downloads http://demo.html2pdf.fr/examples/exemple07.php