<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>PDF Preview Demo</title>
<script src="pdf/build/pdf.js"></script>
<script src="https://cdn.jsdelivr.net/npm/vue@2.6.14/dist/vue.js"></script>
<style scoped>
.wrap{
position: fixed;
top: 0;
left: 0;
width: 100%;
bottom: 0;
}
</style>
</head>
<body>
<div id="app" class="wrap">
<iframe id="pdfPrint" :src="pSrc" width="100%" height="100%"></iframe>
</div>
<script>
new Vue({
el: '#app',
data: {
pSrc: '',
},
methods: {
loadPDF() {
//baseurl :pdf存放的文件路径,可以是本地的,也可以是远程,这个是远程的,亲测可以用
// let baseurl = 'http://image.cache.timepack.cn/nodejs.pdf';
//ie有缓存加个随机数解决 + '?r=' + new Date()
// let pSrc = './test.pdf' + '?r=' + new Date();
// this.pSrc = 'public/pdf/web/viewer.html?file=' + encodeURIComponent(pSrc) + '.pdf';
//法一:
// 获取当前页面的基本路径
let baseUrl = window.location.href;
// 截取基本路径中的目录部分,保留到public目录
let baseUrlSlice = baseUrl.substring(0, baseUrl.lastIndexOf('public') + 6);
// 构建本地PDF文件路径
let pdfPath = baseUrlSlice + '/pdf/test.pdf';
// 将本地PDF文件路径编码并拼接到viewer.html中
this.pSrc = '/pdf/web/viewer.html?file=' + encodeURIComponent(pdfPath);
//法二:
// let DownUrl = 'pdf/test.pdf?r='+ new Date()
// fetch(DownUrl)
// .then((response) => response.blob())
// .then((res) => {
// let blob = new Blob([res], { type: 'application/pdf' });
// // pdfurl即转化后的结果
// let pdfurl = window.URL.createObjectURL(blob);
// // 新标签页打开,即可预览并下载
// // window.open(pdfurl);
// })
},
},
mounted: function () {
this.loadPDF();
}
});
</script>
</body>
</html>
tip:注意配置viewer.html路由
app.use(express.static('public'));
app.get('/pdf/web/viewer.html', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'pdf', 'web', 'viewer.html'));
});