I want to generate a pdf with images and text, for this I'm using the jsPdf package which includes this method to add images.
addImage(imageData, format, x, y, width, height, alias, compression, rotation)
The imageData argument accepts base64 format data and this part is which I'm struggling with.
My images are not local but hosted in cloudinary and I would prefer not to download them, searching on the web I've found that if I don't want to download the image I will need:
- Fetch the image data, for this I'm using node-fetch package(fetch in the code).
- Convert the image data into a Buffer.
- Finally encode that buffer into a base64.
This is my attempt so far:
const fetchImage = async () => {
const imageUrl = <url-of-my-image>;
const response = await fetch(imageUrl, {
compress: false
});
const dataUrlPrefix = `data:${response.headers.get('content-type')};base64,`;
const body = await response.text();
const buffer = Buffer.from(body)
const imageBase64 = buffer.toString('base64');
const imageDataUrl = dataUrlPrefix+imageBase64;
doc.text("Hello world!", 10, 10);
doc.addImage(imageDataUrl, 'webp', 15, 40, 120, 120)
doc.save("a4.pdf");
}
The code runs without errors but the image is not being inserted into the pdf, it just display the "Hello World!" text but nothing else.
My guess is that I'm doing something wrong in the converting/encoding process (before I add it to jsPdf) because if I convert my image with an online converter like this one the base64 string that results is successfully decoded into an actual image when using a online base64 decoder like this one, whereas when I run the base64 output from my nodejs code i.e. the output for the imageBase64
or imageDataUrl
variables in the same base64 decoder it results in not image being decoded.