Pogodoc
SDKs

TypeScript

Complete reference for the Pogodoc TypeScript/JavaScript SDK with types, advanced configuration, and examples

TypeScript SDK

Complete documentation for the Pogodoc TypeScript/JavaScript SDK. This guide covers installation, configuration, all available methods, TypeScript types, and advanced usage patterns.

New to Pogodoc? Start with the TypeScript Quickstart guide first.

Installation

bash npm install @pogodoc/sdk
bash yarn add @pogodoc/sdk
bash pnpm add @pogodoc/sdk
bash bun add @pogodoc/sdk

Client Configuration

Basic Configuration

import { PogodocClient } from "@pogodoc/sdk";

const client = new PogodocClient({
  token: "your-api-token",
});

Configuration Options

OptionTypeDefaultDescription
tokenstring-Required. Your Pogodoc API token

Environment Variables

The SDK automatically reads environment variables:

// Token and base URL from environment variables
const client = new PogodocClient();
.env
POGODOC_API_TOKEN=your_token_here

The constructor will throw an error if no token is provided either as a parameter or via the POGODOC_API_TOKEN environment variable.

Core Methods

The SDK provides several methods for document generation and template management:

generateDocument()

The recommended method for most use cases. Generates a document and polls for completion automatically.

const result = await client.generateDocument({
  templateId: "your-template-id",
  data: { name: "Jane Doe" },
  renderConfig: {
    type: "react",
    target: "pdf",
  },
});

console.log("Document URL:", result.output?.data.url);

Parameters:

  • template (optional): Raw HTML/template string
  • templateId (optional): ID of a saved template
  • data: Object containing data to populate the template
  • renderConfig: Configuration for rendering

Important: You must provide either template or templateId, but not both. Exactly one is required.

Returns: Promise<GetJobStatusResponse> with the final job status including output URL

generateDocumentImmediate()

For quick, synchronous rendering of small documents. Returns the result immediately without job polling.

const response = await client.generateDocumentImmediate({
  templateId: "your-template-id",
  data: { name: "Jane Doe" },
  renderConfig: {
    type: "ejs",
    target: "pdf",
  },
});

console.log("Document URL:", response.output.data.url);

Important: You must provide either template or templateId, but not both. Exactly one is required.

Best for: Small, quick renders where you need immediate results

Use generateDocument() for larger documents or when reliability is critical. Use generateDocumentImmediate() for small, quick renders.

startGenerateDocument()

Lower-level method that only initializes the job. Use this if you want to implement custom polling logic.

const jobId = await client.startGenerateDocument({
  templateId: "your-template-id",
  data: { name: "Jane Doe" },
  renderConfig: {
    type: "react",
    target: "pdf",
  },
});

console.log("Started job:", jobId);

Important: You must provide either template or templateId, but not both. Exactly one is required.

Returns: Promise<string> - The job ID

pollForJobCompletion()

Polls for the completion of a rendering job. Use with startGenerateDocument() for custom workflows.

const result = await client.pollForJobCompletion(
  jobId,
  60, // maxAttempts (default: 60)
  500 // intervalMs (default: 500)
);

console.log("Job finished:", result.output?.data.url);

Parameters:

  • jobId: The ID of the job to poll
  • maxAttempts: Maximum number of polling attempts (default: 60)
  • intervalMs: Interval between attempts in milliseconds (default: 500)

Template Management

saveTemplate()

Save a new template from a local ZIP file.

const templateId = await client.saveTemplate({
  path: "./path/to/template.zip",
  title: "My Template",
  description: "Invoice template for customers",
  type: "react",
  categories: ["invoice"],
  sampleData: { name: "John Doe", amount: 1299.99 },
  sourceCode: "https://github.com/yourorg/template",
});

console.log("Template saved with ID:", templateId);

Parameters:

  • path: Local file path to the ZIP file
  • title: Template title
  • description: Template description
  • type: Template format type (see Template Types)
  • categories: Array of category strings
  • sampleData: Sample data for generating previews
  • formatOpts (optional): Format-specific options
  • sourceCode (optional): Link to source code

Returns: Promise<string> - The new template ID

saveTemplateFromFileStream()

Core method for saving templates from a stream. Useful for handling uploads in web applications.

import { createReadStream, statSync } from "fs";

const filePath = "./path/to/template.zip";
const zipStream = createReadStream(filePath);
const zipLength = statSync(filePath).size;

const templateId = await client.saveTemplateFromFileStream({
  payload: zipStream,
  payloadLength: zipLength,
  title: "My Template",
  description: "Invoice template",
  type: "react",
  categories: ["invoice"],
  sampleData: { name: "John Doe" },
});

updateTemplate()

Update an existing template with a new version from a ZIP file.

const contentId = await client.updateTemplate({
  templateId: "existing-template-id",
  path: "./path/to/new-version.zip",
  title: "My Updated Template",
  type: "react",
  categories: ["invoice", "updated"],
  sampleData: { name: "John Doe", amount: 1599.99 },
});

