node.js - 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);
解决方案
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.
推荐阅读
- javascript - Vue js 只允许输入 2 位小数而无需四舍五入
- ios - 多个日期选择器 - 使用已更改的值
- javascript - Jquery Anchor Tag 不打开一个弹出窗口
- coveo - 在进行智能发布时,Sitecore 项目未在 Coveo 中建立索引
- arduino - Arduino Esp8266 LittleFS 上传更新
- python - Kivy:如何填充嵌套的回收视图,它位于 Kivy 的弹出窗口中?
- python-3.x - 如何一次删除所有角色(Discord.py 1.4.1)
- android - 保护android库源代码的最佳实践?
- regex - Amazon QuickSight 使用计算字段从逗号分隔的未排序字符串中提取字符串
- html - 如何在html表单上方覆盖div?