使用带有AngularJS的html2pdf创建和下载PDF

时间:2016-12-09 15:08:09

标签: angularjs html2pdf

我正在为Web应用程序做后端,并且我正在使用html2pdf类(http://html2pdf.fr/)创建一个包含数据库中现有数据的PDF文件。

我的前端开发人员说他不能使用" stream"我使用角度提供API。我使用 - >输出(' D')方法来提供文件。

有人知道如何使用此类下载带有angularjs的PDF文件吗?

1 个答案:

答案 0 :(得分:1)

要下载PDF文件的数据,请使用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;
    });
  };
});

将数据转换为blob网址并使用下载按钮:

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

xd-href指令

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

DEMO on PLNKR下载http://demo.html2pdf.fr/examples/exemple07.php