Jonha
Jonha

Reputation: 13

Insert firestore uploaded image in jsPDF

I have an uploaded image in Firestore and I am able to get download URL in my Angular application.

Download URL is like:

https://firebasestorage.googleapis.com/v0/b/appname.appspot.com/o/clinica%2Flogo?alt=media&token=123456789-2bf7-4711-ba17-d12345678

When I click on it web browser shows the image, but how could I include it in jsPDF document? I tried to do:

const doc = new jsPDF('portrait', 'mm', 'a4');
doc.addImage(this.downloadURL, 'JPEG', 30, 20);

But I get this error:

ERROR Error: Supplied Data is not a valid base64-String jsPDF.convertStringToImageData 
at Object.x.convertStringToImageData (jspdf.min.js:50)
at Object.x.addImage

Thanks!

Upvotes: 0

Views: 1279

Answers (2)

Frank van Puffelen
Frank van Puffelen

Reputation: 598668

According to the jsPDF documentation the addImage method accepts its imageData in these formats:

imageData: string | HTMLImageElement | HTMLCanvasElement | Uint8Array

imageData as base64 encoded DataUrl or Image-HTMLElement or Canvas-HTMLElement

So you can't simply pass in a URL that points to an image.

A simple way to get the image into a support format is by creating a img element in code:

var img = document.createElement('img');
img.src = this.downloadURL;
doc.addImage(img, 'JPEG', 30, 20);

Upvotes: 1

Gustavo Alarcón
Gustavo Alarcón

Reputation: 11

I get this working doing the following steps:

First, follow this solution Set CORS in your firebase Storage

I used the following cors.json

[
 {
   "origin": [
       "*"
   ],
   "method": [
       "GET"
   ],
   "maxAgeSeconds": 3600
 }
]

Then just use the following code to read your url and add it to your pdf:

async generatePDF(your_image_url: string) {
  let imageLoaded: HTMLImageElement = await this.getDataUri(your_image_url);
  let pdf = new jsPDF('p', 'pt', 'a4');
  pdf.addImage(imageLoaded, 0, 0, 250, 250);
  pdf.save('test.pdf');
}



async getDataUri(url): Promise<HTMLImageElement> {
    return new Promise(resolve => {
      var image = new Image();

      image.onload = () => {
        resolve(image);
      };

      image.src = url;
    })
 }

Hope this helps you, I was searching alot for this solution, so shared as much as you can.

Regards.

Upvotes: 0

Related Questions