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>
相关推荐
马武寨山的猴子2 小时前
【MinerU】:一款将PDF转化为机器可读格式的工具——RAG加强(Docker版本)
人工智能·docker·容器·pdf·rag
萧鼎2 小时前
PDFMathTranslate:让数学公式在PDF翻译中不再痛苦
python·pdf
会功夫的李白2 小时前
PDF嵌入隐藏的文字
java·pdf·itext
陌殇殇1 天前
Java使用IText7动态生成带审批文本框的PDF文档
java·pdf
Ven%1 天前
VsCode如何使用默认程序打开word Excel pdf等文件
ide·vscode·pdf·编辑器
软件工程小施同学1 天前
计算机学报 2024年 区块链论文 录用汇总 附pdf下载
pdf·区块链
Sherlock Ma2 天前
PDFMathTranslate:基于LLM的PDF文档翻译及双语对照的工具【使用教程】
人工智能·pytorch·语言模型·pdf·大模型·机器翻译·deepseek
kadog2 天前
PubMed PDF下载 cloudpmc-viewer-pow逆向
前端·javascript·人工智能·爬虫·pdf
小墨宝2 天前
js 生成pdf 并上传文件
前端·javascript·pdf
热水养鲨鱼2 天前
Java实现HTML转PDF(deepSeekAi->html->pdf)
人工智能·pdf·html