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:
- The data
In any format is fine. I see there is agetBase64ImageSrcmethod - this will do. - The filename
No filename is fine - I can see the API does not have it - I can build it with the alt text or justimage_{n}where {n} is the image index, but I cannot see a way to get the extension - is this in the data as adata:image/jpeg;blahblah??? I don't know the docs don't have this level of information.
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:
- Strings.isNullOrEmpty
Return true if string is null or empty, otherwise false - Path.toFriendlyUrl
Returns the string with spaces converted to-and some other improvements
Is my current approach correct?
Please check out this sample that is doing what you need. I think you are in the right track.
Here is some sample code:
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.