金山在线文档编辑器

2024-09-07 05:20
文章标签 文档 编辑器 在线 金山

本文主要是介绍金山在线文档编辑器,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

官方文档地址:快速开始-WebOffice 知识库

首先按照文档写的方式将包引入项目了

util.js

import WebOfficeSDK from "../../public/JSEditor/open-jssdk-v0.0.13.umd"
export function WordSDK(url, isEdit, mountDom, isShowTopArea, isShowHeader) {const el = document.querySelector(mountDom)if (!el) return nullconst instance = WebOfficeSDK.config({url,mount: el,commandBars: [{cmbId: 'HeaderMiddle', // 组件 IDattributes: {enable: isEdit, // 禁用组件(组件显示但不响应点击事件)},},],wordOptions: {enableReadOnlyComment: isEdit,isBestScale: false, // 打开文档时,默认以最佳比例显示},commonOptions: {isShowTopArea, // 隐藏顶部区域(头部和工具栏)isShowHeader, // 隐藏头部区域// isBrowserViewFullscreen: false, // 是否在浏览器区域全屏// isIframeViewFullscreen: false, // 是否在 iframe 区域内全屏// acceptVisualViewportResizeEvent: true, // 控制 WebOffice 是否接受外部的 VisualViewport},});instance.setToken({// token: `bearer ${getToken('token')}`,token: '',timeout: 10 * 60 * 1000,});return instance;
}

封装编辑器组件:KSEditor.vue

<template><div ref="editorContainer" class="editor-container"></div>
</template><script>import {WordSDK} from "@/utils/util"export default {name: 'JsEditorComponent',props: {KSfile: {type: String,default: ''},isShowHeader: {type: Boolean,default: true},isShowTopArea: {type: Boolean,default: true},isEditable: {type: Boolean,default: true}},data() {return {editorInstance: null,ksConfig: {// 在这里配置金山在线文档编辑器的初始化参数// 比如 token、文档ID 等}};},mounted() {// 在组件加载完成后初始化编辑器this.initEditor()},methods: {initEditor() {let KSInstance = WordSDK(this.KSfile,this.isEditable,'.editor-container',this.isShowTopArea,this.isShowHeader,)this.$emit('setInstance', KSInstance)},createDocument() {// 在点击按钮时触发新建文档操作// 假设SDK提供了相应的方法来新建文档if (this.editor) {this.editor.createDocument(); // 假设SDK方法名为createDocument} else {console.error('编辑器尚未初始化');}}}};
</script><style scoped>/* 可能需要一些样式来控制编辑器容器的宽度和高度 */.editor-container {width: 100%;height: 600px;}
</style>

页面testKSEditor.vue

<template><div style="width: 100%"><el-uploadclass="compare-uploader"ref="upload":with-credentials="true":show-file-list="false"withCredentials:http-request="httpRequest":on-progress="onProgress":multiple="false"><!-- 文件上传--><el-buttontype="ghost"slot="trigger"size="mini">导入文件</el-button></el-upload>id:<el-input v-model="ksFileInfoCopy.id"/><br/>文件类型:<el-input v-model="ksFileInfoCopy.ext"/><br/>文件名称:<el-input v-model="ksFileInfoCopy.name"/><br/><el-button@click="()=>getFileUrl(this.ksFileInfoCopy.id, this.ksFileInfoCopy.ext)">刷新</el-button><el-button@click="()=>destroyKS()">销毁</el-button><el-button@click="()=>insertBookmark('TEXT')">插入书签</el-button><el-button@click="()=>insertBookmark('TABLE')">插入表格类型书签</el-button><el-button@click="() => this.bookmarks = []">清空</el-button><el-button@click="()=>changeMode()">{{mode === 'edit'?'预览':'编辑'}}</el-button><el-button@click="()=>replaceBookmarkValue()">替换书签值</el-button><JSEditorv-if="showKS"@setInstance="setInstance":KSfile="KSfile":isShowTopArea="isShowTopArea":isShowHeader="isShowHeader":isEditable="isEditableFile"/></div>
</template><script>import axios from "axios";import JSEditor from 'lib@/components/KSEditor'import {userTableMap} from "@/modules/testKSeditor/fieldMap";const userTable = userTableMapexport default {name: "index",components: {JSEditor},data () {// supplementRules:return {userId: this.$store.getters.userId,fileLoading: false,app: null,bookmark: null,KSfile: '',KSurl: '',showKS: false,isShowHeader: true,isShowTopArea: true,isEditableFile: true,ksFileInfo: {ext: 'docx',id: '0af2cc2e1da145f48667a6bd09d30e77',// id: '6170f21b9fe94db78bc2e56d8f543c1e',name: '工治具报修管理.docx',url: ''},ksFileInfoCopy: {ext: 'docx',id: '0af2cc2e1da145f48667a6bd09d30e77',// id: '6170f21b9fe94db78bc2e56d8f543c1e',name: '工治具报修管理.docx',url: ''},tableData: [{number: '1',name: 'yy',sex: 'b',age: '11'},{number: '2',name: 'ee',sex: 'g',age: '22'},{number: '3',name: 'ss',sex: 'b',age: '33'},{index: '4',name: 'ff',sex: 'g',age: '44'},],mode: 'edit',bookmarks: [],KSInstance: null}},methods: {async setInstance(instance){// console.log(instance, '1111')this.KSInstance = instanceawait instance.ready()if(this.mode === 'preview'){const app = instance.Applicationawait app.ActiveDocument.SetReadOnly({Value: true})}// console.log(app, 'this.KSInstance.Application')},httpRequest(fileObj) {const formData = new FormData();formData.append("file", fileObj.file);axios({url: 'https://sdap-dev.sunwoda.com/api/platform-oss/public/upload?bucket=sdap',method: "post",data: formData,}).then(res => {this.ksFileInfo = res.data.datasthis.ksFileInfoCopy = res.data.datasthis.getFileUrl(res.data.datas.id, res.data.datas.ext)}).catch(error => {console.log(error);});},getFileUrl(fileId, ext, isPreview) {this.showKS = falsethis.fileLoading = trueaxios({url: 'https://sdap-dev.sunwoda.com/api/platform-system/public/wps-api/edit-url',method: "get",params: { fileId, ext, previewMode: 'high_definition' }}).then(res => {this.fileLoading = falsethis.KSfile = res.data.datasthis.KSurl = res.data.datasthis.ksFileInfoCopy.url = isPreview ? this.ksFileInfo.url : res.data.datasthis.ksFileInfo.url = res.data.datasthis.showKS = true}).catch(error => {console.log(error);});},destroyKS(){this.KSInstance.destroy()},async insertBookmark(type){const bookmark = await this.KSInstance.Application.ActiveDocument.Bookmarks;const selection = await this.KSInstance.Application.ActiveDocument.ActiveWindow.Selection// 区域对象let mark = 'mark' + Date.now()const range = await selection.Rangeconst start = await range.Startlet content = type + '书签'+ markconst end = start + content.length// 在选区后面插入内容await selection.InsertAfter(content)await bookmark.Add({Name: mark,Range: {Start: start,End: end}})this.bookmarks.push({markName: mark,type: type,value: mark + '的值'})},changeMode(){if(this.mode === 'edit'){this.mode = 'preview'this.isShowHeader = falsethis.isShowTopArea = falsethis.isEditableFile = falselet replaceData = []let modelLines = this.bookmarks // 合同元素相关信息// let allMarks = await this.KSInstance.Application.ActiveDocument.Bookmarks.Json()for (const i of modelLines) {replaceData.push({bookmark: i.markName,type: i.type,text: i.value})}let template_url = 'https://sdap-dev.sunwoda.com/api/platform-oss/public/download/' + this.ksFileInfo.idlet data = {task_id: this.userId,template_url: template_url,template_filename: this.ksFileInfo.name,use_template_section_property:true,flatten_source_style: true,sample_list: replaceData}axios({url: 'https://sdap-dev.sunwoda.com/api/platform-system/public/wps-api/wrap-header',method: 'post',data}).then(res => {if(res.data.resp_code === 200){this.getReviewFile(res.data.datas.download_id)}})} else {this.mode = 'edit'this.ksFileInfoCopy = this.ksFileInfothis.isShowHeader = truethis.isShowTopArea = truethis.isEditableFile = truethis.getFileUrl(this.ksFileInfo.id, this.ksFileInfo.ext)}},getReviewFile(id){let data = {bucket: 'sdap',downloadId: id,fileName: id + '测试文档.docx'}axios({url: ' https://sdap-dev.sunwoda.com/api/platform-system/public/wps-api/upload-file',method: 'post',params: data}).then(res => {this.ksFileInfoCopy = res.data.datasthis.getFileUrl(res.data.datas.id, res.data.datas.ext, true)})},async replaceBookmarkValue(){let modelLines = this.bookmarks // 合同元素相关信息let allMarks = await this.KSInstance.Application.ActiveDocument.Bookmarks.Json()let replaceData = []for (const i of modelLines) {if (i.type === 'TABLE') {let tableData = JSON.parse(JSON.stringify(this.tableData))let header = ["序号", "姓名", "性别", "年龄"]await this.insertTable(header, tableData, userTable, i)} else {replaceData.push({name: i.markName,type: 'text',value: i.value})}}this.KSInstance.Application.ActiveDocument.Bookmarks.ReplaceBookmark(replaceData)},async insertTable(tableHead, tableBodyData, fieldMap, eleInfo){const tables = await this.KSInstance.Application.ActiveDocument.Tables // 编辑器的表格对象let tableData = JSON.parse(JSON.stringify(tableBodyData))tableData.map((i, ind) => {i.number = ind + 1 + ''})let headerData = {}let fields = tableHead.map((elmKey, index) => {if (!!elmKey) {headerData[fieldMap.get(elmKey)] = elmKeyreturn {name: elmKey,field: fieldMap.get(elmKey)}}})tableData.unshift(headerData)let rowCount = tableData.length, colCount = tableHead.length// 插入表格await tables.Add(this.KSInstance.Application.ActiveDocument.Bookmarks.Item(eleInfo.markName).Range, // 位置信息rowCount, // 新增表格的行数colCount, // 新增表格的列数1, // 启用自动调整功能1 // 根据表格中包含的内容自动调整表格的大小)const count = await tables.Count  // 表格数量const curTable = await tables.Item(count)console.log(count, 'count')// console.log(tableData, 'tableData')// console.log(headerData, 'headerData')// console.log(fields, 'fields')for (let j = 1; j < rowCount + 1; j++) { // 遍历行let row = tableData[j-1]for (let f = 1; f < colCount + 1; f++) {  // 遍历列let fieldsInfo = fields[f-1]// console.log(fieldsInfo, 'fieldsInfo')let field = row[fieldsInfo.field] || ''const cell = await curTable.Rows.Item(j).Cells.Item(f).Rangecell.Text = field + ''}}this.KSInstance.Application.ActiveDocument.ReplaceText([ // 将书签的内容替换成空字符串{key: 'TABLE书签' + eleInfo.markName,value: ''}])}}}
</script><style scoped></style>
fieldMap.js
export const userTableMap = new Map();
userTableMap.set('序号', "number");
userTableMap.set('姓名', "name");
userTableMap.set("性别", "sex");
userTableMap.set("年龄", "age");

前端代码实现书签替换页面效果:

两张截图是分开截的,效果差不多是这样。是有bug的,给表格赋值不太稳定。书签替换也不稳定,没截到连续的图就是因为这个,老有问题,不想截了,不稳定的原因不明。

还可以调用在线编辑的接口实现书签替换,这种方式不支持替换成表格,但支持替换成在线文档,就是可以建一个在线文档,里面加表格,然后将这个在线文档引入进来。我用的接口是我们的后端封装过的,具体的找金山的询问,毕竟要用这个肯定得买,他们肯定会派人支持。

调用接口的方式,可以在“编辑”“预览”之前多次跳转,因为这个方法替换书签不是在原文档上修改,是后台会新建一个文件来替换书签,并且这个新文档会缓存24小时,在这时间内可以下载。

这篇关于金山在线文档编辑器的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/1144170

相关文章

C#借助Spire.XLS for .NET实现在Excel中添加文档属性

《C#借助Spire.XLSfor.NET实现在Excel中添加文档属性》在日常的数据处理和项目管理中,Excel文档扮演着举足轻重的角色,本文将深入探讨如何在C#中借助强大的第三方库Spire.... 目录为什么需要程序化添加Excel文档属性使用Spire.XLS for .NET库实现文档属性管理Sp

Java利用Spire.Doc for Java实现在模板的基础上创建Word文档

《Java利用Spire.DocforJava实现在模板的基础上创建Word文档》在日常开发中,我们经常需要根据特定数据动态生成Word文档,本文将深入探讨如何利用强大的Java库Spire.Do... 目录1. Spire.Doc for Java 库介绍与安装特点与优势Maven 依赖配置2. 通过替换

C#实现插入与删除Word文档目录的完整指南

《C#实现插入与删除Word文档目录的完整指南》在日常的办公自动化或文档处理场景中,Word文档的目录扮演着至关重要的角色,本文将深入探讨如何利用强大的第三方库Spire.Docfor.NET,在C#... 目录Spire.Doc for .NET 库:Word 文档处理利器自动化生成:C# 插入 Word

Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)

《Python实现Word文档自动化的操作大全(批量生成、模板填充与内容修改)》在职场中,Word文档是公认的好伙伴,但你有没有被它折磨过?批量生成合同、制作报告以及发放证书/通知等等,这些重复、低效... 目录重复性文档制作,手动填充模板,效率低下还易错1.python-docx入门:Word文档的“瑞士

使用EasyPoi快速导出Word文档功能的实现步骤

《使用EasyPoi快速导出Word文档功能的实现步骤》EasyPoi是一个基于ApachePOI的开源Java工具库,旨在简化Excel和Word文档的操作,本文将详细介绍如何使用EasyPoi快速... 目录一、准备工作1、引入依赖二、准备好一个word模版文件三、编写导出方法的工具类四、在Export

利用Python操作Word文档页码的实际应用

《利用Python操作Word文档页码的实际应用》在撰写长篇文档时,经常需要将文档分成多个节,每个节都需要单独的页码,下面:本文主要介绍利用Python操作Word文档页码的相关资料,文中通过代码... 目录需求:文档详情:要求:该程序的功能是:总结需求:一次性处理24个文档的页码。文档详情:1、每个

C++读写word文档(.docx)DuckX库的使用详解

《C++读写word文档(.docx)DuckX库的使用详解》DuckX是C++库,用于创建/编辑.docx文件,支持读取文档、添加段落/片段、编辑表格,解决中文乱码需更改编码方案,进阶功能含文本替换... 目录一、基本用法1. 读取文档3. 添加段落4. 添加片段3. 编辑表格二、进阶用法1. 文本替换2

Python实现自动化删除Word文档超链接的实用技巧

《Python实现自动化删除Word文档超链接的实用技巧》在日常工作中,我们经常需要处理各种Word文档,本文将深入探讨如何利用Python,特别是借助一个功能强大的库,高效移除Word文档中的超链接... 目录为什么需要移除Word文档超链接准备工作:环境搭建与库安装核心实现:使用python移除超链接的

在Android中使用WebView在线查看PDF文件的方法示例

《在Android中使用WebView在线查看PDF文件的方法示例》在Android应用开发中,有时我们需要在客户端展示PDF文件,以便用户可以阅读或交互,:本文主要介绍在Android中使用We... 目录简介:1. WebView组件介绍2. 在androidManifest.XML中添加Interne

C#实现一键批量合并PDF文档

《C#实现一键批量合并PDF文档》这篇文章主要为大家详细介绍了如何使用C#实现一键批量合并PDF文档功能,文中的示例代码简洁易懂,感兴趣的小伙伴可以跟随小编一起学习一下... 目录前言效果展示功能实现1、添加文件2、文件分组(书签)3、定义页码范围4、自定义显示5、定义页面尺寸6、PDF批量合并7、其他方法