Open podeig opened 4 years ago
some question
Hi,
I found the solution:
// Package for getting dimentions of an image
const sizeOf = require('image-size');
...
const images = [];
const promises = [];
poem.lines.forEach((line, k) => {
if (line.type && line.type === 'image') {
// Last after . -> .jpg, .png and so on
const ext = line.imageUrl.substr(line.imageUrl.lastIndexOf('.'));
images.push({
id: line.id,
file: line.id + ext
});
promises.push(download_image(line.imageUrl, line.id + ext));
}
});
// here you get array with all the images downloaded
await Promise.all(promises);
// Images are downloaded
// then insert to the document
if (line.type && line.type === 'image') {
const file = images.find(i => i.id === line.id).file;
var dimensions = sizeOf(file);
const ratio = dimensions.width / imageMaxWidth;
pObj = docx.createP();
pObj.options.align = 'center';
pObj.addImage(file, { cx: imageMaxWidth, cy: dimensions.height / ratio });
pObj = docx.createP();
}
...
// This function fetch images
const download_image = (url, image_path) =>
axios({
url,
responseType: 'stream',
}).then(
response =>
new Promise((resolve, reject) => {
response.data
.pipe(fs.createWriteStream(image_path))
.on('finish', () => resolve())
.on('error', e => reject(e));
}),
);
It is just fragments of my code, but I think you can get what you need for downloading and inserting of images :-)
I am tring to add image by URL, f.eks:
pObj.addImage("https://www.site.com/image.jpg");
It does not work. Is it supported? How can I add external images?