目的
實現word文件的預覽以及簡單的在線編輯
工具
ckeditor5是一款富文本編輯器,它可以實現常用word的操作,下載安裝網上一大堆就不再這細說了。
原理
ckeditor可以提前使用setData函數載入數據,但如果直接載入word格式的文件會把word文件的特征消失掉,但通過研究發現他其中的數據最后是轉換成HTML格式輸出,那么直接輸入HTML格式就能完整的顯示了,而且能實時的更改。
java的poi包,poi是第三方包可以針對word文檔進行一系列的操作,現在我要用到的是html與word的轉換。
實現
前端代碼
<meta charset="UTF-8">
<title>Title</title>
<script>
function f() {//向后端發送請求
var xhttp= new XMLHttpRequest();
xhttp.onreadystatechange=function(){
if (this.readyState == 4 && this.status == 200){
myEditor.setData(this.responseText)//后端返回HTML字符串
}
}
xhttp.open("post","/返回文件",true);
xhttp.send();
}
function f1() {
}
</script>
<textarea name="content" id="editor">//編輯器
</textarea>
<script src="/HTML/文本編輯插件/ckeditor.js"></script> <!--改成自己項目的路徑-->
<script src="/HTML/文本編輯插件/translations/zh-cn.js"></script>//改成中文
<script>
var myEditor = null;//先設置一個全局變量
ClassicEditor
.create( document.querySelector( '#editor' ) ,{
language: 'zh-cn',//設置成中文
} )
.then(editor=>{
myEditor=editor;//獲得編輯器對象
})
.catch( error => {
console.error( error );
} );
</script>
<br>
<input type="button" value="顯示" onclick="f()">
后端代碼
框架spring boot
@PostMapping("/返回文件")
public String 返回文件() throws IOException {
//獲取要訪問的文件
File file = new File("E:\\測試\\雲盤\\src\\main\\resources\\templates\\ckeditor5-build-classic\\市場調研報告.docx");
FileInputStream fileInputStream= new FileInputStream(file);//獲取文件的字符流
XWPFDocument re = new XWPFDocument(fileInputStream);//docx格式要求
StringWriter stringWriter = new StringWriter();//創建一個新的字符流對象
XHTMLConverter xhtmlConverter = (XHTMLConverter)XHTMLConverter.getInstance();
XHTMLOptions options = XHTMLOptions.getDefault();
xhtmlConverter.convert(re, stringWriter,options);//注入
String html = new String (stringWriter.toString().getBytes("utf-8"),"utf-8");編碼賦值
System.out.println(html);//顯示
re.close();
return html;//返回給前端
}
展示
字體格式,間距都保存了下來。可以在線編輯保存就在把HTML轉換成word就行。Java新手,不足還請多多指教😀