typescriptms-wordoffice-jsword-addinsapps-for-office

Get all images in a Word document


I am trying to get a collection of the images in a Word document. The documentation of this page: https://dev.office.com/reference/add-ins/word/inlinepicture literally is a cut'n'paste for the examples, and does not show actually how to get the images - only the first one.

I need the following things per image:

I have the following code so far but am really unsure if it will work:

Word.run(

async (context) =>
{
    // Create a proxy object for the pictures.
    const allPictures = context.document.body.inlinePictures;

    // Queue a command to load the pictures
    context.load(allPictures);

    // Synchronize the document state by executing the queued commands,
    // and return a promise to indicate task completion.
    return context.sync().then(() => allPictures);
})
.then((allPictures) =>
{
    const images: IFileData[] = [];
    let picture: Word.InlinePicture | undefined;
    let imageCount = 0;

    while (undefined !== (picture = allPictures.items.pop()))
    {
        const data = picture.getBase64ImageSrc();
        const extension = ""; // TODO: no idea how to find this
        const filename =
            (
                Strings.isNullOrEmpty(picture.altTextTitle)
                    ? `image_${imageCount++}`
                    : Path.toFriendlyUrl(picture.altTextTitle)
            )

        images.push({
            filename: filename + extension,
            data: data
        });
    }

    resolve(images);
})
.catch((e) => reject(e));

I am using some custom helpers here they do the following:


Is my current approach correct?


Solution

  • Please check out this sample that is doing what you need. I think you are in the right track.

    Here is some sample code:

    async function run() {
        await Word.run(async (context) => {
    
            let myImages = context.document.body.inlinePictures;
            myImages.load("imageFormat");
    
            await context.sync();
            
            if (myImages.items.length >0)
            console.log(myImages.items[0].imageFormat);
            else
            console.log("no image found.")
    
    
        });
    }

    Note that we have an imageFormat property, the problem is that we have it in on the preview CDN. (use https://appsforoffice.microsoft.com/lib/beta/hosted/office.js). we don't have the image name, but you can use alt text to store it.