用Office-js替换一张图片

Replace a picture with Office-js

背景信息

目前正在开发一个 office-js 插件,它将用于修改文档中的内联图像。

问题

理想情况是 select 将文档中已有的特定图像替换为其他图像。现在理想我认为我可以单击图像和 运行 a var range = context.document.getSelection(); 以加载 selection,但我无法加载 selected 图像和用新图像替换它。除非我真的清除它。

代码

Word.run(function (context) {
        var range = context.document.getSelection();
        context.load(range)
        return context.sync().then(function () {           
            range.insertInlinePictureFromBase64(base64, Word.InsertLocation.replace);
            console.log('Added base64 encoded text to the beginning of the range.');
        });
    })

更新

此代码块也能够在我想要的位置插入图像,但是当我尝试添加尺寸时出现以下错误。

更新代码

function insertImageToDoc(base64, selectedContent) {
    Word.run(function (context) {

        var range = context.document.getSelection();
        var paragraphs = range.paragraphs;
        context.load(paragraphs);

        return context.sync().then(function () {

            var para = paragraphs.items[0];
            var image = para.insertInlinePictureFromBase64(base64, Word.InsertLocation.replace);
            image.width = selectedContent.ImageWidth;
            image.height = selectedContent.Imageheight;              
        });
    })
};

此代码给我的错误

您不需要删除图像。你只需要更换它。

几点建议:

  1. 对于任何给定范围,您都可以访问 inlinePictures collection,因此您的第一个指令是获取所选内容及其中的所有 inlinePictures。
  2. 一旦你有了它,你就可以遍历 collection,当你遍历 collection 中的图像时,你可以获得原始宽度和高度,并在以后需要时使用它也许你想保持文档结构,因此有必要知道现有的图像大小,您还可以获得图像中的其他属性(即 alt 标题和描述,如果您想标记特定图像,则很有用。
    1. 最后您的代码看起来不错,您可以使用 "replace" insertLocation 调用 insertInlinePictures,唯一缺少的部分是您需要再次调用 context.sync 以便 Word 执行指令.

下面是一些示例代码,可以执行我提到的所有操作:

Word.run(function (context) {
            // here is how you access the inline pictures on the selection:
            var myImages = context.document.getSelection().inlinePictures;
            context.load(myImages);

            return context.sync().then(function () {
                if (myImages.items.length > 0) {
                    for (var i = 0; myImages.items.length; i++) {
                        //you could get the current image with and height if needed, so you replace use the same real estate.
                        var currentHeight = myImages.items[i].height;
                        var currentWidth = myImages.items[i].width;
// this is the instruction to replace the image:
                        var myNewImage = myImages.items[i].insertInlinePictureFromBase64(ImageBase64(), "replace");
                        return context.sync()  // very important you need to context.sync again



                    }
                }

            });
        }).catch(function (e) {
            app.showNotification(e.message);

        })