UberSwyser
UberSwyser

Reputation: 69

Generating pdf in Angular 2

Me again with another Angular 2 question.

We are trying to generate a PDF file from a html source. I searched and searched trying to find an Angular 2 wrapper for the jsPdf or makePdf libraries, but I can't find any. Is there something I am missing? Is there a pure javascript way and is that good practice? Hope you guys can help.

Thanks in advance.

Francois

Upvotes: 5

Views: 6574

Answers (3)

Srikanth Reddy
Srikanth Reddy

Reputation: 1

HTML code:

  <button type="button" (click)="downloadPdf()" 
          class="button">download</button>

Component.ts:

  downloadPdf(){
  this.authService.downloadPdf().subscribe(data => {
  this.partnerDetails = data
  } ); }

routes.js:

router.get('/downloadPdf',partnerCntrl.downloadPdf);

partnercntrl:

module.exports.downloadPdf = function (req, res) {
     var fs = require('fs');
     var pdf = require('html-pdf');
     var html = fs.readFileSync('./test/businesscard.html', 'utf8');
     var options = { format: 'Letter' };
     pdf.create(html, options).toFile('./businesscard.pdf', function(err, res) {
     if (err) return console.log(err);
     console.log(res); // { filename: '/app/businesscard.pdf' }
     });

Upvotes: 0

Mark Redman
Mark Redman

Reputation: 24515

PDF is a complex file format, there may be some pdf parsers/generators built with js, but they will be limited & slow, your best bet is to do something server side.

Upvotes: 1

stijn.aerts
stijn.aerts

Reputation: 6206

I was searching for the same thing, some weeks ago. I decided to do the generating on server-side (Node.js in my case). However you can do it on client-side, with jsPDF, like you mentioned.

Don't need a wrapper, just include the script and then access jsPDF through the window object. Wrapper will make it easier to test though.

I don't remember exactly but I thought it was something like this:

var doc = new window.jsPDF();

Upvotes: 2

Related Questions