console.log("Template updated. New content ID:", contentId);

Returns: Promise<string> - The content ID of the new template version

updateTemplateFromFileStream()

Update a template from a file stream.

const contentId = await client.updateTemplateFromFileStream({
  templateId: "existing-template-id",
  payload: zipStream,
  payloadLength: zipLength,
  title: "My Updated Template",
  type: "react",
  categories: ["invoice"],
  sampleData: { name: "John Doe" },
});

Template Types

Pogodoc supports multiple template formats for different use cases:

TypeDescriptionBest For
reactAny frontend JS frameworkComplex layouts, reusable components
ejsEmbedded JavaScript templatesSimple variable substitution
latex 🚧LaTeX for scientific documentsAcademic papers, mathematical content
docx 🚧Microsoft Word templatesBusiness documents, form letters
xlsx 🚧Microsoft Excel templatesSpreadsheets, data reports
pptx 🚧Microsoft PowerPoint templatesPresentations, slides

React Templates: Any JavaScript framework works here! Use React, Vue, Angular, Svelte, or any other framework that renders to HTML/JSX. See our JavaScript Framework Templates guide for detailed setup instructions.

🚧 Coming Soon: LaTeX, DOCX, XLSX, and PPTX template types are currently in development and will be available soon.

JavaScript Framework Templates

JavaScript framework templates require a build process and must be uploaded as ZIP files. See the complete guide: JavaScript Framework Templates

Quick example of using a React template:

// Upload your built and zipped React template
const templateId = await client.saveTemplate({
  path: "./my-react-template.zip",
  title: "Invoice Template",
  type: "react",
  categories: ["invoice"],
});

// Generate documents using the template
const result = await client.generateDocument({
  templateId: templateId,
  data: {
    customer: { name: "Jane Smith" },
    items: [
      { name: "Service A", price: 150.0 },
      { name: "Service B", price: 250.0 },
    ],
    total: 400.0,
  },
  renderConfig: {
    type: "react",
    target: "pdf",
  },
});

console.log("Document URL:", result.output?.data.url);

EJS/HTML Template

EJS/HTML templates can be provided as inline strings:

const result = await client.generateDocument({
  template: `
    <h1>Hello <%= name %></h1>
    <p>Your order #<%= orderId %> has been confirmed.</p>
    <% if (premium) { %>
      <p>Thank you for being a premium member!</p>
    <% } %>
  `,
  data: {
    name: "John Doe",
    orderId: 12345,
    premium: true,
  },
  renderConfig: {
    type: "ejs",
    target: "pdf",
  },
});

Render Targets

Generate documents in multiple output formats:

TargetDescriptionUse Cases
pdfPDF documentsInvoices, reports, printable documents
pngPNG imagesSocial media graphics, thumbnails
jpg 🚧JPEG imagesCompressed images for web
html 🚧HTML outputWeb previews, email content
docx 🚧Word documentsEditable business documents
xlsx 🚧Excel spreadsheetsData reports, financial documents
pptx 🚧PowerPoint presentationsSlides, presentations

🚧 Coming Soon: JPG, HTML, DOCX, XLSX, and PPTX render targets are currently in development and will be available soon.

Specifying Output Format

const result = await client.generateDocument({
  templateId: "invoice-template",
  data: invoiceData,
  renderConfig: {
    type: "react",
    target: "pdf", // or 'png', 'jpg', 'html', etc.
  },
});

Format Options

Customize the rendering process with format-specific options:

const result = await client.generateDocument({
  templateId: "invoice-template",
  data: invoiceData,
  renderConfig: {
    type: "react",
    target: "pdf",
    formatOpts: {
      format: "A4", // Page format: 'A3', 'A4', 'A5', 'Letter', etc.
      waitForSelector: ".ready", // Wait for specific CSS selector
      fromPage: 1, // Start page for multi-page documents
      toPage: 5, // End page for multi-page documents
    },
  },
});

Available Format Options

OptionTypeDescription
formatstringPage format (A3, A4, A5, Letter, Legal, Tabloid)
waitForSelectorstringCSS selector to wait for before rendering
fromPagenumberStarting page number for partial renders
toPagenumberEnding page number for partial renders

Personal Upload URL

You can provide your own S3 presigned URL to upload the generated document to your storage:

const result = await client.generateDocument({
  templateId: "invoice-template",
  data: invoiceData,
  renderConfig: {
    type: "react",
    target: "pdf",
    personalUploadPresignedS3Url: "https://your-bucket.s3.amazonaws.com/...",
  },
});

TypeScript Types

The SDK exports all TypeScript types for type-safe development:

import type {
  PogodocClient,
  GenerateDocumentProps,
  RenderTarget,
  TemplateFormatType,
  SaveTemplateMetadata,
  UpdateTemplateProps,
  Categories,
} from "@pogodoc/sdk";

GenerateDocumentProps

