要实现在AWS Lambda中使用PhantomJS来支持多语言字体,你可以按照以下步骤进行操作:
const phantom = require('phantom');
const fs = require('fs');
exports.handler = async (event, context) => {
const fontPath = '/var/task/fonts/';
const fontName = 'arial.ttf';
const html = '你好世界
';
const instance = await phantom.create();
const page = await instance.createPage();
// 设置自定义字体路径
await page.property('customHeaders', {
'Accept-Encoding': 'identity',
'Content-Type': 'text/html; charset=utf-8',
'Accept-Language': 'en-US,en;q=0.9,zh-CN;q=0.8,zh;q=0.7',
'Accept': '*/*',
'Referer': '',
'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/67.0.3396.79 Safari/537.36',
});
await page.property('content', html);
// 设置字体
await page.property('paperSize', {
format: 'A4',
orientation: 'portrait',
margin: '1cm',
header: {
height: '1cm',
contents: phantom.callback(function(pageNum, numPages) {
return '';
})
},
footer: {
height: '1cm',
contents: phantom.callback(function(pageNum, numPages) {
return '';
})
}
});
await page.property('settings', {
loadImages: true,
localToRemoteUrlAccessEnabled: true,
webSecurityEnabled: false,
ignoreSslErrors: true,
javascriptEnabled: true,
resourceTimeout: 5000
});
// 注入自定义字体
await page.property('font', `${fontPath}${fontName}`);
// 保存为PDF
await page.render('output.pdf');
await instance.exit();
// 将生成的PDF上传到S3或其他目标
const pdfData = fs.readFileSync('output.pdf');
// 上传到S3
// ...
return {
statusCode: 200,
body: 'PDF生成成功'
}
};
以上示例代码演示了如何在PhantomJS中使用自定义字体生成PDF文件。你可以根据自己的需要进行修改和调整。
请注意,在将代码部署到AWS Lambda之前,你需要将PhantomJS二进制文件和自定义字体文件打包到Lambda函数的部署包中。这可以通过在本地创建一个压缩文件,并将所有文件和目录添加到其中来完成。上传部署包后,Lambda函数将可以访问这些文件。
上一篇:AWS Lambda 抛出的错误信息为:“读取:对等方重置了连接”。
下一篇:AWS Lambda php spawn EACCESS: AWS Lambda PHP生成EACCESS的错误。