schoero / swissqrbill

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

Error when trying to load image via browser #331

Closed lucbu01 closed 3 years ago

lucbu01 commented 3 years ago

I try to generate a pdf with a image that can be selected over a HTML file input and I get an error in the browser:

Error:

ERROR TypeError: fs.readFileSync is not a function
    at Function.open (browser.js:11586)
    at PDF.openImage (browser.js:11729)
    at PDF.image (browser.js:11630)
    at AppComponent.addDebtor (app.component.ts:140)
    at app.component.ts:97
    at Array.forEach (<anonymous>)
    at AppComponent.generatePdf (app.component.ts:96)
    at FileReader.reader.onload (app.component.ts:61)
    at ZoneDelegate.invoke (zone-evergreen.js:372)
    at Object.onInvoke (core.js:28577)

Code:

const stream = new SwissQRBill.BlobStream();

const pdf = new SwissQRBill.PDF(data, {
  autoGenerate: false,
  size: 'A4',
});

pdf.image(fileNameFromHtmlFileInput, 20, 20, {
  align: 'right',
  fit: [ 20, 20]
});

pdf.end();

pdf.on("finish", () => {
  const iframe = document.getElementById("iframe") as HTMLIFrameElement;
  if(iframe){
    iframe.src = stream.toBlobURL("application/pdf");
  }
  console.log("PDF has been successfully created.");
});
schoero commented 3 years ago

If you want to insert an image in a browser you will have to pass a base64-encoded image rather than the path. You can use the fileReader API for this.

lucbu01 commented 3 years ago

Oh, stupid me 😅. Thank you very much. Works fine!