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>
相关推荐
MaiTube&Maipdf16 小时前
麦瓜PDF 的安全分享流程图:从上传到权限控制
pdf·流程图
CodeCaptain16 小时前
【一】dify的知识库上传过相关的文件作为待引用的文档,这样已经与[原始语料 → 按“一文档一份 PDF”存 ObjectStore]同样的概念吗
人工智能·pdf·dify
放飞自我的Coder1 天前
【PDF拆分 Python拆分左右并排PDF】
python·pdf
开开心心_Every1 天前
发票批量打印工具支持双面预览页面方向设置
游戏·微信·pdf·华为云·excel·语音识别·googlecloud
AI刀刀1 天前
千问 文心 元宝 Kimi公式乱码
ai·pdf·豆包·deepseek·ds随心转
J_liaty2 天前
Java实现PDF添加水印的完整方案(支持灵活配置、平铺、多页策略)
java·开发语言·pdf
德育处主任Pro2 天前
『NAS』告别付费和广告,在群晖部署PDF工具箱-bentopdf
pdf·nas
索荣荣2 天前
Spring Boot 实现DOCX转PDF(基于docx4j的轻量级开源方案)
spring boot·后端·pdf
裴嘉靖2 天前
uni-app 打包后 PDF 无法生成问题完整解决方案
pdf·uni-app
wujian83112 天前
AI导出pdf方法
人工智能·pdf