SOURCE

console 命令行工具 X clear

                    
>
console
new Vue({
    el: '#app',
    data() {
        return {
            webofficeInstance: null,
            debunce: false,
            config: {
                "officeType": "docx",
                "appId": "e13d6cf1fad141eaa08266bc5b74e141",
                "fileId": "881943301371201472",
                "signature": {
                    "sign": "0c99f78cf644d214d744f9a96a7732037b4dead5",
                    "nonce": "4595",
                    "timeStamp": "1725000218625"
                },
                "endpoint": "https://test-cmp-doc.woa.com",
                "fileToken": "79774",
                "mode": "normal",
                "commonOptions": {
                    "isShowTitleBar": true,
                    "isShowToolBar": true
                },
                "wordOptions": {
                    "isShowStatusBar": true,
                    "isShowOutline": true
                }
            },
            bookNum: 1,
            fileId: "35000",
            processedKeysObject: { "F23032890003-vPXx": "腾讯音乐(北京)有限公司", "F24082920001-8CAn": "腾讯大厦", "F24082940003-fijF": "南京鸡鸣寺", "F24082970002-OmJB": "撒大大阿达是的", "F24082970004-1NWl": "招商银行", "contractTitle": "手打撒上的大萨达" }
        };
    },
    methods: {
        async handleBookmarksRange() {
            await this.buildBookmarksSetText();
        },
        // 加载文档
        updateConfigFromJson() {
            try {
                const parsedConfig = JSON.parse(this.jsonConfig);
                if (typeof parsedConfig === "object" && parsedConfig !== null) {
                    this.config = { ...this.config, ...parsedConfig };
                    this.updateWps();
                } else {
                    alert("请输入有效的JSON格式配置");
                }
            } catch (error) {
                console.log(error, "JDK");
            }
        },
        async addBookmark() {
            this.bookNum = this.bookNum + 1;
            if(!webofficeInstance.Application) {
                console.log("Application 正在初始化");
                return;
            }
            const app = webofficeInstance.Application;
            await app.getActiveDocument().addBookmark(`书签${this.bookNum}`, {
                    getStart: () => 1 + this.bookNum,
                    getEnd: () => 2 + this.bookNum
            });
            const bookmarks = await app.getActiveDocument().getBookmarks();
            console.log(bookmarks.length)
        },
        async buildBookmarksSetText() {
            if(!webofficeInstance.Application) {
                console.log("Application 正在初始化");
                return;
            }
            if(this.debunce){
                console.log("书签还在创建中");
                return;
            }
            this.debunce = true;
            const app = webofficeInstance.Application
            let allBookmarks = await app.getActiveDocument().getBookmarks();
            const allBookmarksLen = allBookmarks.length;
            const bookmarkRanges = [];
            for(let i = 0;i < allBookmarksLen; i++) {
                const bookmarkKey = allBookmarks[i].getName().split(":")[1];
                const bookmarkValue = this.processedKeysObject[bookmarkKey];
                if(!bookmarkValue){
                    continue;
                }
                const range = await allBookmarks[i].getRange();
                const { start } = range.data;
                const end = start + bookmarkValue.length;

                const selection = await app.getActiveDocument().getSelection();
                await selection.update(range);
                await selection.setText(bookmarkValue);
                // 新增书签
                // await app.getActiveDocument().addBookmark(`书签${i + 1}:${bookmarkKey}`, {
                //         getStart: () => start,
                //         getEnd: () => end
                // });
                bookmarkRanges.push([bookmarkKey, start, end]);
            }
            allBookmarks = await app.getActiveDocument().getBookmarks();
            console.log(allBookmarks.length, 'before');
            for(let i = 0;i < allBookmarksLen; i++) {
                const [bookmarkKey, start, end] = bookmarkRanges[i];
                // 新增书签
                await app.getActiveDocument().addBookmark(`书签${i + 1}${bookmarkKey}`, {
                        getStart: () => start,
                        getEnd: () => end
                });
            }
            allBookmarks = await app.getActiveDocument().getBookmarks();
            console.log(allBookmarks.length, 'new');
            this.debunce = false;
        },
        async updateWps() {
            // 销毁已存在的WebOffice实例
            if (window.webofficeInstance && webofficeInstance.destroy) {
                webofficeInstance.destroy();
                webofficeInstance = null; // 销毁后清空引用
            }
            const iframeElement = document.getElementById("wpshtml");
            let mergedConfigs = {
                ...this.config,
                mount: iframeElement,
            };
            // console.log(mergedConfigs, "mergedConfigs1");
            // 初始化新的WebOffice实例
            window.webofficeInstance = TencentDocsSDK.init(mergedConfigs);
            await webofficeInstance.ready();
        },
        async getContentRange() {
            const contentControls = await webofficeInstance.Application.getActiveDocument().getContentControls();
            if (contentControls[0]) {
                console.log('result:getId', contentControls[0].getId());
                console.log('result:getRange', await contentControls[0].getRange());
                console.log('result:getContent', await contentControls[0].getContent());
            }
        },
        async getBookmarksRange() {
            if(!webofficeInstance.Application) {
                console.log("Application 正在初始化");
                return;
            }
            const bookmarks = await webofficeInstance.Application.getActiveDocument().getBookmarks();
            console.log(bookmarks.length)
            if (bookmarks[0]) {
                // console.log('result:getId', bookmarks[0].getId());
                // console.log('result:getName', bookmarks[0].getName());
                // const rangeData = await bookmarks[0].getRange();
                // console.log('result:getRange', rangeData.data.end);
                // console.log('result', JSON.stringify(rangeData));

            }
        },
    },

    computed: {
        jsonConfig: {
            get() {
                return JSON.stringify(this.config);
            },
            set(value) {
                try {
                    const parsedConfig = JSON.parse(value);
                    this.config = { ...this.config, ...parsedConfig };
                } catch (error) {
                    console.error("Failed to parse JSON:", error);
                }
            },
        },
    },
})
<!-- 引入样式 -->
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<!-- 引入组件库 -->
<script src="https://unpkg.com/element-ui/lib/index.js">

</script>
<div id="app">
    <div class="module-container">
        <pre>联动对象关系: {{processedKeysObject}}</pre>
        <!-- JSON配置编辑区域 -->
        <div class="custom-card">
            <el-form :model="config" label-width="120px" class="config-editor">
                <el-form-item label="JSON配置">
                    <el-input
                        rows="2"
                        type="textarea"
                        v-model="jsonConfig"
                        placeholder="粘贴JSON配置"
                    />
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="updateConfigFromJson">加载文档</el-button>
                    <el-button @click="getContentRange">内容选区</el-button>
                    <el-button @click="getBookmarksRange">书签选区</el-button>
                    <el-button @click="handleBookmarksRange">联动书签</el-button>
                </el-form-item>
            </el-form>
        </div>
        <div class="custom-card">
            <div frameborder="0" id="wpshtml" class="doc-main"></div>
        </div>
    </div>
</div>
.inner-box {
    width: 100%;
    /* height: 100%; */
}
.container {
    min-height: 800px;
    height: 100%;
}
.config-editor {
    padding: 10px;
    box-sizing: border-box;
}
.doc-main {
    height: 100vh;
    min-height: 200px;
}

本项目引用的自定义外部资源