Node.js / TypeScript

Integrate DoCreate with Node.js and TypeScript

This guide shows how to generate PDFs with DoCreate using Node.js and TypeScript. The examples use the built-in fetch API available in Node.js 18 and later.

Basic Example

Generate a PDF and save it to a file:

import { writeFile } from 'node:fs/promises';

const API_URL = 'https://api.docreate.io/api/pdf/external';
const API_KEY = process.env.DOCREATE_API_KEY;

async function generatePdf() {
  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${API_KEY}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify({
      html: `
        <h1>Invoice #1042</h1>
        <p>Date: 2026-02-17</p>
        <table>
          <tr><th>Item</th><th>Amount</th></tr>
          <tr><td>Web Development</td><td>$2,500.00</td></tr>
          <tr><td>Hosting (annual)</td><td>$300.00</td></tr>
        </table>
        <p><strong>Total: $2,800.00</strong></p>
      `,
      css: `
        body { font-family: Arial, sans-serif; padding: 40px; }
        h1 { color: #1a1a1a; }
        table { width: 100%; border-collapse: collapse; margin: 20px 0; }
        th, td { border: 1px solid #ddd; padding: 8px; text-align: left; }
        th { background-color: #f5f5f5; }
      `,
    }),
  });

  if (!response.ok) {
    const error = await response.json();
    throw new Error(`PDF generation failed: ${error.error}`);
  }

  const buffer = Buffer.from(await response.arrayBuffer());
  await writeFile('invoice.pdf', buffer);

  console.log('PDF saved to invoice.pdf');
}

generatePdf();

With Full Error Handling

A production-ready implementation with comprehensive error handling and retry logic:

import { writeFile } from 'node:fs/promises';

const API_URL = 'https://api.docreate.io/api/pdf/external';

interface GeneratePdfOptions {
  html: string;
  css?: string;
}

interface PdfErrorResponse {
  error: string;
}

async function generatePdf(
  apiKey: string,
  options: GeneratePdfOptions,
): Promise<Buffer> {
  const response = await fetch(API_URL, {
    method: 'POST',
    headers: {
      'Authorization': `Bearer ${apiKey}`,
      'Content-Type': 'application/json',
    },
    body: JSON.stringify(options),
  });

  if (!response.ok) {
    let message = `HTTP ${response.status}`;

    try {
      const body: PdfErrorResponse = await response.json();
      message = body.error || message;
    } catch {
      // Response body is not JSON
    }

    throw new Error(`PDF generation failed: ${message}`);
  }

  return Buffer.from(await response.arrayBuffer());
}

// Usage
async function main() {
  const apiKey = process.env.DOCREATE_API_KEY;

  if (!apiKey) {
    console.error('Missing DOCREATE_API_KEY environment variable');
    process.exit(1);
  }

  try {
    const pdf = await generatePdf(apiKey, {
      html: '<h1>Hello from DoCreate</h1><p>Generated with Node.js</p>',
      css: 'h1 { color: #2563eb; }',
    });

    await writeFile('output.pdf', pdf);
    console.log(`PDF generated successfully (${pdf.length} bytes)`);
  } catch (error) {
    console.error('Failed to generate PDF:', error);
    process.exit(1);
  }
}

main();

Express.js Integration

Serve generated PDFs directly from an Express route:

import express from 'express';

const app = express();
const API_URL = 'https://api.docreate.io/api/pdf/external';

app.get('/invoice/:id/pdf', async (req, res) => {
  try {
    const invoice = await getInvoice(req.params.id); // Your data layer

    const response = await fetch(API_URL, {
      method: 'POST',
      headers: {
        'Authorization': `Bearer ${process.env.DOCREATE_API_KEY}`,
        'Content-Type': 'application/json',
      },
      body: JSON.stringify({
        html: renderInvoiceHtml(invoice),
        css: invoiceStyles,
      }),
    });

    if (!response.ok) {
      throw new Error(`DoCreate API error: ${response.status}`);
    }

    const buffer = Buffer.from(await response.arrayBuffer());

    res.set({
      'Content-Type': 'application/pdf',
      'Content-Disposition': `attachment; filename="invoice-${invoice.number}.pdf"`,
      'Content-Length': buffer.length,
    });

    res.end(buffer);
  } catch (error) {
    console.error('PDF generation failed:', error);
    res.status(500).json({ error: 'Failed to generate PDF' });
  }
});

Environment Variables

Store your API key securely as an environment variable. Never hard-code it in your source files.

# .env
DOCREATE_API_KEY=your_api_key_here

If you are using a framework like Next.js or NestJS, refer to its documentation on how to load environment variables. For plain Node.js scripts, you can use the dotenv package or pass the variable directly:

DOCREATE_API_KEY=your_api_key_here node generate-pdf.js