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>
相关推荐
wh39331 小时前
使用Python将PDF转换成word、PPT
python·pdf·word
开开心心就好13 小时前
免费PDF处理软件,支持多种操作
运维·服务器·前端·spring boot·智能手机·pdf·电脑
念九_ysl17 小时前
Java 使用 OpenHTMLToPDF + Batik 将含 SVG 遮罩的 HTML 转为 PDF 的完整实践
java·开发语言·pdf
一头生产的驴1 天前
java整合itext pdf实现自定义PDF文件格式导出
java·spring boot·pdf·itextpdf
开开心心就好2 天前
批量PDF转换工具,一键转换Word Excel
开发语言·前端·学习·pdf·电脑·word·excel
老家的回忆3 天前
jsPDF和html2canvas生成pdf,组件用的elementplus,亲测30多页,20s实现
前端·vue.js·pdf·html2canvas·jspdf
Vertira3 天前
pdf 合并 python实现(已解决)
前端·python·pdf
十一0829933 天前
【PDF-XSS攻击】springboot项目-上传文件-解决PDF文件XSS攻击
spring boot·pdf·xss
qq_393828223 天前
PDF的图片文字识别工具
windows·pdf·电脑·软件需求·图片处理
wsxqaz3 天前
浏览器原生控件上传PDF导致hash值不同
算法·pdf·哈希算法