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

2 pdf pdflib libraries google-apps-script pdf.js

我需要在 Apps 脚本应用程序上修改 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()
}
Run Code Online (Sandbox Code Playgroud)

当我执行该功能时,modifyPDF我有:

Erreur  
ReferenceError: PDFDocument is not defined
modifyPdf   @ modifie_pdf.gs:7
Run Code Online (Sandbox Code Playgroud)

您知道如何在我的 Apps 脚本应用程序中导入 js 库吗?

The*_*ter 5

  • eval使用的全局变量命名空间是PDFLib. 因此,所有变量(如rgbdegrees、 )PDFDocument都是该对象的键,并且应该这样引用。

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

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

  • getContentText()返回text而不是binary content. 使用getContent()getbyte[]代替并将其强制转换为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 JavaScript\n\n${' '.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'))
}

Run Code Online (Sandbox Code Playgroud)