pdfh5 pdf

踩坑1: 渲染失败

(1)在vue项目中,读取本地的pdf文件需要放到public下static文件夹中,不能放在别的地方;

(2)引用时,不能使用相对路径,因为使用public文件下面的资源,是不会被webpack处理的,它们会被直接复制到最终的打包目录下面,且必须使用绝对路径来引用这些文件。写法:"/static/pdf/show.pdf",/即表示public文件夹(需略去public);

文档:

https://www.npmjs.com/package/pdfh5

安装:

javascript 复制代码
npm install pdfh5 --legacy-peer-deps
npm install --save canvas --legacy-peer-deps
html 复制代码
<script setup>
import { ref } from 'vue'
import Pdfh5 from 'pdfh5'
import 'pdfh5/css/pdfh5.css'

// pdfh5实例
const pdfh5 = ref(null)

// pdf预览
const handlePreview = () => {
  pdfh5.value = new Pdfh5('#demo', {
    pdfurl: '/static/1.pdf',  // 读取本地的pdf文件需要放到public下static文件夹中
  })
}

const beforeRead = (file) => {
  if (file.type == 'application/pdf') {
    // 使用类型化数组(Uint8Array)可以提高内存使用率。
    let reader = new FileReader()
    reader.readAsArrayBuffer(file)
    reader.onload = (loadEvent) => {
      let arrayBuffer = loadEvent.target.result
      pdfh5.value = new Pdfh5('#demo', {
        data: arrayBuffer,
      })
    }
  }
  return true
}

const afterRead = (file) => {
  // file.content是BASE64
  // PDF数据是BASE64编码的,请先使用atob()将其转换为二进制字符串
  // const data = atob(file.content.replace('data:application/pdf;base64,', '')) // 去除BASE64编码的头
  // pdfh5.value = new Pdfh5('#demo', {
  //   data
  // })
}
</script>

<template>
  <div class="home-page">
    <header class="header">
      <van-button type="default" @click="handlePreview" style="margin-right: 8px;">通过pdfurl预览</van-button>
      <van-uploader accept=".pdf" :before-read="beforeRead" :after-read="afterRead">
        <van-button icon="plus" type="primary">通过pdf文件流预览</van-button>
      </van-uploader>

    </header>
    <main class="main">
      <div id="demo"></div>
    </main>
  </div>
</template>

<style>
.home-page {
  width: 100%;
  height: 100%;

  .header {
    height: 50px;
    display: flex;
    align-items: center;
  }

  .main {
    height: calc(100% - 50px);
  }

  #demo {
    width: 100%;
    height: 100%;
  }
}
</style>
相关推荐
CHANG_THE_WORLD17 小时前
PDFium导出pdf 图像
开发语言·c++·pdf
momo_al17 小时前
Umi-OCR制作双层PDF
pdf·ocr
励志成为美貌才华为一体的女子17 小时前
pdf解析工具---Miner-u 本地部署记录
学习·pdf
reasonsummer17 小时前
【办公类-115-02】20251018信息员每周通讯上传之文字稿整理(PDF转docx没有成功)
python·pdf
top_designer20 小时前
告别“静态”VI手册:InDesign与AE打造可交互的动态品牌规范
设计模式·pdf·交互·vi·工作流·after effects·indesign
2501_929382652 天前
MobiOffice解锁高级功能版 v15.9.57971 安卓手机doc, docx ppt, .pptx pdf办公软件
智能手机·pdf·powerpoint·wps
CodeCraft Studio2 天前
国产化PDF处理控件Spire.PDF教程:如何在 C# 中从 HTML 和 PDF 模板生成 PDF
pdf·c#·html·.net·spire.pdf·pdf文档开发·html创建模板pdf
E_ICEBLUE2 天前
高效压缩 PDF 文件大小(3 大实用的 Python 库)
python·pdf
技术钱2 天前
vue3 封装图片上传预览组件支持docx、excel、pdf、图片、txt格式
vue.js·pdf·excel
xingxing_F2 天前
PDF Protector for mac PDF文档加密解密工具
macos·pdf