生成一个使用Angular JS下载的pdf

时间:2015-08-21 11:40:58

标签: javascript angularjs pdf

我有一个使用Angular JS构建的应用程序,我想有一个生成并下载div区域的pdf的按钮(这只是绑定数据)

This is close to what I would like, but it does not outline how this would be executed

任何帮助都会很棒,我也尝试过jsPDF,但这对Angular不起作用。

1 个答案:

答案 0 :(得分:0)

我让jsPDF在一个有角度的应用程序中工作得很好:

angular.module('YourApp')
  .factory('InvoiceGenerator', function() {
    return {
      makeInvoice: function(subject, reference, from, to, /* whatever you need to print out... */ ) {
        getLogo(window.location.origin+'/images/bot-objects-full-logo.png',
          function(imgData) {
            var doc = new window.jsPDF();
            var x=0, y=0;

            doc.addImage(imgData, 'PNG', 10, 10, 50, 15);

            doc.setFontSize(12);
            x=10;y=30;
            from.forEach(function(line) {
              doc.text(x, y, line);
              y += 5;
            });

            x=145;y=50;
            to.forEach(function(line) {
              doc.text(x, y, line);
              y += 5;
            });

            x=10;y=80; doc.text(x, y, 'Subject: '+subject);
            y+=5;      doc.text(x, y, 'Reference: '+reference);

            doc.setLineWidth(0.5);
            y=110;     doc.line(20, y, 180, y); // horizontal line

            /* do whatever you need to do with the other sutff you need to print out ... */

            doc.save('foo.pdf');
          });
       }
    }
}

然后可以在整个项目中使用该代码:

.controller('YourAppController',
   ['$scope', 'InvoiceGenerator', 
   function($scope, InvoiceGenerator)) {
    $scope.printInvoice = function(invoice) {
        InvoiceGenerator.makeInvoice('This is an invoice',
                                     'IV1234', 
                                     ['Your firm',
                                      'your street',
                                      'your city',
                                      'your country'
                                     ], 
                                     ['Your client',
                                      'his street',
                                      'his city',
                                      'his country'
                                     ],
                                     /* 'other stuff you want to printout' */
                                     )
    }
}

然后您需要做的就是根据 的需要完成它,并在任何需要的地方使用它。

所以你的断言"我也尝试了jsPDF,但这对Angular不起作用。" 错了,你可能只是有问题,所以你应该关注SO& #39;方式并展示您试图帮助我们帮助您解决问题的方法。