Vue3前端h5移动端页面预览PDF使用pdfjs-dist,添加自定义文本水印

这篇具有很好参考价值的文章主要介绍了Vue3前端h5移动端页面预览PDF使用pdfjs-dist,添加自定义文本水印。希望对大家有所帮助。如果存在错误或未考虑完全的地方,请大家不吝赐教,您也可以点击"举报违法"按钮提交疑问。

pdfjs-dist版本

pnpm i pdfjs-dist@2.5.207文章来源地址https://www.toymoban.com/news/detail-802489.html


<script setup>
import {ref, onMounted, watch} from 'vue'
import { useRoute } from "vue-router";
import * as pdfjsLib from 'pdfjs-dist'

const route = useRoute()
// !
pdfjsLib.GlobalWorkerOptions.workerSrc = new URL('pdfjs-dist/build/pdf.worker.js', import.meta.url).href
const numPages = ref(0) // pdf一共多少页
const nums = ref(1) // 循环加载的参数
const currentNum = ref(1) // 当前页数
const jumpNum = ref(1)  // 输入框需要跳转的页数
const inpDisabled = ref(true) // pad文件没有加载完所有页数则禁用
const imgSrcList = ref([]) // 存储paf每一页
const watermarkPoint = [
  [-120, -66], [-120, 66], [120, -66], [120, 66]
] // 水印坐标
let pageHeight = null // 每一页高度
let pdfWrap = null
let isChangeCurrentNum = false

const query = new URLSearchParams(route.fullPath.split('?')[1]) // 从url地址栏获取水印文本信息
const watermarkText = query.get('text') // 自定义的水印文本

// url为pdf链接
const loadingTask = pdfjsLib.getDocument(query.get('url'))

// dom加载之后
onMounted(() => {
  pdfWrap = document.getElementById('pdf')
  togglePage(nums.value)
})

watch(() => nums.value, (num) => {
  if (num <= numPages.value) {
    togglePage(num)
  } else {
    inpDisabled.value = false
  }
})

async function togglePage(pageNumber = 1) {
  loadingTask.promise.then(function(pdf) {
    numPages.value = pdf.numPages

    pdf.getPage(pageNumber).then((page) => {

      const scale = 0.1 // 关键!如果清晰度不行,慢慢调整这个数值。
      let viewport = page.getViewport({ scale });
      let scaleViewport = page.getViewport({ scale: window.screen.width / viewport.width });


      let canvas = document.createElement('canvas');

      let context = canvas.getContext('2d');

      canvas.width = scaleViewport.width;
      canvas.height = scaleViewport.height;
			
		// 只赋值一次	
      !pageHeight && (pageHeight = (scaleViewport.height * scale).toFixed(2))

      let renderContext = {
        canvasContext: context,
        viewport: scaleViewport,
      };
      let renderTask = page.render(renderContext);
      renderTask.promise.then(() => {
      // 设置自定义文本样式
        context.font = `${16 / scale}px Microsoft Yahei`;
        context.fillStyle = 'rgba(0, 0, 0, .1)'
        context.textAlign = 'center'
        context.textBaseline = 'middle'

		// 设置自定义文本位于每一页pdf的空间位置
        watermarkPoint.forEach(point => {
          context.translate( ((scaleViewport.width * scale / 2) + point[0]) / scale, ((scaleViewport.height * scale / 2) + point[1]) / scale )
          context.rotate(-30 * Math.PI / 180)
          context.fillText(watermarkText, 0, 0)
          context.resetTransform()
        })
		// 导出canvas图片到图片列表,循环渲染
        imgSrcList.value.push(canvas.toDataURL('img/png'))

        nums.value++
      });
    });
  }, function (reason) {
    console.error(reason);
  });
}

function goToPage(num) {
  pdfWrap.scrollTo(0, num === 1 ? 0 : pageHeight * num - pageHeight)
  currentNum.value = num
  isChangeCurrentNum = true
}

function handleScroll(e) {
  if (!isChangeCurrentNum) {
    const current = e.target.scrollTop / pageHeight
    currentNum.value = Math.ceil(current === 0 ? 1 : current)
  }
  isChangeCurrentNum = false
}

