-
-
Save radermacher/5af6ac5013ac6be5dec71b4a9bd50789 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(); | |
| } | |
| } | |
| }; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment