微信小程序预览PDF、H5预览PDF、网页预览PDF,并添加专属文字水印

下载PDF.js

点击PDF.js下载地址

在这里插入图片描述

引入预览PDF 文件

// const url = new URL("./1.pdf", import.meta.url).href // 在本地项目获取pdf
// const url = "https://xxxx/05d833041f.pdf" // 在线上链接获取pdf
const url = query.get('url') // 在地址栏获取pdf
const query = new URLSearchParams(window.location.search.split('?')[1])
const watermarkText = query.get('text') || 'xxx' // 添加水印
const baseUrl = import.meta.env.BASE_URL; // 如果有更改基本路径则添加

<!-- 注意引入路径是否正确 -->
<iframe :src="`${baseUrl}/pdfjs-dist/web/viewer.html?file=${url}&watermarkText=${watermarkText}`" width="100%" height="100%" frameborder="0"></iframe>

AddWatermark.js 添加水印的功能

(() => {
    // 添加水印
    window.AddWatermark = (ctx, that) => {
        // 水印数据 start
        const watermarkPoint = [
            [45, 35], [310, 35], [45, 165], [310, 165],
        ] // 水印坐标
        const query = new URLSearchParams(window.location.search.split('?')[1])
        let watermarkText = query.get('watermarkText')

        // 水印数据 end
        // 添加水印
        const scale = that.scale
        ctx.font = `${16 / scale}px Microsoft Yahei`;
        // ctx.fillStyle = 'rgba(255, 0, 0, 1)'
        ctx.fillStyle = 'rgba(0, 0, 0, .1)'
        ctx.textAlign = 'center'
        ctx.textBaseline = 'middle'
        watermarkPoint.forEach(point => {
            ctx.translate( point[0] / scale,  point[1] / scale )
            ctx.rotate(-30 * Math.PI / 180)
            ctx.fillText(watermarkText, 0, 0)
            ctx.resetTransform()
        })
    }
})()

viewer.html引入添加水印的js

/pdfjs-dist/web/viewer.html

<!-- 注意引入路径是否正确 -->
<script src="../js/AddWatermark.js" type="module"></script>

更改/pdfjs-dist/web/viewer.mjs文件

  • 注释掉校验
// validateFileURL(file);
  • 搜索“await this.#renderDrawLayer();”关键字
    在这里插入图片描述
// 添加水印
AddWatermark(ctx, this)

使用的PDF.js版本

4.5.136

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Amodoro

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值