https://github.com/maheshpaulj/serverless-pdf-generator
serverless-pdf-generator is a lightweight package that simplifies the process of generating PDFs from web pages in a serverless environment like Vercel. It utilizes Puppeteer and Chromium to render pages and generate high-quality PDFs.
https://github.com/maheshpaulj/serverless-pdf-generator
nextjs node-module node-package nodemodules npm pdf-generation react
Last synced: about 2 months ago
JSON representation
serverless-pdf-generator is a lightweight package that simplifies the process of generating PDFs from web pages in a serverless environment like Vercel. It utilizes Puppeteer and Chromium to render pages and generate high-quality PDFs.
- Host: GitHub
- URL: https://github.com/maheshpaulj/serverless-pdf-generator
- Owner: maheshpaulj
- License: mit
- Created: 2025-02-16T08:18:38.000Z (over 1 year ago)
- Default Branch: main
- Last Pushed: 2025-02-16T08:21:52.000Z (over 1 year ago)
- Last Synced: 2025-02-16T09:21:37.250Z (over 1 year ago)
- Topics: nextjs, node-module, node-package, nodemodules, npm, pdf-generation, react
- Language: TypeScript
- Homepage: https://www.npmjs.com/package/@maheshpaul/serverless-pdf-generator
- Size: 23.4 KB
- Stars: 1
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: readme.md
- License: LICENSE
Awesome Lists containing this project
README
# Serverless PDF Generator
`serverless-pdf-generator` is a lightweight package that simplifies the process of generating PDFs from web pages in a serverless environment like Vercel. It utilizes Puppeteer and Chromium to render pages and generate high-quality PDFs.
## Features
- 📄 Convert any URL to a PDF easily.
- 🚀 Optimized for serverless environments (Vercel, AWS Lambda, etc).
- âš¡ Supports Puppeteer and Chromium-min for minimal dependencies.
- 🎯 Customizable PDF output (format, margins, background printing, etc.).
## Installation
```sh
npm install @maheshpaul/serverless-pdf-generator
```
## Usage
### Next.js API Route Example
Create an API route at `src/app/api/pdf/route.ts`:
```ts
import { handlePDFRequest } from '@maheshpaul/serverless-pdf-generator';
import { NextRequest } from 'next/server';
export async function GET(request: NextRequest) {
return handlePDFRequest(request, async () => {
const url = new URL(request.url).searchParams.get('url');
if (!url) throw new Error('Missing URL');
return { url, filename: 'download.pdf' };
}, {
format: 'A4',
printBackground: true,
development: process.env.NODE_ENV === 'development'
});
}
```
### Next.js Client Component Example
Create a download button in a React client component:
```tsx
'use client';
export default function DownloadPDF() {
const handleDownload = async () => {
try {
const response = await fetch(`/api/pdf?url=${encodeURIComponent('https://google.com')}`);
if (!response.ok) throw new Error('PDF generation failed');
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'google.pdf';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error('Download failed:', error);
alert('Failed to download PDF');
}
};
return (
Download PDF
);
}
```
### React Server Component Example
If using a server-side approach in a React environment:
```tsx
import React, { useState } from 'react';
const DownloadPDF = () => {
const [loading, setLoading] = useState(false);
const handleDownload = async () => {
setLoading(true);
try {
const response = await fetch('/api/pdf?url=https://example.com');
if (!response.ok) throw new Error('PDF generation failed');
const blob = await response.blob();
const url = URL.createObjectURL(blob);
const a = document.createElement('a');
a.href = url;
a.download = 'example.pdf';
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
} catch (error) {
console.error(error);
alert('Error downloading PDF');
}
setLoading(false);
};
return (
{loading ? 'Generating...' : 'Download PDF'}
);
};
export default DownloadPDF;
```
## API
### `generatePDF(options: PDFGeneratorOptions)`
Generates a PDF from a given URL.
#### Parameters
```ts
interface PDFGeneratorOptions {
url: string;
format?: 'A4' | 'Letter' | 'Legal';
margin?: {
top?: string;
right?: string;
bottom?: string;
left?: string;
};
printBackground?: boolean;
development?: boolean;
}
```
#### Example
```ts
import { generatePDF } from '@maheshpaul/serverless-pdf-generator';
async function downloadPDF() {
const pdfBuffer = await generatePDF({ url: 'https://example.com' });
require('fs').writeFileSync('output.pdf', pdfBuffer);
}
```
### `handlePDFRequest(request: NextRequest, getData: () => Promise<{ url: string; filename?: string }>, options?: Omit)`
Handles a Next.js API request for generating a PDF.
#### Example
```ts
export async function GET(request: NextRequest) {
return handlePDFRequest(request, async () => {
return { url: 'https://example.com', filename: 'example.pdf' };
}, { format: 'A4' });
}
```
## Deployment
This package is optimized for serverless environments like Vercel. If using locally, ensure you have set `process.env.NODE_ENV === 'development'` to automatically switch between local and serverless execution.
## License
MIT License
## Author
Created by [Mahesh Paul](https://github.com/maheshpaulj). Contributions are welcome!