首页 > 解决方案 > Pdf 未从 Aws Lambda 返回,但在本地工作正常

问题描述

我正在 nodejs 中创建一个无服务器应用程序,并使用命令“sls deploy”到 Aws Cloud。app 功能是在通过 get 端点访问时发回 pdf。我正在使用 pdfkit 创建 pdf 内容并根据 GET 请求返回它。这在本地运行良好。但是,当我将代码部署到 aws 时,我看到我的函数执行很好(云形成日志是这样说的),但是我的 pdf 返回为空。以下是我正在使用的 pdfkit 包

http://pdfkit.org/docs/getting_started.html

请让我知道,我该如何解决这个问题..

const serverless = require('serverless-http');
const express = require('express');
const bodyParser = require('body-parser');
const axios = require('axios');
const app = express();
const PDFDocument = require('pdfkit');
const fs = require('fs');

app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: true }))

app.get('/retrievePdf', (req, res) => {
var doc = new PDFDocument({size: "A4"});
doc.pipe(res);
doc.fontSize(16).text("Sample Pdf").moveDown();
doc.end();
});

app.listen(3000, function () {
console.log('listening on port 3000')
});

module.exports.handler = serverless(app);

标签: node.jsamazon-web-servicesserverless-frameworkaws-serverlessnode-pdfkit

解决方案


PDF generation in Lambda functions can be quite finicky as it typically requires and assumes a number of things from the runtime under which it runs (fonts, OS versions etc).

After some trial and error, in the end my approach to PDF generation in Lambda was to use wkhtmltopdf and upload the binary for it along with my function code, though my use case vastly preferred HTML formatting for the rendered document either way.

Note that in order to return binary documents through API Gateway you have to explicitly map certain content types as binary, else you're going to end up with a base64 encoded string response. An easy way to do this is to use a Serverless plugin such as serverless-apigw-binary and make sure you set the response content type correctly in your Lambda code.


推荐阅读