pdf-lib添加水印 文件体积增大

在使用pdf-lib对文档进行前端水印 添加时,发现使用自定义的字体文件;导致PDF文档增大了很多。
在查看官方解释后发现 添加{subset: true}就能缩小文件体积。

const customFont = await pdfDoc.embedFont(fontBuffer,{subset:true});
const fs = require('fs')
const { PDFDocument, rgb } = require('pdf-lib')
const fontkit = require('@pdf-lib/fontkit')

async function generatePDF(){
    // This should be a Uint8Array or ArrayBuffer
// This data can be obtained in a number of different ways
// If you're running in a Node environment, you could use fs.readFile()
// In the browser, you could make a fetch() call and use res.arrayBuffer()
    const fontBytes = fs.readFileSync('./font/pingfang.ttf')

// Create a new PDFDocument
    const pdfDoc = await PDFDocument.create()

// Register the `fontkit` instance
    pdfDoc.registerFontkit(fontkit)

// Embed our custom font in the document
    // this line works well
//     const customFont = await pdfDoc.embedFont(fontBytes)

    // this does not work properly
    const customFont = await pdfDoc.embedFont(fontBytes,{subset:true})


// Add a blank page to the document
    const page = pdfDoc.addPage()

// Create a string of text and measure its width and height in our custom font
    const text = '中文字体你行不行This is text in an embedded font!'
    const textSize = 35
    const textWidth = customFont.widthOfTextAtSize(text, textSize)
    const textHeight = customFont.heightAtSize(textSize)

// Draw the string of text on the page
    page.drawText(text, {
        x: 40,
        y: 450,
        size: textSize,
        font: customFont,
        color: rgb(0, 0.53, 0.71),
    })

// Draw a box around the string of text
    page.drawRectangle({
        x: 40,
        y: 450,
        width: textWidth,
        height: textHeight,
        borderColor: rgb(1, 0, 0),
        borderWidth: 1.5,
    })

// Serialize the PDFDocument to bytes (a Uint8Array)
    const pdfBytes = await pdfDoc.save()
    fs.writeFileSync('./dist/pdflib-test.pdf',pdfBytes)

// For example, `pdfBytes` can be:
//   • Written to a file in Node
//   • Downloaded from the browser
//   • Rendered in an <iframe>
}

generatePDF()

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值