> ## Documentation Index
> Fetch the complete documentation index at: https://docs.pdfdyno.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Node.js SDK

> Official Node.js client for PDFDyno

# Node.js SDK

The official Node.js SDK for the PDFDyno API makes it simple to generate PDFs from your Node.js or TypeScript backend.

## Installation

You can install the SDK directly via npm (or yarn/pnpm):

```bash theme={null}
npm install pdfdyno
```

## Usage Example

Initialize the client with your API key and call `generatePdf` with your `template` and `data`.

```typescript theme={null}
import { PDFDynoClient } from 'pdfdyno';
import fs from 'fs';

const client = new PDFDynoClient({ apiKey: 'your_api_key_here' });

async function generate() {
  const pdfBuffer = await client.generatePdf({
    template: '#set page(width: 10cm, height: auto)\n= Invoice for #data.name\nTotal: $#data.amount',
    data: {
      name: 'Acme Corp',
      amount: '150.00'
    }
  });

  fs.writeFileSync('output.pdf', pdfBuffer);
}

generate();
```

*(Note: The `data` variable is auto-injected by the backend, so you can access it directly in your template as `#data.fieldname`)*

## Next.js (App Router) Example

You can easily use the SDK inside Next.js Server Actions or Route Handlers (`app/api/pdf/route.ts`).

```typescript theme={null}
import { PDFDynoClient } from 'pdfdyno';
import { NextResponse } from 'next/server';

const client = new PDFDynoClient({ apiKey: process.env.PDFDYNO_API_KEY! });

export async function POST(request: Request) {
  try {
    const { name } = await request.json();
    
    const pdfBuffer = await client.generatePdf({
      template: '= Hello #data.name',
      data: { name: name || 'World' }
    });

    return new NextResponse(pdfBuffer, {
      headers: {
        'Content-Type': 'application/pdf',
        'Content-Disposition': 'attachment; filename="document.pdf"'
      }
    });
  } catch (error) {
    return NextResponse.json({ error: 'Failed to generate PDF' }, { status: 500 });
  }
}
```

## Error Handling

Handle API errors such as rate limiting gracefully using specific error classes.

```typescript theme={null}
import { PDFDynoClient, PDFDynoRateLimitError } from 'pdfdyno';

const client = new PDFDynoClient({ apiKey: 'your_api_key' });

async function safeGenerate() {
  try {
    await client.generatePdf({
      template: 'Hello #data.name',
      data: { name: 'World' }
    });
  } catch (error) {
    if (error instanceof PDFDynoRateLimitError) {
      console.error('Rate limit exceeded. Please try again later.');
    } else {
      console.error('An error occurred during generation:', error);
    }
  }
}
```

## TypeScript Support

The `@pdfdyno/node` SDK is built with TypeScript and includes complete type definitions out of the box, providing auto-completion and compile-time validation for all options.
