JS-前端在dom中预览pdf等文件

1、将pdf等文件显示到dom元素中预览

  • pdf文件可以是blob、url、file类型等
  • 只要使用URL.createObjectURL(file)全部转为URL即可使用
  • 无需借助任何插件,只需要使用<object></object>标签即可实现

1.1、html

html 复制代码
<template>
  <div class="home">
    <object id="pdf-object" width="50%" height="500px"></object>
 
    <input type="file" id="pdf-file" />
    <button @click="showPDF">预览文件</button>
  </div>
</template>

1.2、js

js 复制代码
<script>

export default {
  name: 'HomeView',
  methods: {
    showPDF() {
      const inputElement = document.getElementById('pdf-file');
      const objectData = document.getElementById('pdf-object');

	  // 获取选择的文件
      const file = inputElement.files[0];
      // 转为url
      const url = URL.createObjectURL(file);
      // 给object标签赋值 相当于image标签的src属性
      objectData.data = url;
    }
  }
}
</script>

1.3、效果

1.4、注意

  • 如果不是这种file类型,而是后台返回的blob类型数据。
  • 那么在接收blob的时候,需要给构造函数传入第二个类型参数application/pdf,如下这样
  • 如果需要展示其他类型文件,只需修改相应type值即可。
  • word、excel、ppt等,不能直接展示,具体原因如下
相关推荐
San813_LDD1 小时前
[C语言]《Dev-C++ 报错解决手册(Day0607 精华版)》
java·前端·javascript
xiaofeichaichai7 小时前
Webpack
前端·webpack·node.js
问心无愧05137 小时前
ctf show web入门111
android·前端·笔记
唐某人丶7 小时前
模型越来越强,我们还需要 Agent 工程吗?—— 从价值重估到 Harness 实践
前端·agent·ai编程
智码看视界7 小时前
现代Web开发基础:全栈工程师的起航点
前端·后端·c5全栈
JS菌8 小时前
手写一个 AI Agent 全栈项目:从沙箱执行到子智能体的完整实现
前端·人工智能·后端
excel9 小时前
HLS TS 文件损坏的元凶:Git 提交与拉取
前端
Aphasia3119 小时前
https连接传输流程
前端·面试
徐小夕9 小时前
万字长文!千万级文档 RAG 知识库系统落地实践
前端·算法·github