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

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

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

1.1、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

<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、效果

JS-前端在dom中预览pdf等文件_第1张图片

1.4、注意

  • 如果不是这种file类型,而是后台返回的blob类型数据。
  • 那么在接收blob的时候,需要给构造函数传入第二个类型参数application/pdf,如下这样
    • JS-前端在dom中预览pdf等文件_第2张图片
  • 如果需要展示其他类型文件,只需修改相应type值即可。
  • word、excel、ppt等,不能直接展示,具体原因如下
    • JS-前端在dom中预览pdf等文件_第3张图片

你可能感兴趣的:(前端,javascript,pdf)