function handleBeforePage() {
  currentNum.value = currentNum.value - 1 <= 0 ? 1 : currentNum.value - 1
  goToPage(currentNum.value)
  isChangeCurrentNum = true
}
function handleNextPage() {
  currentNum.value = currentNum.value + 1 >= numPages.value ? numPages.value : currentNum.value + 1
  goToPage(currentNum.value)
  isChangeCurrentNum = true
}
</script>

<template>
  <div>
    <div class="overflow-y-scroll" id="pdf" style="height: calc(100vh - 60px);" @scroll="handleScroll">
      <img v-for="src in imgSrcList" :src="src" alt="">
    </div>
    <div v-if="imgSrcList.length !== 0" class="operation-box">
      <div class="operation">
        <div class="page-num-info">
          <span>{{ currentNum }}</span>
          /
          <span v-if="!inpDisabled">{{ numPages }}</span>
          <van-loading style="margin-left: 3px;margin-top: 3px" v-else size="14" type="spinner" />
        </div>
        <van-icon @click="handleBeforePage" name="arrow-left" />
        <div class="jump-box" v-if="!inpDisabled">
          <div class="inp-box">
            跳转 <input style="width: 60px;text-align: center;color: black" type="number" v-model="jumpNum" /></div>
          <div @click.stop="goToPage(jumpNum)">确定</div>
        </div>
        <div v-else class="tips">文件正在加载中..跳转功能暂不可用</div>
        <van-icon @click="handleNextPage" name="arrow" />
        <van-icon @click="goToPage(1)" class="home" name="wap-home" size="20" />
      </div>
    </div>
  </div>
</template>

<style scoped lang="less">
.operation-box {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  .operation {
    display: flex;
    align-items: center;
    justify-content: space-around;
    background-color: #404040;
    width: 100%;
    color: #fff;
    padding: 10px 20px;
    border-radius: 30px;
    box-sizing: border-box;
    .jump-box {
      flex: 1;
      font-size: 14px;
      display: flex;
      align-items: center;
      justify-content: center;
      .inp-box {
        margin-right: 5px;
      }
    }
    .tips {
      flex: 1;
      text-align: center;
      font-size: 14px;
    }
    .page-num-info {
      display: flex;
      justify-content: center;
      align-items: center;
      font-size: 14px;
    }
    .page-num-info, .home {
      width: 60px;
      text-align: center;
    }
  }
}
</style>

到了这里,关于Vue3前端h5移动端页面预览PDF使用pdfjs-dist,添加自定义文本水印的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处: 如若内容造成侵权/违法违规/事实不符,请点击违法举报进行投诉反馈,一经查实,立即删除!

领支付宝红包赞助服务器费用

