如何在Google Apps Script中引入并使用外部JavaScript库PDF-LIB?
在Google Apps Script中正确导入PDF-LIB并修复错误
你遇到的ReferenceError问题很常见——通过unpkg加载的pdf-lib并没有把PDFDocument直接暴露到全局作用域,而是把所有API封装在了pdfLib这个全局对象中。另外还有个容易踩的小坑:你处理PDF字节的方式不对,PDF是二进制文件,用getContentText()读取会损坏文件数据。
下面是修正后的完整代码,我标注了关键修改点:
eval(UrlFetchApp.fetch("https://unpkg.com/pdf-lib/dist/pdf-lib.js").getContentText()); async function modifyPdf() { // 1. 读取PDF二进制数据,改用getContent()而非getContentText() const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'; const existingPdfBytes = UrlFetchApp.fetch(url).getContent(); // 2. 所有pdf-lib的API都要通过pdfLib对象访问 const pdfDoc = await pdfLib.PDFDocument.load(existingPdfBytes); const helveticaFont = await pdfDoc.embedFont(pdfLib.StandardFonts.Helvetica); const pages = pdfDoc.getPages(); const firstPage = pages[0]; const { width, height } = firstPage.getSize(); firstPage.drawText('This text was added with JavaScript!', { x: 5, y: height / 2 + 300, size: 50, font: helveticaFont, // 3. rgb和degrees同样属于pdfLib对象 color: pdfLib.rgb(0.95, 0.1, 0.1), rotate: pdfLib.degrees(-45), }); const pdfBytes = await pdfDoc.save(); // 可选:如果需要保存处理后的PDF,可以添加代码存到Google Drive // DriveApp.createFile('modified.pdf', pdfBytes, 'application/pdf'); }
关键修改说明:
- API前缀:所有pdf-lib的构造函数、工具方法(比如
PDFDocument、StandardFonts、rgb、degrees)都要加上pdfLib.前缀,因为它们是pdfLib对象的属性。 - 二进制数据处理:用
getContent()替代getContentText(),确保读取的是原始二进制PDF数据,避免文件损坏。 - 异步处理:
PDFDocument.load()、embedFont()、save()都是异步方法,所以函数需要用async修饰,调用时加await(Google Apps Script已经支持async/await语法)。
第一次运行时Google会要求授权UrlFetchApp(如果用到Drive还会要求DriveApp权限),记得同意权限请求才能正常执行。
内容的提问来源于stack exchange,提问作者user18977096
相关产品推荐
相关产品推荐

