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等,不能直接展示,具体原因如下
相关推荐
冬奇Lab2 小时前
AI Workflow 定义的四次演进:从 Markdown 到 JS 脚本,再到分布式多 Agent
javascript·人工智能·agent
zhangxingchao2 小时前
Kotlin常用的Flow 操作符整理
前端
IT_陈寒3 小时前
React的useState居然还有这种坑?我差点删库跑路
前端·人工智能·后端
Pedantic4 小时前
SwiftUI 手势笔记
前端·后端
橙子家5 小时前
浏览器缓存之【结构化数据库与缓存】: IndexedDB、Cache storage 和 Storage buckets
前端
user20585561518135 小时前
X6 中边悬浮置顶,规避 `mouseleave` 事件丢失问题
前端
李明卫杭州5 小时前
CSS aspect-ratio 属性完全指南
前端
Pedantic7 小时前
SwiftUI 手势层级(Gesture Hierarchy)详解
前端
飘尘7 小时前
前端转型全栈(Java后端)的快速上手指引
前端·后端·全栈