Pogodoc
SDKs

Golang

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

Golang SDK

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

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

Installation

go get github.com/Pogodoc/pogodoc-go

Client Configuration

Basic Configuration

import "github.com/Pogodoc/pogodoc-go"

client, err := pogodoc.PogodocClientInitWithToken("your-api-token")
if err != nil {
    log.Fatal(err)
}

Configuration Options

The SDK provides three initialization methods:

MethodDescription
PogodocClientInit()Reads token from POGODOC_API_TOKEN environment variable
PogodocClientInitWithToken(token)Initialize with a specific token
PogodocClientInitWithConfig(baseURL, token)Initialize with custom base URL and token

Environment Variables

The SDK automatically reads environment variables:

// Token from environment variables
client, err := pogodoc.PogodocClientInit()
if err != nil {
    log.Fatal(err)
}
.env
POGODOC_API_TOKEN=your_token_here
POGODOC_BASE_URL=https://api.pogodoc.com  # Optional

The initialization functions will return 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. All methods require a context.Context parameter.

GenerateDocument()

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

ctx := context.Background()
template := `<h1>Hello <%= name %></h1>`

result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    Template: &template,
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        Data: map[string]interface{}{
            "name": "Jane Doe",
        },
        Type:   pogodoc.InitializeRenderJobRequestType("ejs"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

if err != nil {
    log.Fatal(err)
}

fmt.Println("Document URL:", result.Output.Data.Url)

Parameters:

  • GenerateDocumentProps struct containing:
    • Template (optional): Pointer to raw HTML/template string
    • InitializeRenderJobRequest: Configuration including:
      • TemplateId (optional): ID of a saved template
      • Data: Map containing data to populate the template
      • Type: Template format type
      • Target: Output format

Important: You must provide either Template or TemplateId in the request, but not both. Exactly one is required.

Returns: *GetJobStatusResponse with the final job status including output URL

GenerateDocumentImmediate()

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

result, err := client.GenerateDocumentImmediate(pogodoc.GenerateDocumentProps{
    Template: &template,
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        Data:   data,
        Type:   pogodoc.InitializeRenderJobRequestType("ejs"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

if err != nil {
    log.Fatal(err)
}

fmt.Println("Document URL:", result.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.

jobId, err := client.StartGenerateDocument(pogodoc.GenerateDocumentProps{
    Template: &template,
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        Data:   data,
        Type:   pogodoc.InitializeRenderJobRequestType("ejs"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

if err != nil {
    log.Fatal(err)
}

fmt.Println("Started job:", *jobId)

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

Returns: *string - Pointer to the job ID

PollForJobCompletion()

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

result, err := client.PollForJobCompletion(jobId, ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Job finished:", result.Output.Data.Url)

Parameters:

  • jobId: The ID of the job to poll
  • ctx: Context for the operation

Behavior:

  • Polls up to 60 times with 500ms intervals
  • Returns when job status is "done"
  • Returns error if job not found after max attempts

Template Management

SaveTemplate()

Save a new template from a local ZIP file.

metadata := pogodoc.SaveCreatedTemplateRequestTemplateInfo{
    Title:       "My Template",
    Description: "Invoice template for customers",
    Type:        pogodoc.SaveCreatedTemplateRequestTemplateInfoType("react"),
    Categories: []pogodoc.SaveCreatedTemplateRequestTemplateInfoCategoriesItem{
        pogodoc.SaveCreatedTemplateRequestTemplateInfoCategoriesItemInvoice,
    },
    SampleData: map[string]interface{}{
        "name":   "John Doe",
        "amount": 1299.99,
    },
    SourceCode: pogodoc.String("https://github.com/yourorg/template"),
}

templateId, err := client.SaveTemplate("./path/to/template.zip", metadata, ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Template saved with ID:", templateId)

Parameters:

  • filePath: Local file path to the ZIP file
  • metadata: Template metadata struct
  • ctx: Context for the operation

Returns: string - The new template ID

SaveTemplateFromFileStream()

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

file, err := os.Open("./path/to/template.zip")
if err != nil {
    log.Fatal(err)
}
defer file.Close()

fileInfo, err := file.Stat()
if err != nil {
    log.Fatal(err)
}

fsProps := pogodoc.FileStreamProps{
    Payload:       file,
    PayloadLength: int(fileInfo.Size()),
}

templateId, err := client.SaveTemplateFromFileStream(fsProps, metadata, ctx)

UpdateTemplate()

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

metadata := pogodoc.UpdateTemplateRequestTemplateInfo{
    Title:       "My Updated Template",
    Description: "Updated invoice template",
    Type:        pogodoc.UpdateTemplateRequestTemplateInfoType("react"),
    Categories: []pogodoc.UpdateTemplateRequestTemplateInfoCategoriesItem{
        pogodoc.UpdateTemplateRequestTemplateInfoCategoriesItemInvoice,
    },
    SampleData: map[string]interface{}{
        "name":   "John Doe",
        "amount": 1599.99,
    },
}

contentId, err := client.UpdateTemplate("existing-template-id", "./path/to/new-version.zip", metadata, ctx)
if err != nil {
    log.Fatal(err)
}

fmt.Println("Template updated. New content ID:", contentId)

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

UpdateTemplateFromFileStream()

Update a template from a file stream.

contentId, err := client.UpdateTemplateFromFileStream("existing-template-id", fsProps, metadata, ctx)

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
templateId, err := client.SaveTemplate("./my-react-template.zip", pogodoc.SaveCreatedTemplateRequestTemplateInfo{
    Title:      "Invoice Template",
    Type:       pogodoc.SaveCreatedTemplateRequestTemplateInfoType("react"),
    Categories: []pogodoc.SaveCreatedTemplateRequestTemplateInfoCategoriesItem{
        pogodoc.SaveCreatedTemplateRequestTemplateInfoCategoriesItemInvoice,
    },
}, ctx)

// Generate documents using the template
result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        TemplateId: &templateId,
        Data: map[string]interface{}{
            "customer": map[string]interface{}{
                "name": "Jane Smith",
            },
            "items": []map[string]interface{}{
                {"name": "Service A", "price": 150.00},
                {"name": "Service B", "price": 250.00},
            },
            "total": 400.00,
        },
        Type:   pogodoc.InitializeRenderJobRequestType("react"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

EJS/HTML Template

EJS/HTML templates can be provided as inline strings:

template := `
<h1>Hello <%= name %></h1>
<p>Your order #<%= orderId %> has been confirmed.</p>
<% if (premium) { %>
  <p>Thank you for being a premium member!</p>
<% } %>
`

result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    Template: &template,
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        Data: map[string]interface{}{
            "name":    "John Doe",
            "orderId": 12345,
            "premium": true,
        },
        Type:   pogodoc.InitializeRenderJobRequestType("ejs"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

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, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        TemplateId: &templateId,
        Data:       invoiceData,
        Type:       pogodoc.InitializeRenderJobRequestType("react"),
        Target:     pogodoc.InitializeRenderJobRequestTarget("pdf"),
        FormatOpts: &pogodoc.InitializeRenderJobRequestFormatOpts{
            Format:          pogodoc.String("A4"),
            WaitForSelector: pogodoc.String(".ready"),
            FromPage:        pogodoc.Int(1),
            ToPage:          pogodoc.Int(5),
        },
    },
}, ctx)

Available Format Options

OptionTypeDescription
Format*stringPage format (A3, A4, A5, Letter, Legal, Tabloid)
WaitForSelector*stringCSS selector to wait for before rendering
FromPage*intStarting page number for partial renders
ToPage*intEnding 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

templateId := "your-template-id"

result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        TemplateId: &templateId,
        Data: map[string]interface{}{
            "name":   "John Doe",
            "amount": 1299.99,
        },
        Type:   pogodoc.InitializeRenderJobRequestType("react"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

Best Practices

1. Environment Variables

Always store API tokens in environment variables:

// ✅ Good
client, err := pogodoc.PogodocClientInit()

// ❌ Bad - hardcoded token
client, err := pogodoc.PogodocClientInitWithToken("sk-abc123...")

2. Use Saved Templates

For production, use saved templates instead of inline templates:

// ✅ Good
templateId := "invoice-v2"
result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        TemplateId: &templateId,
        Data:       data,
        Target:     pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

// ❌ Less ideal - template in code
template := `<html>...</html>`
result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
    Template: &template,
    InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
        Data:   data,
        Type:   pogodoc.InitializeRenderJobRequestType("html"),
        Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
    },
}, ctx)

3. Error Handling

Always check errors returned by SDK methods:

result, err := client.GenerateDocument(props, ctx)
if err != nil {
    log.Printf("Document generation failed: %v", err)
    return err
}
log.Printf("Document URL: %s", result.Output.Data.Url)

4. Context Management

Use appropriate contexts for better control:

// With timeout
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()

result, err := client.GenerateDocument(props, ctx)

Examples

Invoice Generation

func generateInvoice(client *pogodoc.PogodocClient, invoiceData InvoiceData) (string, error) {
    ctx := context.Background()
    templateId := "invoice-template"

    result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
        InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
            TemplateId: &templateId,
            Data: map[string]interface{}{
                "invoiceNumber": invoiceData.Number,
                "customer":      invoiceData.Customer,
                "items":         invoiceData.Items,
                "subtotal":      invoiceData.Subtotal,
                "tax":           invoiceData.Tax,
                "total":         invoiceData.Total,
                "date":          time.Now().Format(time.RFC3339),
            },
            Type:   pogodoc.InitializeRenderJobRequestType("react"),
            Target: pogodoc.InitializeRenderJobRequestTarget("pdf"),
            FormatOpts: &pogodoc.InitializeRenderJobRequestFormatOpts{
                Format: pogodoc.String("A4"),
            },
        },
    }, ctx)

    if err != nil {
        return "", err
    }

    return result.Output.Data.Url, nil
}

Social Media Graphics

func generateSocialGraphic(client *pogodoc.PogodocClient, post Post) (string, error) {
    ctx := context.Background()
    templateId := "social-media-card"

    result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
        InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
            TemplateId: &templateId,
            Data: map[string]interface{}{
                "title":         post.Title,
                "author":        post.Author,
                "featuredImage": post.FeaturedImage,
            },
            Type:   pogodoc.InitializeRenderJobRequestType("react"),
            Target: pogodoc.InitializeRenderJobRequestTarget("png"),
        },
    }, ctx)

    if err != nil {
        return "", err
    }

    return result.Output.Data.Url, nil
}

Batch Document Generation

func generateMultipleDocuments(client *pogodoc.PogodocClient, dataList []map[string]interface{}) ([]string, error) {
    ctx := context.Background()
    templateId := "report-template"
    var urls []string

    for _, data := range dataList {
        result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{
            InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{
                TemplateId: &templateId,
                Data:       data,
                Type:       pogodoc.InitializeRenderJobRequestType("react"),
                Target:     pogodoc.InitializeRenderJobRequestTarget("pdf"),
            },
        }, ctx)

        if err != nil {
            return nil, fmt.Errorf("failed to generate document: %w", err)
        }

        urls = append(urls, result.Output.Data.Url)
    }

    return urls, nil
}

Next Steps