0

I am trying to replace the token in the word document with the image i have in base64. But i get an unhelpful error Error Code

Here is the function thats not working

async function insertImage(token, image) {
  console.log("adding image");

  await Word.run(async (context) => {
    const results = context.document.body.search(token);
    await context.sync();
    results.load();
    await context.sync();
    console.log(results.items);

    for (let i = 0; i < results.items.length; i++) {
      const pasteMeHere = results.items[i];
      pasteMeHere.insertInlinePictureFromBase64(image, "Replace");
      pasteMeHere.delete();
      
    }
    await context.sync();
  });
}

I have tried different images, one of which from the ms script lab repo which i confirmed working. I have also tried different locations including using the paragraphs.getLast() function.

Skaven
  • 1
  • 1
  • Before you do anything else, rewrite the function so that you are not calling `context.sync` in a loop. This can cause problems with timing and other issues. See https://learn.microsoft.com/office/dev/add-ins/concepts/correlated-objects-pattern – Rick Kirkham Feb 11 '23 at 20:13
  • Thanks for that, im new to using OfficeJs, i made the change and everything works the same so thats good. It didn't fix the problem though of course. – Skaven Feb 12 '23 at 12:58
  • Please update your question to show the new code. – Rick Kirkham Feb 12 '23 at 18:25
  • Sorry, new to asking questions on here wasn't aware of the etiquette to update the original post. – Skaven Feb 15 '23 at 18:43
  • Two suggestions: (1) does it work if you replace the `image` parameter with some text in the call of `insertInlinePictureFromBase64`? Is the token replace with the text or do you get the error? (2) Can you reproduce the error in Script Lab? – Rick Kirkham Feb 15 '23 at 18:50
  • Sorry for the delay in updating you, the issue was the image I was using had a string at the beginning. I found the answer by following your suggestions. I did try different images including the one in script lab prior to posting but i must have missed something when copying it. Thanks for your help! – Skaven Mar 21 '23 at 14:27

0 Answers0