如何在Apps脚本中使用外部Javascript库(PDF库)



我需要修改应用程序脚本应用程序上的PDF。为此,我想使用JS库:PDF-LIB

我的代码:

eval(UrlFetchApp.fetch("https://unpkg.com/pdf-lib/dist/pdf-lib.js").getContentText());
function modifyPdf() {
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const existingPdfBytes = UrlFetchApp.fetch(url).getContentText();
const pdfDoc = PDFDocument.load(existingPdfBytes)
const helveticaFont = pdfDoc.embedFont(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,
color: rgb(0.95, 0.1, 0.1),
rotate: degrees(-45),
})
const pdfBytes = pdfDoc.save()
}

当我执行动作modifyPDF时,我有:

Erreur  
ReferenceError: PDFDocument is not defined
modifyPdf   @ modifie_pdf.gs:7

你知道我如何在我的Apps脚本应用程序上导入js-lib吗?

  • eval派生的全局变量命名空间是PDFLib。因此,像rgbdegreesPDFDocument这样的所有变量都是这个对象的键,应该这样引用。

  • 库中的大多数函数都使用promises,尽管应用程序脚本在功能上不支持CCD_7功能,但在语法上支持它。因此,应该使用asyncawait,否则只会得到promise对象,而不会得到实际的documentfont

  • 库使用setTimeout,这在应用程序脚本中不可用。我使用Utilities.sleep来模拟它的行为。

  • 15返回CCD_ 16而不是CCD_。使用getContent()获取byte[],并将其转换为Uint8Array

eval(UrlFetchApp.fetch("https://unpkg.com/pdf-lib/dist/pdf-lib.js").getContentText());
/*+++simulate setTimeout*/setTimeout = (func, sleep) => (Utilities.sleep(sleep),func())
async function modifyPdf() {
const url = 'https://pdf-lib.js.org/assets/with_update_sections.pdf'
const existingPdfBytes = new /*cast to uint8*/Uint8Array(/*returns byte[]*/UrlFetchApp.fetch(url).getContent/*---Text*/());
/*+++ simulate import*/const { PDFDocument, StandardFonts, rgb, degrees} = PDFLib;
const pdfDoc = /*+++*/await PDFDocument.load(existingPdfBytes)
const helveticaFont = /*+++*/ await pdfDoc.embedFont(StandardFonts.Helvetica)
const pages = pdfDoc.getPages()
const firstPage = pages[0]
const { width, height } = firstPage.getSize()
firstPage.drawText(`This text was added with JavaScriptnn${' '.repeat(10)}(Google Apps script)!`, {
x: width/10 + 60,
y: height/10 + 120,
size: 40,
font: helveticaFont,
color: rgb(0.1, 0.1, 0.1),
rotate: degrees(50),
opacity: 0.5,
})
const pdfBytes = /*+++*/await pdfDoc.save();
/*+++*/DriveApp.createFile(Utilities.newBlob(pdfBytes).setName('newpdf from apps script'))
}

最新更新