Created
December 6, 2019 14:05
-
-
Save virendra656/8352198f10ef55db30de3e89bacfc07c to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
'use strict' | |
const chromium = require('chrome-aws-lambda') | |
exports.handler = async (event, context, callback) => { | |
console.log("generating pdf"); | |
const html = ` | |
<html lang="en"> | |
<body> | |
<h1>Hello, world!</h1> | |
</body> | |
</html>` | |
// 3. Open puppeteer | |
let browser = null | |
try { | |
browser = await chromium.puppeteer.launch({ | |
args: chromium.args, | |
defaultViewport: chromium.defaultViewport, | |
executablePath: await chromium.executablePath, | |
headless: chromium.headless | |
}) | |
const page = await browser.newPage() | |
page.setContent(html) | |
// 4. Create pdf file with puppeteer | |
const pdf = await page.pdf({ | |
format: 'A4', | |
printBackground: true, | |
margin: { top: '1cm', right: '1cm', bottom: '1cm', left: '1cm' } | |
}) | |
console.log("generating done"); | |
console.log(pdf.toString('base64')); | |
return callback(null, { | |
statusCode: 200, | |
headers: { | |
'Access-Control-Allow-Origin': '*', | |
'Access-Control-Allow-Credentials': false, | |
}, | |
body: pdf.toString('base64') | |
}) | |
console.log(pdf); | |
// 5. Return PDf as base64 string | |
const response = { | |
headers: { | |
'Content-type': 'application/json' | |
}, | |
statusCode: 200, | |
body: pdf.toString('base64') | |
} | |
context.succeed(response) | |
} catch (error) { | |
return context.fail(error) | |
} finally { | |
if (browser !== null) { | |
await browser.close() | |
} | |
} | |
} | |
{ | |
"name": "aws-lambda-html-pdf-master", | |
"version": "1.0.0", | |
"description": "An easy to deploy implementation of the html-pdf package for AWS Lambda", | |
"main": "index.js", | |
"dependencies": { | |
"chrome-aws-lambda": "1.18.1", | |
"pg": "7.11.0", | |
"pg-hstore": "2.3.2", | |
"puppeteer-core": "1.18.1" | |
}, | |
"devDependencies": { | |
"serverless": "1.40.0", | |
"serverless-apigw-binary": "0.4.4", | |
"serverless-offline": "4.9.4" | |
}, | |
"scripts": { | |
"test": "echo \"Error: no test specified\" && exit 1" | |
}, | |
"keywords": [], | |
"author": "", | |
"license": "ISC" | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment