Pogodoc
SDKs

Python

Complete reference for the Pogodoc Python SDK with types, advanced configuration, and examples

Python SDK

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

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

Installation

pip install pogodoc

Client Configuration

Basic Configuration

from pogodoc import PogodocClient

client = PogodocClient(token='your-api-token')

Environment Variables

The SDK automatically reads environment variables:

# Token from environment variables
client = PogodocClient()
.env
POGODOC_API_TOKEN=your_token_here
POGODOC_BASE_URL=https://api.pogodoc.com  # Optional

The constructor will raise a ValueError 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.

generate_document()

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

from pogodoc import PogodocClient, RenderConfig

client = PogodocClient()

result = client.generate_document(
    template_id='your-template-id',
    data={
        'name': 'Jane Doe',
        'amount': 1299.99,
    },
    render_config=RenderConfig(
        type='react',
        target='pdf',
    )
)

print(f"Document URL: {result.output.data.url}")

Parameters:

  • template (optional): Raw HTML/template string
  • template_id (optional): ID of a saved template
  • data: Dictionary containing data to populate the template
  • render_config: RenderConfig object with:
    • type: Template format type
    • target: Output format
    • format_opts (optional): Format-specific options

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

Returns: Job status response with the final output URL

generate_document_immediate()

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

result = client.generate_document_immediate(
    template_id='your-template-id',
    data={'name': 'Jane Doe'},
    render_config=RenderConfig(
        type='ejs',
        target='pdf',
    )
)

print(f"Document URL: {result.output.data.url}")

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

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

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

start_generate_document()

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

job_id = client.start_generate_document(
    template_id='your-template-id',
    data={'name': 'Jane Doe'},
    render_config=RenderConfig(
        type='react',
        target='pdf',
    )
)

print(f"Started job: {job_id}")

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

Returns: str - The job ID

poll_for_job_completion()

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

result = client.poll_for_job_completion(
    job_id,
    max_attempts=60,   # default: 60
    interval_ms=500    # default: 500
)

print(f"Job finished: {result.output.data.url}")

Parameters:

  • job_id: The ID of the job to poll
  • max_attempts: Maximum number of polling attempts (default: 60)
  • interval_ms: Interval between attempts in milliseconds (default: 500)

Template Management

save_template()

Save a new template from a local ZIP file.

from pogodoc.client.templates.types import SaveCreatedTemplateRequestTemplateInfo

template_info = SaveCreatedTemplateRequestTemplateInfo(
    title='My Template',
    description='Invoice template for customers',
    type='react',
    categories=['invoice'],
    sample_data={
        'name': 'John Doe',
        'amount': 1299.99,
    },
    source_code='https://github.com/yourorg/template',
)

template_id = client.save_template(
    path='./path/to/template.zip',
    template_info=template_info
)

print(f"Template saved with ID: {template_id}")

Parameters:

  • path: Local file path to the ZIP file
  • template_info: Template metadata object

Returns: str - The new template ID

save_template_from_file_stream()

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

with open('./path/to/template.zip', 'rb') as zip_file:
    zip_length = os.path.getsize('./path/to/template.zip')

    template_id = client.save_template_from_file_stream(
        payload=zip_file,
        payload_length=zip_length,
        template_info=template_info
    )

update_template()

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

from pogodoc.client.templates.types import UpdateTemplateRequestTemplateInfo

template_info = UpdateTemplateRequestTemplateInfo(
    title='My Updated Template',
    description='Updated invoice template',
    type='react',
    categories=['invoice', 'updated'],
    sample_data={
        'name': 'John Doe',
        'amount': 1599.99,
    },
)

content_id = client.update_template(
    template_id='existing-template-id',
    path='./path/to/new-version.zip',
    template_info=template_info
)

print(f"Template updated. New content ID: {content_id}")

Returns: Updated template response

update_template_from_file_stream()

Update a template from a file stream.

with open('./path/to/new-version.zip', 'rb') as zip_file:
    zip_length = os.path.getsize('./path/to/new-version.zip')

    content_id = client.update_template_from_file_stream(
        template_id='existing-template-id',
        payload=zip_file,
        payload_length=zip_length,
        template_info=template_info
    )

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
template_id = client.save_template(
    path='./my-react-template.zip',
    template_info=SaveCreatedTemplateRequestTemplateInfo(
        title='Invoice Template',
        type='react',
        categories=['invoice'],
    )
)

