方法一、blob实现
//content是base64格式
viewPdf(content) {
console.log("content",content)
const blob = this.base64ToBlob(content)
if (window.navigator && window.navigator.msSaveOrOpenBlob) {
window.navigator.msSaveOrOpenBlob(blob)
} else {
const fileURL = URL.createObjectURL(blob)
// window.open(fileURL);//弹出ppf文件
}
//code是base64格式
base64ToBlob(code) {
code = code.replace(/[\n\r]/g, '')
// atob() 方法用于解码使用 base-64 编码的字符串。
const raw = window.atob(code)
const rawLength = raw.length
const uInt8Array = new Uint8Array(rawLength)
for (let i = 0; i < rawLength; ++i) {
uInt8Array[i] = raw.charCodeAt(i)
}
return new Blob([uInt8Array], { type: 'application/pdf' })
},
方法二、embed或者iframe
// 打开一个新窗口或新标签页
const newWindow = window.open('', '_blank');
// 如果窗口打开成功,在新窗口中加载一个包含iframe的页面
if (newWindow) {
// 写入HTML到新窗口中
newWindow.document.write(`<embed v-if="${url}" : src="${url}" type="application/pdf" width="100%" height="600px"/>`);
// newWindow.document.write(`<iframe src="${url}" style="width:100%;height:100vh;" frameborder="0"></iframe>`);
} else {
// 窗口打开失败的处理逻辑
}
方法三、pdf.js实现
<!DOCTYPE html>
<html>
<head>
<title>PDF.js Preview</title>
</head>
<body>
<canvas id="the-canvas"></canvas>
<script src="./build/pdf.js"></script>
<script>
// 预览PDF的函数
function showPDF(pdfData) {
// 使用PDF.js加载PDF
pdfjsLib.getDocument({data: pdfData}).promise.then(function(pdf) {
// 获取第一页
pdf.getPage(1).then(function(page) {
var viewport = page.getViewport({scale: 1.5});
var canvas = document.getElementById('the-canvas');
var context = canvas.getContext('2d');
canvas.height = viewport.height;
canvas.width = viewport.width;
// 渲染页码
var renderContext = {
canvasContext: context,
viewport: viewport
};
page.render(renderContext).promise.then(function() {
console.log('Page rendered');
});
});
});
}
var data;
showPDF(data);
</script>
</body>
</html>