相关文章

  • vue3管理系统中后台返回pdf格式的文件流,前端如何预览?以及uniapp微信小程序中后台返回的base64位的pdf文件如何预览?

    vue3管理系统中后台返回pdf格式的文件流,前端如何预览?以及uniapp微信小程序中后台返回的base64位的pdf文件如何预览?

    后台返回的是base64格式的pdf文件,首先需要解析base64文件的插件 image-tools 1 安装并引入插件 2 封装预览pdf的函数 3 调用接口获取数据

    2024年01月18日
    浏览(61)
  • 前端vue3实现本地及在线文件预览(含pdf/txt/mp3/mp4/docx/xlsx/pptx)

    前端vue3实现本地及在线文件预览(含pdf/txt/mp3/mp4/docx/xlsx/pptx)

    (一)微软office免费预览( 推荐 ) 支持doc/docx/xls/xlsx/ppt/pptx等多种office文件格式的免费预览 (二)XDOC文档预览云服务  移动端和PC端无插件预览PDF、OFD、Word、WPS等多种格式文档 本地或内网预览需要借助插件实现,pdf、mp3、mp4等主要靠原生标签或浏览器自带功能,尽量减少

    2024年02月05日
    浏览(26)
  • vue3 电子书 pdf转图片 pdf实现翻页效果 pdfjs-dist、turn.js电子书翻页效果

    vue3 电子书 pdf转图片 pdf实现翻页效果 pdfjs-dist、turn.js电子书翻页效果

    下载 turn.js 这里使用的是  turn4  ,需要下载到本地引入,通过npm下载会报错可以到官网下载,也可以直接在本博客下,已经上传到博客 导入文件之前先创建   vue.config.js 适配一下jquery ,创建好文件以后,把以下代码复制进去 回到vue页面,导入以下文件 参考博客:GitHub -

    2024年02月16日
    浏览(24)
  • 在uni中使用vue3写h5的pdf导出

    先安装依赖 把dom转canvas,屏幕截图基于 DOM,因此可能不是 100% 准确到真实表示,因为它不会制作实际的屏幕截图,而是根据页面上可用的信息构建屏幕截图。 components/pdf  创建pdf文件夹 在main文件中引入 在需要的页面绑定id  事件

    2024年02月16日
    浏览(3)
  • 前端使用vue-pdf、pdf-lib、canvas 给PDF文件添加水印,并预览与下载

    前端使用vue-pdf、pdf-lib、canvas 给PDF文件添加水印,并预览与下载

    原理就是给显示pdf 的容器增加一层水印遮罩层 下载: 通过url获取pdf文件的arrarybuffer文件流 将arraybuffer数据转成pdf文档 添加水印字体(内置/自定义) 为每页pdf添加文字水印 保存pdf文件的unit64Arrary文件流 预览: 创建canvas容器(用于显示水印文字) 创建水印canvas 将水印canv

    2024年01月24日
    浏览(9)
  • Vue3PDF预览(vue3-pdf-app)

    Vue3PDF预览(vue3-pdf-app)

    vue3-pdf-app 插件 网站预览PDF最佳且最简单的方式: 如果需要自定义网页内预览,可以采用本PDF预览组件(PDFViewer.vue) 本组件基于  vue3-pdf-app@1.0.3  插件进行二次封装,更适合日常使用需要! 插件支持功能包括但不限于:缩放、旋转、全屏预览、打印、下载、内容检索、dar

    2023年04月21日
    浏览(8)
  • uniapp使用H5实现预览pdf文件

    uniapp使用H5实现预览pdf文件

    下载后把压缩包解压到自己的项目的static文件夹下的pdf文件下,如图 新建一个文件名为filePreview.vue 在下载文件事件 1.如果预览文件是乱码情况或者在pc上报ocale.properties的请求返回404 解决:就是pdfjs下载版本有问题,下载以前的老版本 2.如果出现跨域问题直接修改源代码在v

    2024年02月09日
    浏览(7)
  • 前端实现PDF预览【vue】

    前言:项目中提出这样一个需求,在移动端H5页面预览pdf功能。pdf文件由后端返回的一个地址,前端实现展示预览pdf文件 在此仅提供两种方法: 一、使用iframe标签通过src属性直接展示pdf文件         坑点:兼容比较差,PC端能正常展示,移动端会出现空白的问题 二、使用第

    2024年01月16日
    浏览(9)
  • vue前端预览pdf并加水印、ofd文件,控制打印、下载、另存,vue-pdf的使用方法以及在开发中所踩过的坑合集

    vue前端预览pdf并加水印、ofd文件,控制打印、下载、另存,vue-pdf的使用方法以及在开发中所踩过的坑合集

    根据公司的实际项目需求,要求实现对pdf和ofd文件的预览,并且需要限制用户是否可以下载、打印、另存pdf、ofd文件,如果该用户可以打印、下载需要控制每个用户的下载次数以及可打印的次数。正常的预览pdf很简单,直接调用浏览器的预览就可以而且功能也比较全,但是一

    2024年02月16日
    浏览(64)
  • vue3 实现预览pdf的几种方式(vue3-pdf, iframe流展示,vue-office/pdf)

    功能描述: 要实现菜单(二级)绑定文件,并进行预览(点击菜单即触发),支持文件上传下载(绑定菜单),文件以byte[]形式保存到数据库(至于为什么不用文件存储系统,因为这是领导定的 =,= 而且这个功能比较小,数据也不多,成本有限),同时,要解析pdf文件里的内

    2024年02月16日
    浏览(5)

觉得文章有用就打赏一下文章作者

支付宝扫一扫打赏

博客赞助

微信扫一扫打赏

请作者喝杯咖啡吧~博客赞助

支付宝扫一扫领取红包,优惠每天领

二维码1

领取红包

二维码2

领红包