# Generate documents using the template
result = client.generate_document(
    template_id=template_id,
    data={
        'customer': {'name': 'Jane Smith'},
        'items': [
            {'name': 'Service A', 'price': 150.00},
            {'name': 'Service B', 'price': 250.00},
        ],
        'total': 400.00,
    },
    render_config=RenderConfig(
        type='react',
        target='pdf',
    )
)

print(f"Document URL: {result.output.data.url}")

EJS/HTML Template

EJS/HTML templates can be provided as inline strings:

result = client.generate_document(
    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,
    },
    render_config=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.

Format Options

Customize the rendering process with format-specific options:

result = client.generate_document(
    template_id='invoice-template',
    data=invoice_data,
    render_config=RenderConfig(
        type='react',
        target='pdf',
        format_opts={
            'format': 'A4',
            'waitForSelector': '.ready',
            'fromPage': 1,
            'toPage': 5,
        }
    )
)

Available Format Options

OptionTypeDescription
formatstrPage format (A3, A4, A5, Letter, Legal, Tabloid)
waitForSelectorstrCSS selector to wait for before rendering
fromPageintStarting page number for partial renders
toPageintEnding page number for partial renders

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

result = client.generate_document(
    template_id='your-template-id',
    data={
        'name': 'John Doe',
        'amount': 1299.99,
    },
    render_config=RenderConfig(
        target='pdf',
    )
)

Best Practices

1. Environment Variables

Always store API tokens in environment variables:

# ✅ Good
client = PogodocClient()

# ❌ Bad - hardcoded token
client = PogodocClient(token='sk-abc123...')

2. Use Saved Templates

For production, use saved templates instead of inline templates:

# ✅ Good
result = client.generate_document(
    template_id='invoice-v2',
    data=data,
    render_config=RenderConfig(target='pdf')
)

# ❌ Less ideal - template in code
result = client.generate_document(
    template='<html>...</html>',
    data=data,
    render_config=RenderConfig(type='html', target='pdf')
)

3. Error Handling

Always wrap SDK calls in try-except blocks:

try:
    result = client.generate_document(
        template_id='invoice',
        data=data,
        render_config=RenderConfig(target='pdf')
    )
    print(f"Document URL: {result.output.data.url}")
except Exception as e:
    print(f"Document generation failed: {e}")
    # Handle error appropriately

4. Type Hints

Use type hints for better code quality:

from typing import Dict, Any
from pogodoc import PogodocClient, RenderConfig

def generate_invoice(client: PogodocClient, data: Dict[str, Any]) -> str:
    result = client.generate_document(
        template_id='invoice-template',
        data=data,
        render_config=RenderConfig(target='pdf')
    )
    return result.output.data.url

Examples

Invoice Generation

def generate_invoice(client: PogodocClient, invoice_data: dict) -> str:
    result = client.generate_document(
        template_id='invoice-template',
        data={
            'invoice_number': invoice_data['number'],
            'customer': invoice_data['customer'],
            'items': invoice_data['items'],
            'subtotal': invoice_data['subtotal'],
            'tax': invoice_data['tax'],
            'total': invoice_data['total'],
            'date': datetime.now().isoformat(),
        },
        render_config=RenderConfig(
            target='pdf',
            format_opts={'format': 'A4'}
        )
    )

    return result.output.data.url

Social Media Graphics

def generate_social_graphic(client: PogodocClient, post: dict) -> str:
    result = client.generate_document(
        template_id='social-media-card',
        data={
            'title': post['title'],
            'author': post['author'],
            'image': post['featured_image'],
        },
        render_config=RenderConfig(target='png')
    )

    return result.output.data.url

Batch Document Generation

def generate_multiple_documents(
    client: PogodocClient,
    data_list: list
) -> list[str]:
    urls = []

    for data in data_list:
        try:
            result = client.generate_document(
                template_id='report-template',
                data=data,
                render_config=RenderConfig(
                    type='react',
                    target='pdf'
                )
            )
            urls.append(result.output.data.url)
        except Exception as e:
            print(f"Failed to generate document: {e}")
            continue

    return urls

Next Steps