如何根据 HTTP 请求 firebase 函数生成 pdf?

How to generate a pdf as a result of HTTP request firebase function?

如何使用 pdfmake 生成 pdf 作为 HTTP 请求 firebase 函数的结果?

假设我有以下 JSON

{
  "user" : "John Doe",
  "booksOwned":[
      {
        "title":"Fancy Coffins to Make Yourself",
        "author":"Dale L. Power"
      },
      {
        "title":"Knitting With Dog Hair",
        "author":"K Crolius"
      },
      {
        "title":"Everything I Want to Do is Illegal",
        "author":"Joel-Salatin"
      }
    ]
}

我想要一个 PDF 来问候用户并在 table 中列出所有书籍。这应该是我用这个 JSON 调用 firebase 函数时的结果。 我如何使用 pdfmake 做到这一点?

首次安装pdfmake

npm install pdfmake

并使用以下函数,请注意您必须根据需要调整 docDefinition

exports.getPDF = functions.https.onRequest(async (req, res) => {
    //...
    var data = JSON.parse(req.query.json); //asume json is given as parameter
    //fonts need to lay in the functions directory
    var fonts = {
        Roboto: {
            normal: './fonts/Roboto-Regular.ttf',
            bold: './fonts/Roboto-Medium.ttf',
            italics: './fonts/Roboto-Italic.ttf',
            bolditalics: './fonts/Roboto-MediumItalic.ttf'
        },
    };

    var PdfPrinter = require('pdfmake'); //needs to installed via "npm install pdfmake"
    var printer = new PdfPrinter(fonts);

    var docDefinition ={
content: [
        
        {text: 'Hello User:', style: 'header'},
        {
            table: {
                body: [
                    ['book', 'author',],
                    ['book1','author1'],
                    ['book2','author2'],
                    ['book3','author3']
                ]
            }
        }
    ]
}


    var options = {
        // ...
    }

    var pdfDoc = printer.createPdfKitDocument(docDefinition, options);
    pdfDoc.pipe(res.status(200));
    pdfDoc.end();

});