Vue使用pdf.js和docx-preview實現(xiàn)docx和pdf的在線預覽
更新時間:2025年03月12日 09:57:50 作者:當new作碼
這篇文章主要為大家詳細介紹了在Vue中使用pdf.js和docx-preview實現(xiàn)docx和pdf的在線預覽的相關知識,文中的示例代碼講解詳細,需要的可以參考下
后端代碼:
SshConfig sshConfig = new SshConfig("ip", port, "username", "password");
ChannelSftp channelSftp = sshConfig.getChannelSftp();
String downUrl = "/**/**/";//服務器相對路徑
String pathname1 = downUrl + fileId + ".docx";
String pathname2 = downUrl + fileId + ".pdf";
InputStream inputStream1 = null;
InputStream inputStream2 = null;
//文件可能是docx或者pdf,因此需要分別嘗試獲取文件輸入流
try {
inputStream1 = channelSftp.get(pathname1);
} catch (SftpException e) {
inputStream2 = channelSftp.get(pathname2);
}
byte[] buffer = new byte[1024];
int bytesRead;
ByteArrayOutputStream output = new ByteArrayOutputStream();
if (inputStream1 != null) {
while ((bytesRead = inputStream1.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
byte[] fileBytes1 = output.toByteArray();
// 現(xiàn)在fileBytes中包含了遠程文件的字節(jié)流
if (fileBytes1 != null) {
channelSftp.disconnect();
sshConfig.disconnect();
// Convert the file to base64
String base64 = Base64.getEncoder().encodeToString(fileBytes1);
map.put("fileUrl", pathname1);
map.put("base64", base64);
return map;
}
} else {
while ((bytesRead = inputStream2.read(buffer)) != -1) {
output.write(buffer, 0, bytesRead);
}
byte[] fileBytes1 = output.toByteArray();
// 現(xiàn)在fileBytes中包含了遠程文件的字節(jié)流
if (fileBytes1 != null) {
channelSftp.disconnect();
sshConfig.disconnect();
// Convert the file to base64
String base64 = Base64.getEncoder().encodeToString(fileBytes1);
map.put("fileUrl", pathname2);
map.put("base64", base64);
return map;
}
}
return map;前端代碼:
mounted方法中判斷使用哪一個插件
mounted() {
let fileUrl = sessionStorage.getItem("fileUrl");
if (fileUrl.indexOf('.docx') !== -1) {
let bstr = sessionStorage.getItem("bstr");
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
console.log("docx");
//u8arr.buffer 轉(zhuǎn)成arrayBuffer類型
this.docxRender(u8arr.buffer, this.title);
} else {
let bstr = sessionStorage.getItem("bstr");
let n = bstr.length;
let u8arr = new Uint8Array(n);
while (n--) {
u8arr[n] = bstr.charCodeAt(n);
}
this.pdfData = u8arr;
console.log("pdf");
this.pdfReader(u8arr);
}
},docx文件的渲染
//渲染docx
docxRender(buffer, fileName) {
let box = document.createElement('div') // 創(chuàng)建一個div
let docx = require("docx-preview")
docx.renderAsync(buffer, box).then(() => { // 渲染文件
let zhengwen = document.getElementById('zhengwen');
zhengwen.appendChild(box);
//document.write(box.outerHTML);
//渲染文件后將div添加到新窗口中,div不能提前添加,否則新窗口中不能渲染出文件
//注意這里不能直接用box
document.title = fileName // 窗口標題
document.getElementsByClassName('docx')[0].style.width = 'auto'
// 如果文件顯示正常,不用設置寬度
}).catch(function () {
Message({
type: "error",
message: "該文檔可能已損壞,請嘗試下載查閱"
})
})
},渲染效果圖:

pfd文件渲染:
//渲染pdf
pdfReader(u8arr) {
// 獲取PDF容器元素
let container = this.$refs.pdfContainer;
// 配置PDFJS worker路徑
pdfjsLib.GlobalWorkerOptions.workerSrc = 'https://cdnjs.cloudflare.com/ajax/libs/pdf.js/2.16.105/pdf.worker.min.js';
// 加載PDF文件流
pdfjsLib.getDocument(u8arr).promise.then((pdf) => {
// 獲取頁面數(shù)量
const numPages = pdf.numPages;
// 循環(huán)遍歷所有頁面
for (let i = 1; i <= numPages; i++) {
pdf.getPage(i).then((page) => {
// 設置縮放比例
const scale = 1.7;
// 獲取渲染上下文
const canvas = document.createElement('canvas');
const ctx = canvas.getContext('2d');
// 計算畫布大小
const viewport = page.getViewport({scale});
canvas.height = viewport.height;
canvas.width = viewport.width;
// 將PDF頁面渲染到畫布上
const renderContext = {
canvasContext: ctx,
viewport: viewport
};
page.render(renderContext);
// 添加畫布到容器中
container.appendChild(canvas);
});
}
}).catch(function () {
Message({
type: "error",
message: "該文檔可能已損壞,請嘗試下載查閱"
})
});
},注意,使用前需要下載相應的庫,docx-preview工具不適用于渲染doc文件,需要自己去轉(zhuǎn)換文件類型(比如直接修改文件后綴名)
npm install pdfjs-dist npm install docx-preview
以上就是Vue使用pdf.js和docx-preview實現(xiàn)docx和pdf的在線預覽的詳細內(nèi)容,更多關于Vue文件在線預覽的資料請關注腳本之家其它相關文章!
相關文章
Vue導出Excel,后端返回的文件流,前端接收后無法打開文件的解決
在使用Vue導出Excel時,如果后端返回文件流,前端接收后無法打開文件,通常是由于響應類型設置不正確導致的,通過設置axios請求接口時的響應類型為`blob`,并使用blob轉(zhuǎn)換文件流,可以解決文件損壞無法打開的問題2025-12-12
Vue中Class和Style實現(xiàn)v-bind綁定的幾種用法
項目開發(fā)中給元素添加/刪除 class 是非常常見的行為之一, 例如網(wǎng)站導航都會給選中項添加一個 active 類用來區(qū)別選與未選中的樣式,那么在 vue 中 我們?nèi)绾翁幚磉@類的效果呢?下面我們就一起來了解一下2021-05-05
Vue使用pdf.js和docx-preview實現(xiàn)docx和pdf的在線預覽
這篇文章主要為大家詳細介紹了在Vue中使用pdf.js和docx-preview實現(xiàn)docx和pdf的在線預覽的相關知識,文中的示例代碼講解詳細,需要的可以參考下2025-03-03

