请求pdf文件流并进行预览

最近做了一个需求就是预览pdf等文件,不过后端返回的是一个文件流,需要前端做一定地处理才行。

我们来看一下具体的实现方式。预览pdf的插件使用的是pdf.js,具体请看这篇文章:pdf.js插件怎么控制工具栏的显示与隐藏

1、请求pdf文件流数据

先看一下请求pdf文件流的请求接口

javascript 复制代码
getPdfStream(id,data,responseType = 'blob'){
   return request.get('/api/business/getPdfStream/'+id,{params:{...data},responseType:responseType})
}
2、把请求回来的文件流数据转化为url
javascript 复制代码
<template>
   <div>
     <iframe
        allowfullscreen="true"
        :src="contentUrl"
        frameborder="0"
        width="100%"
        height="1200px"
     ></iframe>
   </div>
</template>
<script setup>	
import {onMounted,ref} from 'vue'
let contentUrl = ref("")
let fileId = new URLSearchParams(location.hash.split("previewPdf?")[1]);
onMounted(()=>{
   getPdfContent(fileId)
})

// 获取pdf内容
function getPdfContent(fileId) {
   API.getPdfStream(fileId).then(res=>{
      // 这一步是关键,使用window.URL.createObjectURL把blob数据转为本地URL
      let url = window.URL.createObjectURL(new Blob([res.data]));
      
      contentUrl.value = `static/pdfjs/web/viewer.html?file=${url}`
   })
}
</script>
相关推荐
优选资源分享41 分钟前
全能 PDF 工具 - Icecream PDF Candy v3.17 便携版
pdf
开开心心_Every2 小时前
CDR版本转换工具,支持多版本互转免升级软件
linux·运维·服务器·云原生·edge·pdf·serverless
开开心心就好5 小时前
实用PDF擦除隐藏信息工具,空白处理需留意
运维·服务器·windows·pdf·迭代器模式·桥接模式·1024程序员节
2501_907136821 天前
word元数据批量修改与PDF转换工具
pdf·软件需求
halen3331 天前
Transform PDFs into Stunning Images with Free PDF to IMG!
pdf
开开心心_Every1 天前
局域网大文件传输,设密码双向共享易用工具
运维·服务器·网络·游戏·pdf·电脑·excel
开开心心就好1 天前
实用PDF批量加马赛克,抹除敏感信息绿色版
java·linux·开发语言·网络·人工智能·pdf·word2vec
github.com/starRTC2 天前
Claude Code中英文系列教程35:通过API使用Skills创建ppt,word文档和pdf
pdf·word·powerpoint·ai编程
开开心心_Every3 天前
剪切板工具存500条,可搜索备份导入导出
linux·运维·服务器·华为od·edge·pdf·华为云
疯狂敲代码的老刘3 天前
PDFSam Basic:轻量开源的 PDF 拆分合并利器
pdf·工具·pdf工具·pdfsam