You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用pdf-lib获取并修改PDF元数据时遇PDFDocument未定义问题

解决PDFDocument is not defined错误
  • 错误原因:你使用的pdf-lib@1.4.0在浏览器环境中,PDFDocument并非全局直接暴露的变量,而是挂载在全局对象PDFLib之下的,直接调用PDFDocument会导致变量未定义的错误。

  • 修正后的完整代码:

<head>
    <meta charset="utf-8" />
    <script src="https://unpkg.com/pdf-lib@1.4.0"></script>
    <script src="https://unpkg.com/downloadjs@1.4.7"></script>
</head>

<body>
    <button onclick="get()">get</button>
</body>

<script>
    async function get() {
        const url = 'https://pdf-lib.js.org/assets/with_cropbox.pdf'
        const existingPdfBytes = await fetch(url).then(res => res.arrayBuffer())

        // 通过PDFLib全局对象访问PDFDocument
        const pdfDoc = await PDFLib.PDFDocument.load(existingPdfBytes, {
            updateMetadata: false
        })
        console.log('Title:', pdfDoc.getTitle())
        console.log('Author:', pdfDoc.getAuthor())
        console.log('Subject:', pdfDoc.getSubject())
        console.log('Creator:', pdfDoc.getCreator())
        console.log('Keywords:', pdfDoc.getKeywords())
        console.log('Producer:', pdfDoc.getProducer())
        console.log('Creation Date:', pdfDoc.getCreationDate())
        console.log('Modification Date:', pdfDoc.getModificationDate())
    };
</script>

</html>
  • 补充说明:若后续升级pdf-lib版本,部分新版本可能支持ES模块导入的方式,但针对你当前使用的1.4.0版本,上述修改即可解决问题。

内容的提问来源于stack exchange,提问作者vercapo

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 03:42:38