Ziv-Barber / officegen

Standalone Office Open XML files (Microsoft Office 2007 and later) generator for Word (docx), PowerPoint (pptx) and Excell (xlsx) in javascript. The output is a stream.
MIT License
2.66k stars 471 forks source link

How to add external image by URL? #341

Open podeig opened 4 years ago

podeig commented 4 years ago

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?

wuxiaolan91 commented 4 years ago

some question

podeig commented 4 years ago

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 :-)

sagardeepansh commented 1 month ago

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?

Is there any way without downloading that images?