schoero / swissqrbill

Swiss QR Bill generation in Node.js and browsers
MIT License
155 stars 29 forks source link

How to directly access pdf stream instead of writing file #397

Closed fionues closed 8 months ago

fionues commented 1 year ago

I have a question. I need to generate bills and send them per email. I dont want to save the files on my server.

With nodemailer and pdfkit i can achieve this like this:

const doc = new pdfkit();

transport.sendMail({
  from: '...',
  to: '...',
  subject: '...',
  text: '...',
  attachments: [{
    filename: 'attachment.pdf',
    content: doc,
  }],
});

A pdfkit instance is a stream, and can simply be passed to nodemailer.

With a qrbill instance this does not work, even though it extends from pdfkit. (which extends from stream). I did a workaround and achieved this like so:

const dummyStream = new Writable({
    write(chunk, controller) {},
  })
const doc = new PDF(billData, dummyStream, {autoGenerate: false, size: 'A4'})

// create invoice pdf
doc.end()

transport.sendMail({
  from: '...',
  to: '...',
  subject: '...',
  text: '...',
  attachments: [{
    filename: 'attachment.pdf',
    content: await buffer(doc),
  }],
});

I just wonder if there is an easier/better way?

schoero commented 1 year ago

Thank you for creating this issue. I wasn't aware of this. So no, there is currently no other way of doing this. But I am working on a refactoring of this module and I will keep this in mind.

schoero commented 8 months ago

With SwissQRBill v4 this is now possible.

Example:


const data = {
  amount: 1994.75,
  creditor: {
    account: "CH44 3199 9123 0008 8901 2",
    address: "Musterstrasse",
    buildingNumber: 7,
    city: "Musterstadt",
    country: "CH",
    name: "SwissQRBill",
    zip: 1234
  },
  currency: "CHF",
  debtor: {
    address: "Musterstrasse",
    buildingNumber: 1,
    city: "Musterstadt",
    country: "CH",
    name: "Peter Muster",
    zip: 1234
  },
  reference: "21 00000 00003 13947 14300 09017"
};

const pdf = new PDFDocument();
const qrBill = new SwissQRBill(data);

qrBill.attachTo(pdf);
pdf.end();

transport.sendMail({
  attachments: [{
    content: await buffer(pdf),
    filename: "attachment.pdf"
  }],
  from: "...",
  subject: "...",
  text: "...",
  to: "..."
});