Created
January 22, 2026 12:48
-
-
Save bnski/20d8d60f78ab3d40ec70768dd7f74f03 to your computer and use it in GitHub Desktop.
URL / Route to PDF
This file contains hidden or 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
| import chromium from '@sparticuz/chromium'; | |
| import puppeteer from 'puppeteer-core'; | |
| import { S3Client, PutObjectCommand } from '@aws-sdk/client-s3'; | |
| const s3 = new S3Client({ region: process.env.AWS_REGION || 'us-east-1' }); | |
| export const handler = async (event) => { | |
| let browser = null; | |
| try { | |
| const { url, fileName } = event; | |
| const bucketName = process.env.S3_BUCKET_NAME; | |
| if (!url || !fileName || !bucketName) { | |
| throw new Error('Missing required parameters: url, fileName, or S3_BUCKET_NAME'); | |
| } | |
| browser = await puppeteer.launch({ | |
| args: chromium.args, | |
| defaultViewport: chromium.defaultViewport, | |
| executablePath: await chromium.executablePath(), | |
| headless: chromium.headless, | |
| }); | |
| const page = await browser.newPage(); | |
| await page.goto(url, { waitUntil: 'networkidle2' }); | |
| await page.emulateMediaType('print'); | |
| const pdfBuffer = await page.pdf({ | |
| format: 'Letter', | |
| printBackground: true, | |
| margin: { top: '0.25in', right: '0.25in', bottom: '0.25in', left: '0.25in' }, | |
| }); | |
| await s3.send(new PutObjectCommand({ | |
| Bucket: bucketName, | |
| Key: fileName, | |
| Body: pdfBuffer, | |
| ContentType: 'application/pdf', | |
| })); | |
| return { | |
| statusCode: 200, | |
| body: { | |
| message: 'PDF generated successfully', | |
| url: `https://${bucketName}.s3.amazonaws.com/${fileName}`, | |
| }, | |
| }; | |
| } catch (error) { | |
| console.error('PDF generation failed:', error); | |
| return { | |
| statusCode: 500, | |
| body: { error: error.message }, | |
| }; | |
| } finally { | |
| if (browser) { | |
| await browser.close(); | |
| } | |
| } | |
| }; |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
PDF Generator Lambda
Converts a webpage to PDF and uploads it to S3.
Runtime: Node.js 22.x (x86_64)
Environment Variables
S3_BUCKET_NAME— destination S3 bucketPayload
{ "url": "https://example.com", "fileName": "output.pdf" }Usage
cURL:
AWS SDK (Node.js):
AWS SDK (PHP/Laravel):
Dependencies
@sparticuz/chromiumpuppeteer-core@aws-sdk/client-s3