natergj / excel4node

Node module to allow for easy Excel file creation
MIT License
1.38k stars 215 forks source link

File size is increasing by using the same image multiple times #302

Open HTMHell opened 4 years ago

HTMHell commented 4 years ago

I want to use the same image multiple times in the excel document. However, the file size of the excel is increasing for every image added (it's the same image).

Every time I add the image I use:

worksheet.addImage({
    path: './myImage.jpg',
    type: 'picture',
    position: {
        type: 'twoCellAnchor',
        from: {
            ...
        },
        to: {
            ...
        },
    },
});

I found this issue: https://github.com/natergj/excel4node/issues/58 opened by @dgofman which claims he fixed this issue. However the code looks different, probably old syntax.

Is there any way of doing that?

Newbie012 commented 4 years ago

This can be achieved by allowing to modify rId. Since id and rId are the same, I couldn't reference multiple RelationShip[Id] to the same target.

What I did:

  1. Forked this libray and allow setting rId to Picture.
  2. Instead of using addImage, I manually added to Media and Drawing with condition.

See example:

    static i = 1;

    private addMedia(opts) {
        opts = opts ? opts : {};
        const mediaIndex = this.workbook.mediaCollection.items.indexOf(opts.path);
        const mediaID = mediaIndex !== -1
            ? mediaIndex + 1
            : this.workbook.mediaCollection.add(opts.path);

        const newImage = this.addDrawing(opts, mediaID);
        newImage.id = mediaID;

        return newImage;
    }

    private addDrawing(opts, mediaID) {
        switch (opts.type) {
            case 'picture':
                const newPic = new Picture(opts);
                newPic.id = mediaID;
                newPic.rId = 'rId' + WorksheetPhotoCell.i++; // you should add `set rId` in the source code.
                this.worksheet.drawingCollection.drawings.push(newPic);
                return newPic;

            default:
                throw new TypeError('this option is not yet supported');
        }
    }