type GenerateDocumentProps = {
  template?: string; // Raw template string
  templateId?: string; // Saved template ID
  data: { [key: string]: any }; // Template data
  renderConfig: {
    type: TemplateFormatType; // Template type
    target: RenderTarget; // Output format
    formatOpts?: {
      // Format-specific options
      [key: string]: any;
      fromPage?: number;
      toPage?: number;
      format?: string;
      waitForSelector?: string;
    };
    personalUploadPresignedS3Url?: string; // Optional upload URL
  };
};

TemplateFormatType

type TemplateFormatType =
  | "docx"
  | "xlsx"
  | "pptx"
  | "ejs"
  | "html"
  | "latex"
  | "react";

RenderTarget

type RenderTarget = "pdf" | "html" | "docx" | "xlsx" | "pptx" | "png" | "jpg";

SaveTemplateMetadata

type SaveTemplateMetadata = {
  categories: Categories; // Template categories
  title: string; // Template title
  description: string; // Template description
  sampleData: { [key: string]: any }; // Sample data for previews
  type: TemplateFormatType; // Template format type
  formatOpts?: {
    // Format options
    [key: string]: any;
  };
  sourceCode?: string; // Source code URL
};

type Categories = ("invoice" | "mail" | "report" | "cv" | "other")[];

Using Saved Templates

Instead of providing template content inline, you can use templates saved in your Pogodoc dashboard:

Create a Template

Go to your Pogodoc Dashboard and create a new template. Save it and copy the template ID.

Reference the Template

const response = await pogodoc.generateDocument({
  templateId: 'your-template-id',
  data: {
    // Your template data
    name: 'John Doe',
    amount: 1299.99,
  },
  renderConfig: {
    target: 'pdf',
  },
});

Best Practices

1. Environment Variables

Always store API tokens in environment variables:

// ✅ Good
const client = new PogodocClient({
  token: process.env.POGODOC_API_TOKEN,
});

// ❌ Bad - hardcoded token
const client = new PogodocClient({
  token: "sk-abc123...",
});

2. Use Saved Templates

For production, use saved templates instead of inline templates:

// ✅ Good
const result = await client.generateDocument({
  templateId: "invoice-v2",
  data,
  renderConfig: { target: "pdf" },
});

// ❌ Less ideal - template in code
const result = await client.generateDocument({
  template: `<html>...</html>`,
  data,
  renderConfig: { type: "html", target: "pdf" },
});

3. Error Handling

Always wrap SDK calls in try-catch blocks:

try {
  const result = await client.generateDocument(options);
  console.log("Document URL:", result.output?.data.url);
} catch (error) {
  console.error("Document generation failed:", error);
  // Handle error appropriately
}

4. Use TypeScript

Leverage TypeScript types for better developer experience:

import type { GenerateDocumentProps } from "@pogodoc/sdk";

const options: GenerateDocumentProps = {
  templateId: "invoice",
  data: {
    customer: "John Doe",
    amount: 1299.99,
  },
  renderConfig: {
    target: "pdf",
    options: {
      format: "A4",
      margin: { top: "1cm", right: "1cm", bottom: "1cm", left: "1cm" },
    },
  },
};

Examples

Invoice Generation

const generateInvoice = async (invoiceData: InvoiceData) => {
  const response = await pogodoc.generateDocument({
    templateId: "invoice-template",
    data: {
      invoiceNumber: invoiceData.number,
      customer: invoiceData.customer,
      items: invoiceData.items,
      subtotal: invoiceData.subtotal,
      tax: invoiceData.tax,
      total: invoiceData.total,
      date: new Date().toISOString(),
    },
    renderConfig: {
      target: "pdf",
      options: {
        format: "A4",
        margin: { top: "2cm", right: "2cm", bottom: "2cm", left: "2cm" },
      },
    },
  });

  return response.output?.data.url;
};

Social Media Graphics

const generateSocialGraphic = async (post: Post) => {
  const response = await pogodoc.generateDocument({
    templateId: "social-media-card",
    data: {
      title: post.title,
      author: post.author,
      image: post.featuredImage,
    },
    renderConfig: {
      target: "png",
      options: {
        width: 1200,
        height: 630,
        deviceScaleFactor: 2,
      },
    },
  });

  return response.output?.data.url;
};

Report with Dynamic Data

const generateReport = async (reportData: ReportData) => {
  const response = await pogodoc.generateDocument({
    template: `
      import React from 'react';
      import { Chart } from './components/Chart';
      
      export default function Report({ title, metrics, charts }) {
        return (
          <div>
            <h1>{title}</h1>
            {metrics.map(metric => (
              <div key={metric.id}>
                <h2>{metric.name}</h2>
                <p>{metric.value}</p>
              </div>
            ))}
            {charts.map(chart => (
              <Chart key={chart.id} data={chart.data} />
            ))}
          </div>
        );
      }
    `,
    data: reportData,
    renderConfig: {
      type: "react",
      target: "pdf",
      options: {
        format: "A4",
        landscape: true,
      },
    },
  });

  return response.output?.data.url;
};

Next Steps