问题
之前使用pdf viewer进行pdf预览
先从pdf.js下载pdf viewer到本地 放到public文件夹内
然后在项目内使用iframe访问viewer
<script setup>
const pdfURL = 'http://xxx'
const src = `/pdfjs/web/viewer.html?file=${encodeURIComponent(pdfURL)}`
</script>
<template>
<iframe title="pdf" :src="src"></iframe>
</template>
但是现在后端改了 必须在请求头里添加token才能正确取到pdf
解决
在外部获取pdf信息 转化为blob:http://xxx的临时文件地址 并提供给iframe
<script setup>
const pdfURL = ref('')
watch(() => props.url, url => {
URL.revokeObjectURL(pdfURL.value)
pdfURL.value = ''
getPdfContent(url)
.then(blob => {
pdfURL.value = URL.createObjectURL(blob)
})
}, { immediate: true })
const src = computed(()=>`/pdfjs/web/viewer.html?file=${encodeURIComponent(pdfURL.value)}`)
</script>
<template>
<iframe v-if="pdfURL" title="pdf" :src="src"></iframe>
</template>
如果使用第三方的viewer
例如 要使用微软的在线word功能(参考这篇文章) 则必须通过反向代理使viewer与源网页同源