本示例关键代码的编写位置,请参考“PageOffice 开发者中心-快速起步–开始 - 快速上手”里您所使用的开发语言框架的最简集成代码
注意 本文中展示的代码均为关键代码,复制粘贴到您的项目中,按照实际的情况,例如文档路径,用户名等做适当修改即可使用。
推荐在主窗口浏览器中提供多个打开文件的链接(或按钮),点击每个链接都可以弹出Pageoffice浏览器(POBrowser)在线打开不同的Office文件,这样做就实现了同时打开多个文件,并且在任务栏上切换文件。此方案的优点是:速度更快,效率更高。
如果确实需要在弹出Pageoffice浏览器(POBrowser)窗口调用PageOffice在线打开文件之后,在POBrowser窗口内切换打开另外一个Office文件,比如,提供多个Tab标签页同时打开多个文件,并实现切换打开不同文件的效果,那么,需要升级PageOffice产品到V6.3.2.3(或更高版本),客户端控件增加了js接口pageofficectrl.Reload()
,用于控件的重新加载,实现在PageOffice浏览器(POBrowser)中切换打开另一个文件的功能。
就以目前流行的前后端分离开发Springboot+Vue3框架为例,实现POBrowser窗口内切换打开不同文件的核心代码如下:
后端代码
编写调用PageOffice在线打开指定文件的代码如下:
@RestController
@RequestMapping(value = "/SwitchFile")
public class SwitchFile {
@RequestMapping(value = "/Word")
public String showWord(HttpServletRequest request,String fileName) {
PageOfficeCtrl poCtrl = new PageOfficeCtrl(request);
//打开文档
poCtrl.webOpen("/doc/SwitchFile/"+fileName, OpenModeType.docNormalEdit, "张三");
return poCtrl.getHtml();
}
}
前端代码
实现一个文件列表,点击文件列表中的不同文件的链接,就可以切换打开对应的Office文件。
<template>
<div class="Word">
<div class="sidebar">
<h3>文件列表</h3>
<ul>
<li v-for="file in files" :key="file.id" @click="selectFile(file)" class="file-link">
{{ file.title }}
</li>
</ul>
</div>
<div class="content">
<h4>{{ selectedFile?.title }}</h4>
<!-- 此div用来加载PageOffice客户端控件 -->
<div style="width:auto; height:100%;" v-html="poHtmlCode"></div>
</div>
</div>
</template>
<script setup>
import request from '@/utils/request';
import { ref, onMounted } from 'vue'
const poHtmlCode = ref('');
const files = ref([
{ id: 1, title: 'PageOffice对客户端的要求', fileName: 'test1.docx' },
{ id: 2, title: 'PageOffice授权协议', fileName: 'test2.docx' },
{ id: 3, title: '试用版和正式版的区别', fileName: 'test3.docx' },
]);
const selectedFile = ref(null);
function selectFile(file) {
selectedFile.value = file;
switchFile(file.fileName);
}
function openFile(fileName) {
// 发起GET请求到服务器后端接口,在线打开文件
return request({
url: '/SwitchFile/Word?fileName='+fileName,
method: 'get',
});
}
function switchFile(fileName) {
openFile(fileName).then(response => {
poHtmlCode.value = response;
pageofficectrl.Reload(); //必须,切换打开文件时必须调用pageofficectrl.Reload()
});
}
function firstLoadFile(fileName){
openFile(fileName).then(response => {
poHtmlCode.value = response;
});
}
onMounted(() => {
//如果想要首次打开POBrowser浏览器窗口时不打开文件,则下面的代码可以注释掉,并且注意如果首次打开POBrowser浏览器窗口想要打开文件,则千万不能调用pageofficectrl.Reload(),否则控件会加载两次
selectedFile.fileName="test1.docx";//默认打开test1.docx
firstLoadFile(selectedFile.fileName);
})
</script>
<style>
/* 设置整个页面的样式 */
html,
body {
height: 100%;
margin: 0;
padding: 0;
overflow: hidden;
}
.Word {
display: flex;
}
.sidebar {
flex: 0 0 30%;
height: 100vh;
border-right: 1px solid #ccc;
text-align: center;
padding: 10px 50px;
}
.file-link {
cursor: pointer;
padding: 8px;
border-bottom: 1px solid #eee;
text-decoration: underline;
color: #3568d7;
display: block;
}
.file-link:hover {
background-color: #f0f0f0;
color: #42b983;
}
.content {
flex: 0 0 70%;
padding: 10px;
}
h4{
color:#42b983;
}
</style>