简体   繁体   English

在Firebase云功能上使用PDFMake的承诺

[英]Using promises with PDFMake on Firebase Cloud Functions

I am using PDFMake (a variant of PDFKit ) to generate PDFs on Firebase Cloud Functions using a realtime database trigger. 我使用PDFMake(的变体PDFKit )生成的使用实时数据库触发器火力地堡云功能的PDF文件。 The function gets all relevant data from the database and then passes it to the function that is supposed to generate the PDF. 该函数从数据库获取所有相关数据,然后将其传递给应该生成PDF的函数。

All this is done using Promises. 所有这些都是使用Promises完成的。 Everything works fine until the point where the PDF is actually generated. 一切正常,直到实际生成PDF。

Here's the code in my main event listener: 这是我的主要事件监听器中的代码:

exports.handler = (admin, event, storage) => {
  const quotationData = event.data.val();
  // We must return a Promise when performing async tasks inside Functions
  // Eg: Writing to realtime db
  const companyId = event.params.companyId;
  settings.getCompanyProfile(admin, companyId)
  .then((profile) => {
    return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
  })
  .then(() => {
    console.log('Generation Successful. Pass for email');
  })
  .catch((err) => {
    console.log(`Error: ${err}`);
  });
};

To generate the PDF, here's my code: 要生成PDF,这是我的代码:

exports.generatePDF = (fonts, companyInfo, quotationData, storage) => {
  const printer = new PdfPrinter(fonts);
  const docDefinition = {
    content: [
      {
        text: [
          {
            text: `${companyInfo.title}\n`,
            style: 'companyHeader',
          },
          `${companyInfo.addr_line1}, ${companyInfo.addr_line2}\n`,
          `${companyInfo.city} (${companyInfo.state}) - INDIA\n`,
          `Email: ${companyInfo.email} • Web: ${companyInfo.website}\n`,
          `Phone: ${companyInfo.phone}\n`,
          `GSTIN: ${companyInfo.gst_registration_number}  • PAN: AARFK6552G\n`,
        ],
        style: 'body',
         //absolutePosition: {x: 20, y: 45}
      },
    ],
    styles: {
      companyHeader: {
        fontSize: 18,
        bold: true,
      },
      body: {
        fontSize: 10,
      },
    },
    pageMargins: 20,
  };
  return new Promise((resolve, reject) => {
    // const bucket = storage.bucket(`${PROJECT_ID}.appspot.com`);
    // const filename = `${Date.now()}-quotation.pdf`;
    // const file = bucket.file(filename);
    // const stream = file.createWriteStream({ resumable: false });
    const pdfDoc = printer.createPdfKitDocument(docDefinition);
    // pdfDoc.pipe(stream);

    const chunks = [];
    let result = null;

    pdfDoc.on('data', (chunk) => {
      chunks.push(chunk);
    });
    pdfDoc.on('error', (err) => {
      reject(err);
    });
    pdfDoc.on('end', () => {
      result = Buffer.concat(chunks);
      resolve(result);
    });
    pdfDoc.end();
  });
};

What could be wrong here that is preventing the promise and thereby the quotation code to be executed as intended? 这里可能出现的问题是阻止承诺,从而使报价代码按预期执行?

On firebase log, all I see is Function execution took 3288 ms, finished with status: 'ok' 在firebase日志中,我看到的是Function execution took 3288 ms, finished with status: 'ok'

Based on the execution time and lack of errors, it looks like you're successfully creating the buffer for the PDF but you're not actually returning it from the function. 根据执行时间和缺少错误,看起来您正在为PDF成功创建缓冲区,但实际上并没有从函数中返回它。

.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(() => {
  console.log('Generation Successful. Pass for email');
})

In the code above, you're passing the result to the next then block, but then returning undefined from that block. 在上面的代码,你传递结果到下一次then块,但随后恢复从该块不确定的。 The end result of this Promise chain will be undefined. 这个Promise链的最终结果将是未定义的。 To pass the result through, you'd want to return it at the end of the Promise chain: 要通过结果,您需要在Promise链的末尾返回它:

.then((profile) => {
  return quotPdfHelper.generatePDF(fonts, profile, quotationData, storage);
})
.then(buffer => {
  console.log('Generation Successful. Pass for email');
  return buffer;
})

I'm trying to experiment generating pdf using firebase cloud function but I am blocked about defining fonts parameter. 我正在尝试使用firebase云功能生成pdf,但我被阻止了关于定义fonts参数。 Here's my definition: 这是我的定义:

var fonts = {
    Roboto: {
        normal: './fonts/Roboto-Regular.ttf',
        bold: './fonts/Roboto-Bold.ttf',
        italics: './fonts/Roboto-Italic.ttf',
        bolditalics: './fonts/Roboto-BoldItalic.ttf'
    }
};

I've created a fonts folder which contain the for above files. 我创建了一个包含上述文件的字体文件夹。 However wherever I set the fonts folder (in root, in functions folder or in node_modules folder), I get the error 'no such file or directory' when deploying functions. 但是无论我在哪里设置fonts文件夹(在root,在functions文件夹或node_modules文件夹中),我在部署函数时都会收到错误'no such file or directory'。 Any advice would be very much appreciated. 任何建议将非常感谢。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM