# Welcome to Pogodoc (/docs) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps";
Pogodoc Logo Pogodoc Logo
# What is Pogodoc? **Effortless document creation with any web technology. A true Document-as-a-Service.** Pogodoc is a powerful document generation platform that lets developers and companies dynamically create documents (PDF, PNG, and more) from templates made in any JavaScript framework or HTML. ## Why Pogodoc? {" "} ## How It Works ### Create Your Template Build templates using your favorite framework (React, Vue, EJS) or plain HTML/CSS. You can also use AI to generate templates from descriptions. ```jsx // Example React template export default function Invoice({ data }) { return (

Invoice #{data.invoiceNumber}

Customer: {data.customerName}

{data.items.map((item) => ( ))}
{item.name} ${item.price}
); } ``` ### Integrate Pogodoc SDK Install and configure the [Pogodoc SDK](/docs/sdks) in your application. Choose from TypeScript, Python, .NET, Go, or PHP. ```bash npm install @pogodoc/sdk ``` ```typescript import { PogodocClient } from "@pogodoc/sdk"; const client = new PogodocClient({ token: process.env.POGODOC_API_TOKEN }); ``` ### Generate Documents Call the Pogodoc API with your data and get back a generated document in your desired format. ```typescript const document = await client.generateDocumentImmediate({ template: "invoice-template", target: "pdf", data: { invoiceNumber: "12345", customerName: "Acme Corp", items: [ { id: 1, name: "Service A", price: 100 }, { id: 2, name: "Service B", price: 200 }, ], }, }); ```
## Key Features ### Template Management * **All Frameworks**: Support for React, Vue, EJS, and plain HTML/CSS, and literally any web technology * **AI Generation**: Create templates from natural language descriptions * **Preview**: Test your templates before deployment ### Security & Enterprise * **On-Premise Enterprise Option**: Deploy Pogodoc in your own infrastructure * **Data Safety**: Your sensitive data and documents stay secure * **Token Management**: Organize access for multiple departments or developers * **Compliance Ready**: Suitable for regulated industries ### Admin Dashboard * **Usage Statistics**: Detailed analytics for all generated documents * **API Token Management**: Control access across your organization * **Template Library**: Store and manage all your templates in one place, explore community templates * **Monitoring**: Track performance and usage patterns ### Developer Experience * **Multiple SDKs**: TypeScript, Python, .NET, Go, PHP * **REST API**: Use any programming language * **Comprehensive Docs**: Detailed guides and API references * **Code Examples**: Open-source examples for common use cases ## Use Cases Pogodoc is perfect for: * **Invoices & Receipts**: Generate branded invoices automatically * **Reports**: Create dynamic reports with charts and data * **Certificates**: Produce personalized certificates at scale * **Marketing Materials**: Generate customized PDFs, flyers, or images * **Legal Documents**: Create contracts and agreements with dynamic data * **Tickets & Passes**: Generate event tickets, boarding passes, etc. * **Any documents**: Generate the perfect document for your use-case ## Deployment Options ## Getting Started Our documentation contains everything you need to start generating documents: ## Enterprise Support For businesses and on-premise solutions, we provide: * **Dedicated Onboarding**: We guide you through the entire setup process * **Custom Templates**: We can create templates tailored to your needs * **Technical Support**: Direct access to our engineering team * **SLA Guarantees**: Enterprise-grade reliability and uptime Ready to get started? [Check out our quickstart guides](/docs/get-started) or [contact us](mailto:contact@pogodoc.com) for enterprise inquiries. ## Getting Started Choose your preferred language to get started: * [TypeScript/Node.js](/docs/get-started/typescript) * [Python](/docs/get-started/python) * [.NET](/docs/get-started/dotnet) * [Go](/docs/get-started/golang) * [PHP](/docs/get-started/php) # Clone Template (/docs/api-reference/cloneTemplate) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Creates a new template by duplicating an existing template's content and metadata. Includes copying preview files and template index. # Delete Template (/docs/api-reference/deleteTemplate) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Deletes a template from Strapi and associated S3 storage. Removes all associated files and metadata. # Extract Template Files (/docs/api-reference/extractTemplateFiles) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Extracts contents from an uploaded template ZIP file and stores individual files in the appropriate S3 storage structure. # Generate Presigned URL (/docs/api-reference/generatePresignedGetUrl) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Generates a presigned URL for template access. Used for downloading template files from S3 storage. # Generate Template Previews (/docs/api-reference/generateTemplatePreviews) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Creates both PNG and PDF preview files for template visualization. Generates previews in parallel and returns URLs for both formats. # Get Job Status (/docs/api-reference/getJobStatus) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Fetches detailed job information from S3 storage including job status, template ID, target format, and output details if available. # Get Template By ID (/docs/api-reference/getTemplateById) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Fetches a single template by its ID for the authenticated user. # Get Template Index HTML (/docs/api-reference/getTemplateIndexHtml) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Retrieves the template index.html file from S3 storage. Used for rendering the template in the browser. # Get User Templates (/docs/api-reference/getUserTemplates) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Fetches all templates belonging to the authenticated user. Optionally filter by category. # Initialize Render Job (/docs/api-reference/initializeRenderJob) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Creates a new render job with a unique ID, sets up S3 storage for template and data files, and generates presigned upload URLs if needed. Requires subscription check. # Initialize Template Creation (/docs/api-reference/initializeTemplateCreation) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Initializes template creation by generating a unique ID and providing a presigned URL for template ZIP upload. Sets unfinished tag for tracking incomplete templates. # Save New Template (/docs/api-reference/saveCreatedTemplate) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Finalizes template creation by saving template info to Strapi, copying preview files to permanent storage, and creating template index. Removes unfinished tag upon completion. # Immediate Render (/docs/api-reference/startImmediateRender) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Combines initialization and rendering in one step. Creates a job, uploads template/data directly, starts rendering, and adds the document to Strapi. Requires subscription check. # Start Render Job (/docs/api-reference/startRenderJob) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Takes a previously initialized job, updates its status to in-progress, and triggers the rendering process using Puppeteer. Can optionally wait for render completion. # Update Template (/docs/api-reference/updateTemplate) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Updates template content, handles S3 storage cleanup for old content, updates template metadata in Strapi, and manages preview files. Removes unfinished tags after successful update. # Upload Template Index HTML (/docs/api-reference/uploadTemplateIndexHtml) {/* This file was generated by Fumadocs. Do not edit this file directly. Any changes should be made by running the generation command again. */} Uploads the template index.html file to S3 storage. Used for rendering the template in the browser. # Managing API Tokens (/docs/api-tokens) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # API Tokens API tokens are secure credentials that authenticate your applications with the Pogodoc API and SDKs. Think of them as passwords that allow your code to access Pogodoc services on behalf of your account. If you are a company that wants metric controlled usage by department, project, or developer, you can create different API tokens and view metrics per API token. Manage all your API tokens at [app.pogodoc.com/api-tokens](https://app.pogodoc.com/api-tokens). ## Quick Start ### Subscribe to a plan To set-up quickly and free, you can subscribe to the **Free Plan**. ### Generate Your Token Create a new API token from the dashboard with a descriptive name. ### Store Securely Add the token to your environment variables - never hardcode it in your source code. ### Use in Your App Pass the token to the Pogodoc SDK or include it in API request headers. You'll be prompted to choose a plan before creating your first token if you don't have an active subscription. *** ## What are API Tokens? API tokens are unique, secret strings that identify and authorize your application when making requests to the Pogodoc API. ### Key Characteristics * **Unique** - Each token is globally unique to your account * **Secret** - Tokens should never be shared publicly or committed to version control * **Revocable** - You can delete tokens at any time to immediately stop their access * **Trackable** - Monitor usage and document generation per token *** ### Token Limits * **Maximum Active Tokens**: 10 per account * **Deleted Tokens**: Do not count toward this limit If you need more than 10 active tokens, please [contact support](mailto:contact@pogodoc.com) to discuss enterprise options. *** ## Creating API Tokens Generate new API tokens from the [API Tokens dashboard](https://app.pogodoc.com/api-tokens). ### Navigate to API Tokens Go to [app.pogodoc.com/api-tokens](https://app.pogodoc.com/api-tokens) or click **API Tokens** in the main navigation. ### Generate New Token API Token Generation 1. Click the **"Generate"** button in the "Generate Tokens" section 2. Enter a descriptive name for your token - Use names that indicate purpose: `production-api`, `staging-server`, `dev-local` - Keep it short (1-20 characters) - Use descriptive names to identify usage later 3. Click **"Generate"** or press Enter ### Copy and Save Token **Critical:** You can only view the token once! You should immediately save it in a secure location. Store your token in: * Environment variables in your deployment platform * Secret management systems (AWS Secrets Manager, Azure Key Vault, etc.) * Password managers for local development * `.env` files (never commit these to git!) **Do NOT store tokens in:** * Source code files * Version control systems (Git, SVN, etc.) * Documentation or wikis * Shared documents or chat messages *** ## Using API Tokens Once you have an API token, you can use it to authenticate with Pogodoc services. Tokens are used for our official [SDKs](/docs/sdks) when initializing the Pogodoc client, and provided as an Authorization header with our [API](/docs/api-reference/saveCreatedTemplate). ### Environment Variables Store your token in environment variables for security: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` Add `.env` to your `.gitignore` to prevent accidentally committing tokens! **AWS** ```bash aws secretsmanager create-secret \ --name pogodoc-api-token \ --secret-string "your_token_here" ``` **Azure** ```bash az keyvault secret set \ --vault-name mykeyvault \ --name pogodoc-api-token \ --value "your_token_here" ``` **Heroku** ```bash heroku config:set POGODOC_API_TOKEN=your_token_here ``` **Vercel** ```bash vercel env add POGODOC_API_TOKEN ``` **Environment file** ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` *** ## Managing Your Tokens View and manage all your API tokens from the [API Tokens dashboard](https://app.pogodoc.com/api-tokens). ### Token Dashboard The dashboard displays all your tokens and their usage (how many documents have been generated with a token). ### Viewing Tokens The dashboard has two tabs: #### Active Tokens Shows all currently usable tokens. #### Deleted Tokens Shows previously deleted tokens for audit and reference purposes. These tokens no longer work but are kept for record-keeping. ### Token Statistics You can **filter** by API Token usage in the main [Dashboard](https://app.pogodoc.com/dashboard). *** ## Deleting Tokens Remove tokens you no longer need to improve security. ### Navigate to Active Tokens Go to the **Active** tab in your token dashboard. ### Delete the Token 1. Find the token you want to remove 2. Click the red **"Delete"** button 3. Confirm the deletion in the dialog ### Update Your Applications Deleted tokens stop working **immediately**. Any applications using the deleted token will start receiving `401 Unauthorized` errors. Before deleting, make sure to: * Update applications to use a different token * Remove the deleted token from environment variables * Check CI/CD pipelines for references * Notify team members if applicable ### Recovery Deleted tokens **cannot be restored**. If you accidentally delete a token: 1. Generate a new token 2. Update all applications with the new token 3. The old token is permanently invalidated *** ## Best Practices ### Security #### DO * **Store in environment variables** - Use `.env` files locally, secret managers in production * **Use separate tokens** - Different tokens for development, staging, and production * **Rotate regularly** - Generate new tokens periodically (quarterly recommended) * **Monitor usage** - Check the dashboard for unexpected activity * **Delete unused tokens** - Remove tokens for deprecated projects #### DON'T * **Commit to version control** - Never push tokens to Git, GitHub, GitLab, etc. * **Share publicly** - Don't post tokens in forums, issues, or chat * **Hardcode in source** - Avoid putting tokens directly in code files * **Reuse across environments** - Don't use production tokens in development * **Share between teams** - Generate separate tokens for different teams/projects ### Token Naming Conventions Use clear, descriptive names that indicate the token's purpose: ```bash βœ… Good Examples: - production-api-server - staging-web-app - dev-john-local - ci-github-actions - mobile-app-prod ❌ Bad Examples: - token1 - test - my-token - abc123 ``` *** ## Troubleshooting ### Token Not Working **Symptoms:** Getting `401 Unauthorized` errors **Solutions:** 1. Verify the token is copied correctly (no extra spaces or characters) 2. Check that the token is still active (not deleted) 3. Confirm your subscription is active and in good standing 4. If using the API, ensure you're using the correct base URL (`https://api.pogodoc.com`) and the Authorization header is formatted correctly `Bearer YOUR_TOKEN` ### Can't Generate New Token **Symptoms:** Generation fails or button is disabled **Possible Causes:** * **No active plan** - You need a subscription to generate tokens * **Token limit reached** - You have 10 active tokens already (delete unused ones) ### Token Limit Exceeded If you need more than 10 active tokens: 1. Delete unused tokens first 2. Consolidate similar applications to use the same token 3. [Contact our sales team](mailto:contact@pogodoc.com) about enterprise plans ### Lost Token **If you lost your token:** 1. You cannot recover the original token value 2. Delete the lost token (if you know which one it is) 3. Generate a new token as a replacement 4. Update all applications with the new token This is why it's crucial to store tokens in a secure, backed-up location immediately after generation. *** ## Token Security ### Compromised Token If you believe a token has been compromised: ### Delete Immediately Go to the dashboard and delete the compromised token right away. This stops all access immediately. \### Generate Replacement Create a new token with a different name. ### Update Applications Replace the old token in all legitimate applications with the new one. ### Review Usage Check the deleted token's usage history for any suspicious activity. Contact support if you see unauthorized usage. ### Rotate Other Tokens As a precaution, consider rotating other tokens if you suspect broader security issues. ### Prevention * Use secret scanning tools in your repositories (GitHub Advanced Security, GitGuardian) * Enable branch protection rules to prevent accidental token commits * Set up alerts for unusual API usage patterns * Educate team members about token security * Use least-privilege tokens for specific applications *** ## Next Steps # .NET (/docs/get-started/dotnet) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # .NET Quickstart Welcome! This guide will help you get started with Pogodoc using .NET. You'll learn how to install the SDK, authenticate, and generate your first document in minutes. ## Prerequisites Before you begin, make sure you have: ## Quick Start Guide ### Install the SDK Install the Pogodoc SDK using the .NET CLI: ```bash dotnet add package Pogodoc.SDK ``` ### Initialize the Client Create a Pogodoc client with your API token. You can get your token from the [API tokens page](https://app.pogodoc.com/api-tokens). ```csharp using Pogodoc; var client = new PogodocApiClient(""); ``` For better security, store your API token in an environment variable: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` Then retrieve it in your code: ```csharp var token = Environment.GetEnvironmentVariable("POGODOC_API_TOKEN"); var client = new PogodocApiClient(token); ``` ### Generate Your First Document Now you're ready to generate a document! Here's a simple example using an EJS template: ```csharp using Pogodoc; using Pogodoc.Documents; var client = new PogodocApiClient( Environment.GetEnvironmentVariable("POGODOC_API_TOKEN") ); var template = @" Invoice

Invoice for <%= customerName %>

Amount: $<%= amount %>

Date: <%= date %>

"; var data = new Dictionary { { "customerName", "John Doe" }, { "amount", 1299.99 }, { "date", DateTime.Now.ToString("MM/dd/yyyy") } }; var response = await client.Documents.StartImmediateRenderAsync( new StartImmediateRenderRequest { Template = template, Data = data, Type = StartImmediateRenderRequestType.Ejs, Target = StartImmediateRenderRequestTarget.Pdf, } ); // Get the URL to your generated PDF Console.WriteLine($"Document URL: {response.Output.Data.Url}"); ``` Your document is now generated and available at the returned URL. The URL is publicly accessible and can be shared or downloaded.
## Next Steps Now that you've generated your first document, explore the detailed SDK documentation: # Golang (/docs/get-started/golang) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # Golang Quickstart Welcome! This guide will help you get started with Pogodoc using Go. You'll learn how to install the SDK, authenticate, and generate your first document in minutes. ## Prerequisites Before you begin, make sure you have: ## Quick Start Guide ### Install the SDK Install the Pogodoc SDK using Go modules: ```bash go get github.com/Pogodoc/pogodoc-go ``` ### Initialize the Client Create a Pogodoc client with your API token. You can get your token from the [API tokens page](https://app.pogodoc.com/api-tokens). ```go package main import ( "context" "fmt" "log" "github.com/Pogodoc/pogodoc-go" ) func main() { client, err := pogodoc.PogodocClientInitWithToken("") if err != nil { log.Fatal(err) } } ``` For better security, store your API token in an environment variable: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` Then initialize without a parameter: ```go client, err := pogodoc.PogodocClientInit() ``` ### Generate Your First Document Now you're ready to generate a document! Here's a simple example using an EJS template: ```go package main import ( "context" "fmt" "log" "time" "github.com/Pogodoc/pogodoc-go" ) func main() { client, err := pogodoc.PogodocClientInit() if err != nil { log.Fatal(err) } ctx := context.Background() template := ` Invoice

Invoice for <%= customerName %>

Amount: $<%= amount %>

Date: <%= date %>

` data := map[string]interface{}{ "customerName": "John Doe", "amount": 1299.99, "date": time.Now().Format("01/02/2006"), } result, err := client.GenerateDocument(pogodoc.GenerateDocumentProps{ Template: &template, InitializeRenderJobRequest: pogodoc.InitializeRenderJobRequest{ Data: data, Type: pogodoc.InitializeRenderJobRequestType("ejs"), Target: pogodoc.InitializeRenderJobRequestTarget("pdf"), }, }, ctx) if err != nil { log.Fatal(err) } // Get the URL to your generated PDF fmt.Printf("Document URL: %s\n", result.Output.Data.Url) } ``` Your document is now generated and available at the returned URL. The URL is publicly accessible and can be shared or downloaded.
## Next Steps Now that you've generated your first document, explore the detailed SDK documentation: # Overview (/docs/get-started) import { Card, Cards } from "fumadocs-ui/components/card"; # Get Started with Pogodoc Welcome to the Pogodoc quickstart guides! This section will help you integrate Pogodoc into your application and start generating documents programmatically in just a few minutes. ## What You'll Learn Each quickstart guide will walk you through: * **Installing the SDK** for your programming language * **Setting up authentication** with your API token * **Creating your first template** via the Pogodoc dashboard * **Generating a document** programmatically using the SDK * **Downloading the result** as a PDF or other formats ## Choose Your Language Select your preferred programming language to get started: ## Prerequisites Before you begin, make sure you have: 1. **A Pogodoc account** - [Sign up for free](https://app.pogodoc.com) if you haven't already 2. **An API token** - Generate one from your [Pogodoc dashboard](https://app.pogodoc.com/api-tokens) 3. **A template** - Create a template in the [Pogodoc dashboard](https://app.pogodoc.com/templates) or use one of our examples ## What's Next? After completing a quickstart guide, you can: * Explore the [SDK documentation](/docs/sdks) for advanced features * Learn about [template creation](/docs/templates) and customization * Review the [API Reference](/docs/api-reference) for complete endpoint documentation * Check out [API Tokens](/docs/api-tokens) for security best practices ## Need Help? If you run into any issues: * Check our [FAQs](/docs/knowledge-base/faqs) for common questions * Visit the [Pogodoc Community](https://pogodoc.com/#contact) for support * Contact us at [contact@pogodoc.com](mailto:contact@pogodoc.com) Let's get started! Choose your programming language above to begin your journey with Pogodoc. # PHP (/docs/get-started/php) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # PHP Quickstart Welcome! This guide will help you get started with Pogodoc using PHP. You'll learn how to install the SDK, authenticate, and generate your first document in minutes. ## Prerequisites Before you begin, make sure you have: ## Quick Start Guide ### Install the SDK Install the Pogodoc SDK using Composer: ```bash composer require pogodoc/pogodoc-php ``` ### Initialize the Client Create a Pogodoc client with your API token. You can get your token from the [API tokens page](https://app.pogodoc.com/api-tokens). ```php '); ``` For better security, store your API token in an environment variable: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` The SDK will automatically read the `POGODOC_API_TOKEN` environment variable if no token is provided: ```php $client = new PogodocSdk(); ``` ### Generate Your First Document Now you're ready to generate a document! Here's a simple example using an EJS template: ```php Invoice

Invoice for <%= customerName %>

Amount: $<%= amount %>

Date: <%= date %>

'; $data = [ 'customerName' => 'John Doe', 'amount' => 1299.99, 'date' => date('m/d/Y'), ]; $response = $client->generateDocument([ 'template' => $template, 'data' => $data, 'renderConfig' => [ 'type' => 'ejs', 'target' => 'pdf', ] ]); // Get the URL to your generated PDF printf("Document URL: %s\n", $response->output->data->url); ``` Your document is now generated and available at the returned URL. The URL is publicly accessible and can be shared or downloaded.
## Next Steps Now that you've generated your first document, explore the detailed SDK documentation: # Python (/docs/get-started/python) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # Python Quickstart Welcome! This guide will help you get started with Pogodoc using Python. You'll learn how to install the SDK, authenticate, and generate your first document in minutes. ## Prerequisites Before you begin, make sure you have: ## Quick Start Guide ### Install the SDK Install the Pogodoc SDK using pip: ```bash pip install pogodoc ``` ### Initialize the Client Create a Pogodoc client with your API token. You can get your token from the [API tokens page](https://app.pogodoc.com/api-tokens). ```python from pogodoc import PogodocClient pogodoc = PogodocClient(token='') ``` For better security, store your API token in an environment variable: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` The SDK will automatically read the `POGODOC_API_TOKEN` environment variable if no token is provided: ```python pogodoc = PogodocClient() ``` ### Generate Your First Document Now you're ready to generate a document! Here's a simple example using an EJS template: ```python from pogodoc import PogodocClient, RenderConfig from datetime import datetime pogodoc = PogodocClient() template = ''' Invoice

Invoice for <%= customerName %>

Amount: $<%= amount %>

Date: <%= date %>

''' data = { 'customerName': 'John Doe', 'amount': 1299.99, 'date': datetime.now().strftime('%m/%d/%Y'), } response = pogodoc.generate_document( template=template, data=data, render_config=RenderConfig( type='ejs', target='pdf', ) ) # Get the URL to your generated PDF print(f"Document URL: {response.output.data.url}") ``` Your document is now generated and available at the returned URL. The URL is publicly accessible and can be shared or downloaded.
## Next Steps Now that you've generated your first document, explore the detailed SDK documentation: # TypeScript (/docs/get-started/typescript) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # TypeScript Quickstart Welcome! This guide will help you get started with Pogodoc using TypeScript and Node.js. You'll learn how to install the SDK, authenticate, and generate your first document in minutes. ## Prerequisites Before you begin, make sure you have: ## Quick Start Guide ### Install the SDK Install the Pogodoc SDK using your preferred package manager: ```bash npm install @pogodoc/sdk ``` ```bash yarn add @pogodoc/sdk ``` ```bash pnpm add @pogodoc/sdk ``` ```bash bun add @pogodoc/sdk ``` ### Initialize the Client Create a Pogodoc client with your API token. You can get your token from the [API tokens page](https://app.pogodoc.com/api-tokens). ```typescript import { PogodocClient } from '@pogodoc/sdk'; const pogodoc = new PogodocClient({ token: '', }); ``` For better security, store your API token in an environment variable: ```bash title=".env" POGODOC_API_TOKEN=your_token_here ``` The SDK will automatically read the `POGODOC_API_TOKEN` environment variable if no token is provided. ### Generate Your First Document Now you're ready to generate a document! Here's a simple example using an EJS template: ```typescript const template = ` Invoice

Invoice for <%= customerName %>

Amount: $<%= amount %>

Date: <%= date %>

`; const data = { customerName: 'John Doe', amount: 1299.99, date: new Date().toLocaleDateString(), }; const response = await pogodoc.generateDocument({ template, data, renderConfig: { type: 'ejs', target: 'pdf', }, }); // Get the URL to your generated PDF console.log('Document URL:', response.output?.data.url); ``` Your document is now generated and available at the returned URL. The URL is publicly accessible and can be shared or downloaded.
## Next Steps Now that you've generated your first document, explore the detailed SDK documentation: # FAQs (/docs/knowledge-base/faqs) import { Card, Cards } from "fumadocs-ui/components/card"; import { Callout } from "fumadocs-ui/components/callout"; # Frequently Asked Questions Welcome to the Pogodoc FAQ! This comprehensive resource answers common questions about using Pogodoc effectively. Whether you're new to the platform or looking to deepen your understanding, you'll find answers about getting started, document generation, templates, integrations, security, and more. Can't find your question? Reach out to our [support team](mailto:contact@pogodoc.com) or join our [Discord community](https://discord.gg/pogodoc) for help. *** ## Getting Started ### Do I need coding experience to use Pogodoc? Yes, basic knowledge of HTML or a frontend framework is recommended to make the most of Pogodoc's capabilities. However: * **Template Creation**: You can use our **AI-powered template builder** to generate templates using natural language - no coding required! Just describe what you need, and our AI creates the template for you. * **Visual Editor**: Our dashboard includes a visual editor for non-technical users to customize templates without writing code. * **Community Templates**: Browse and use pre-built templates from our [community library](/docs/templates#community-templates). * **For Developers**: If you're comfortable with HTML, React, Vue, or other web technologies, you'll have full control over template design. Learn more in our [Get Started guides](/docs/get-started) and [Templates documentation](/docs/templates). ### How do I get started with Pogodoc? Getting started is simple: 1. **Sign up** at [app.pogodoc.com](https://app.pogodoc.com) 2. **Choose a plan** - We offer Free, Starter, Professional, and Enterprise tiers 3. **Generate an API token** at [app.pogodoc.com/api-tokens](https://app.pogodoc.com/api-tokens) 4. **Install an SDK** or use our REST API 5. **Create your first template** using our dashboard or AI builder 6. **Generate your first document** using our SDK Check out our language-specific quickstart guides: * [TypeScript/JavaScript](/docs/get-started/typescript) * [Python](/docs/get-started/python) * [PHP](/docs/get-started/php) * [Golang](/docs/get-started/golang) * [.NET](/docs/get-started/dotnet) ### Which programming languages are supported? Pogodoc provides official SDKs for: * **TypeScript/JavaScript** - Full-featured SDK for Node.js with TypeScript support ([View SDK](/docs/sdks/typescript)) * **Python** - Native Python SDK with async support ([View SDK](/docs/sdks/python)) * **PHP** - Composer-based SDK for PHP applications ([View SDK](/docs/sdks/php)) * **Golang** - Idiomatic Go SDK ([View SDK](/docs/sdks/golang)) * **.NET** - C# SDK for .NET applications ([View SDK](/docs/sdks/dotnet)) **Don't see your language?** You can: * Use our [REST API](/docs/api-reference) directly from any language * [Build your own SDK](/docs/sdks/create-your-own) using our comprehensive API documentation ### Is there a free plan? Yes! We offer a **Free Plan** that includes: * Limited document generation for testing and development * Access to basic templates * Community support * API token generation For production use and higher limits, we recommend our [paid plans](https://pogodoc.com/#pricing). *** ## Document Generation ### What types of documents can I create with Pogodoc? Pogodoc enables you to create virtually any document type, including: **Business Documents:** * Invoices and receipts * Quotes and proposals * Purchase orders * Financial reports * Contracts and agreements **Marketing Materials:** * Social media graphics * Email templates * Certificates and badges * Event tickets and passes * Promotional materials **Reports & Analytics:** * PDF reports with charts and graphs * Data visualizations * Analytics dashboards * Performance summaries **Custom Documents:** * Forms and applications * Labels and stickers * Product catalogs * Any custom document you can design! By using templates and integrating real-time data, you can generate dynamic, professional documents on demand. See our [Templates guide](/docs/templates) for examples. ### How fast is document generation? Document generation speed depends on several factors: **Typical Generation Times:** * **Immediate Render** (synchronous): 1-5 seconds for most documents * **Standard Render** (asynchronous): Processing starts immediately, completion in 1-30 seconds depending on complexity **Factors affecting speed:** * Template complexity (number of pages, images, charts) * Data size (thousands of rows vs. simple data) * Output format (PDFs take longer than PNGs) * Server load (Enterprise plans get priority processing) **Performance tips:** * Use asynchronous rendering for complex documents * Cache generated documents when possible * Optimize images in templates * Consider batch processing for multiple documents ### Can I generate multiple documents at once? Yes! There are several approaches: **1. Batch Processing (Recommended):** ```typescript const documents = await Promise.all( orders.map((order) => client.generateDocument({ template: "invoice", data: order, target: "pdf", }) ) ); ``` **2. Asynchronous Generation:** Start multiple jobs and poll for completion: ```typescript const jobs = await Promise.all( orders.map(order => client.startGenerateDocument({...})) ); // Poll each job separately ``` **3. Enterprise Bulk API:** Contact [contact@pogodoc.com](mailto:contact@pogodoc.com) for dedicated bulk generation endpoints with higher throughput. See our [SDK documentation](/docs/sdks) for batch processing examples. ### Can I generate documents without templates? Yes! You can generate documents using **inline templates** - pass the template code directly in your API request: ```typescript const document = await client.generateDocumentImmediate({ template: "

Hello <%= name %>

<%= message %>

", data: { name: "World", message: "This is an inline template!" }, type: "ejs", target: "pdf", }); ``` This is great for: * Quick prototypes and testing * Simple, dynamic documents * One-off document generation * When you don't want to manage templates in the dashboard For production use, we recommend [saving templates](/docs/templates) in the dashboard for: * Reusability * Team collaboration * Visual editing *** ## Templates ### Is there a library of templates available? Yes! Pogodoc provides multiple ways to access templates: **1. Community Templates Library** Browse professionally designed templates in our [community library](https://app.pogodoc.com/templates): * Invoices, receipts, and financial documents * Social media graphics and marketing materials * Reports, certificates, and badges * Clone and customize any template **2. AI Template Generation** Use our AI chatbot to create custom templates: * Describe your needs in plain English * AI generates a complete template with sample data * Edit and refine using our visual editor * Save for future use **3. Upload Your Own** Create templates using any web technology: * HTML/CSS with EJS templating * React, Vue, Svelte, or any framework * Upload as a ZIP file * Full control over design and styling Learn more in our [Templates documentation](/docs/templates). ### What template formats are supported? Pogodoc supports multiple template formats: **HTML-Based Templates:** * **EJS** (Embedded JavaScript) - Simple, powerful templating with placeholders * **HTML** - Pure HTML with static data **JavaScript Frameworks:** * **React** - Build templates with React components * **Vue** - Use Vue components and composition API * **Svelte** - Compile-time templates with Svelte * any other framework **Framework-Agnostic:** Any web technology that compiles to HTML/CSS/JS works! Build with your preferred tools and upload the bundle. See our [Templates guide](/docs/templates) for detailed information and examples. ### Can I use custom fonts in my templates? Yes! You can use custom fonts in several ways: **1. Web Fonts (Google Fonts, etc.):** ```html ``` **2. Self-Hosted Fonts:** Include font files in your template ZIP: ```css @font-face { font-family: "CustomFont"; src: url("./fonts/custom.woff2") format("woff2"); } body { font-family: "CustomFont", sans-serif; } ``` **3. Base64 Embedded Fonts:** Embed font data directly in CSS (increases template size). **Best practices:** * Use common web fonts for faster rendering * Include fallback fonts: `font-family: 'CustomFont', Arial, sans-serif` * Optimize font files (use WOFF2 format) * Only include weights you actually use ### Can I use images in my templates? Absolutely! You can include images in multiple ways: **1. External URLs:** ```html Company Logo ``` **2. Base64 Encoded:** ```html Logo ``` **3. Bundled in Template:** Include images in your template ZIP file: ```html Logo ``` **4. Dynamic from Data:** ```html <%= product.name %> ``` **Performance tips:** * Optimize image sizes before including * Use appropriate formats (PNG for logos, JPEG for photos) * Consider lazy loading for multi-page documents * For frequently used logos, use external URLs (cached by CDN) ### How do I update an existing template? You can update templates in several ways: **Via Dashboard:** 1. Go to [My Templates](https://app.pogodoc.com/templates) 2. Click on the template options button on the template you want to edit 3. Make changes in the visual editor or code editor 4. Click "Save" - your changes are live immediately Or do it via our SDKs or API. ### Can I share templates with my team? Yes! Reusability is one of the key advantages of templates. *** ## Integration & Development ### Does Pogodoc integrate with other tools and platforms? Yes! Pogodoc is framework-agnostic and integrates seamlessly with: **Backend Frameworks:** * Node.js (Express, Fastify, NestJS) * Django, Flask, FastAPI (Python) * Laravel, Symfony (PHP) * ASP.NET Core (.NET) * Go (Gin, Echo, Chi) **Cloud Platforms:** * AWS Lambda, EC2, ECS * Google Cloud Functions, Cloud Run * Azure Functions, App Service * Heroku, Vercel, Netlify **CMS & Tools:** * WordPress, Drupal, Joomla * Strapi, Contentful, Sanity * Zapier, Make, n8n (automation) **Databases:** * PostgreSQL, MySQL, MongoDB * Any database you can query from your backend **APIs:** * REST APIs * GraphQL APIs * Webhooks Pogodoc provides a RESTful API, so it works with any platform that can make HTTP requests. See our [SDK documentation](/docs/sdks) for integration examples. ### Can I use Pogodoc with serverless functions? Absolutely! Pogodoc works great with serverless architectures: **Supported Platforms:** * AWS Lambda * Google Cloud Functions * Azure Functions * Vercel Serverless Functions * Netlify Functions * Cloudflare Workers **Example (AWS Lambda):** ```typescript import { PogodocClient } from "@pogodoc/sdk"; // Initialize outside handler for connection reuse const client = new PogodocClient({ token: process.env.POGODOC_API_TOKEN, }); export const handler = async (event) => { const document = await client.generateDocumentImmediate({ template: event.template, data: event.data, type: "ejs", target: "pdf", }); return { statusCode: 200, body: JSON.stringify({ documentUrl: document.url }), }; }; ``` **Best practices:** * Initialize SDK client outside handler (reuse connections) * Use environment variables for API tokens * Consider async generation for complex documents * Set appropriate timeout limits (30+ seconds for complex docs) See our [SDK guide](/docs/sdks) for more examples. ### Can I self-host Pogodoc? Yes! We offer **on-premise deployment** for Enterprise customers: **Enterprise On-Premise Features:** * Complete control over your infrastructure * Full data ownership and privacy * No external API calls * Custom security configurations * Air-gapped environments supported * Dedicated onboarding and support **Deployment Options:** * Docker containers * Kubernetes clusters * Traditional VM deployments * Cloud VPC deployments **Contact our sales team:** Email [contact@pogodoc.com](mailto:contact@pogodoc.com) to discuss on-premise deployment options, pricing, and support. *** ## Security & Privacy ### Is my data secure with Pogodoc? Yes! We take security seriously: **Cloud Security (Standard Plans):** * Hosted on **AWS** with enterprise-grade security * Data encrypted in transit (TLS 1.3) * Data encrypted at rest (AES-256) * Regular security audits and penetration testing * SOC 2 Type II compliance (in progress) * GDPR and CCPA compliant **Enterprise Security:** * **On-premise deployment** for complete control * Air-gapped environments supported * Custom security configurations * Dedicated security reviews * SSO/SAML integration * Audit logging **Data Handling:** * We don't store your document data longer than necessary * Generated documents are stored temporarily * You can delete documents immediately after generation * Templates are stored securely with access controls **Best practices:** * Use environment variables for API tokens * Rotate tokens regularly (quarterly recommended) * Implement least-privilege access controls * Monitor API usage for anomalies ### Where is my data stored? **Cloud Deployments (Standard Plans):** * Primary hosting: **AWS** **Data Storage:** * **Templates**: Stored securely in S3 and our databases * **Generated Documents**: S3-compatible storage with signed URLs * **Temporary Data**: Processing data is deleted after generation **Enterprise On-Premise:** * You control all data storage locations * No data leaves your infrastructure * Full data sovereignty * Works offline **Data Retention:** * Generated documents: 24 hours * Templates: Stored indefinitely until you delete them Contact [contact@pogodoc.com](mailto:contact@pogodoc.com) for custom data residency requirements. ### Are API tokens secure? Yes, when used properly. Follow these best practices: **βœ… DO:** * Store tokens in environment variables * Use secret management systems (AWS Secrets Manager, Azure Key Vault) * Rotate tokens quarterly * Use separate tokens per environment (dev, staging, prod) * Delete unused tokens immediately * Monitor token usage in the dashboard **❌ DON'T:** * Commit tokens to Git/version control * Share tokens publicly or in chat/email * Hardcode tokens in source code * Use the same token across all environments * Expose tokens in frontend code **If a token is compromised:** 1. Delete it immediately from the [dashboard](https://app.pogodoc.com/api-tokens) 2. Generate a new token 3. Update all applications with the new token 4. Review usage logs for suspicious activity 5. Contact support if needed Learn more in our [API Tokens documentation](/docs/api-tokens). *** ## Features & Capabilities ### Does Pogodoc support responsive design? Yes! Pogodoc supports responsive templates: **Dynamic Templates:** * Use CSS media queries for different screen sizes * Responsive layouts that adapt to content * Mobile-friendly designs **No-Code Editor:** * Our **visual editor** allows non-developers to create responsive templates * Drag-and-drop interface * Live preview for different sizes **Example Responsive Template:** ```css /* Desktop */ .container { width: 800px; } /* Tablet */ @media (max-width: 768px) { .container { width: 100%; } } /* Mobile */ @media (max-width: 480px) { .container { padding: 10px; } } ``` **Page Size Control:** * Set specific page sizes (A4, Letter, etc.) * Custom dimensions for any output format * Portrait or landscape orientation See our [Templates documentation](/docs/templates) for responsive design examples. ### Can I generate documents with charts and graphs? Yes! You can include dynamic charts and visualizations: **Chart Libraries:** * **Chart.js** - Popular canvas-based charts * **D3.js** - Powerful, flexible visualizations * **Recharts** - React charting library * **ApexCharts** - Modern, interactive charts **Example with Chart.js:** ```html ``` ### Can I add QR codes or barcodes to documents? Absolutely! You can generate QR codes and barcodes dynamically: **QR Codes:** ```html Order QR ``` **Using QR Code Libraries:** ```javascript // In your template const QRCode = require("qrcode"); const qrCodeUrl = await QRCode.toDataURL(orderData.url); ``` ```html QR Code ``` **Barcodes:** ```html ``` **Use cases:** * Order tracking codes * Product barcodes * Event tickets with QR codes * Payment links * Shipping labels ### Can I use AI to generate templates? Yes! Pogodoc includes **AI-powered template generation**: **AI Doc:** Follow the detailed explanation [here](/docs/templates#use-ai-doc-ejshtml-only). **AI Features:** * Natural language template generation * Automatic sample data creation * Smart layout suggestions * Style recommendations **Advanced AI Features:** * **Document-to-Template Conversion**: Upload an existing document (PDF, image) and AI extracts the template * **Mobile Scanning**: Use your phone to scan physical documents and convert to templates * **Version History**: AI tracks changes and allows reverting to previous versions * **AI Model Selection**: Choose between multiple models for different use cases Learn more in our [Managing Templates guide](/docs/templates). ### Can I schedule document generation? While Pogodoc doesn't have built-in scheduling, you can easily implement it: **Using Cron Jobs:** ```bash # Generate daily report at 8 AM 0 8 * * * /usr/bin/node /path/to/generate-report.js ``` **Using Task Schedulers:** * **Node.js**: node-cron, Agenda, Bull * **Python**: APScheduler, Celery * **Cloud**: AWS EventBridge, Google Cloud Scheduler, Azure Functions Timer **Example with node-cron:** ```typescript import cron from "node-cron"; import { PogodocClient } from "@pogodoc/sdk"; const client = new PogodocClient({ token: process.env.POGODOC_API_TOKEN }); // Run every day at 9 AM cron.schedule("0 9 * * *", async () => { const report = await client.generateDocument({ template: "daily-report", data: await fetchDailyData(), target: "pdf", }); await sendReportEmail(report.url); }); ``` **Webhook-Based Scheduling:** * Use services like Zapier or Make to trigger document generation * Set up scheduled workflows * Integrate with calendar events or other triggers *** ## Billing & Pricing ### Can I change plans at any time? Yes! You can upgrade or downgrade your plan anytime. Both upgrading or downgrading take effect at the end of your current billing cycle. If you cancel your subscription you can still enjoy your plan until the end of the billing cycle. **Manage your plan:** 1. Go to [app.pogodoc.com/profile](https://app.pogodoc.com/profile) 2. Click "Manage Subscription" or select a specific plan 3. Select your new plan 4. Confirm changes **Billing Cycles:** * Monthly billing * Annual billing (up to 50% discount) ### How does pay-as-you-go work? Pay-as-you-go starts once you have reached your plan limit for generated documents. Each document generation costs **$0.031415**. You can generate unlimited documents. You will be charged every time your pay-as-you-go generated documents accumulate to $10. If they don't you will be charged at the end of the billing cycle. You can use enjoy pay-as-you-go, while being on the **Free Plan** as well. *** ## Support & Community ### How do I get help if I'm stuck? We offer multiple support channels: **Documentation:** * Start with our [comprehensive docs](/docs) * Check this FAQ **Community Support:** * Join our [Discord server](https://discord.gg/pogodoc) * Ask questions and share solutions * Connect with other Pogodoc users **Email Support:** * Free/Starter: [contact@pogodoc.com](mailto:contact@pogodoc.com) (48-hour response) * Professional: Priority email support (24-hour response) * Enterprise: Dedicated support team (4-hour response) **Premium Support (Enterprise):** * Dedicated Slack channel * Direct access to engineering team * Phone support available * Custom SLAs **Emergency Support:** For production outages (Professional/Enterprise plans): * Email: [contact@pogodoc.com](mailto:contact@pogodoc.com) * Include: Account ID, error details, impact assessment ### Can I request new features? Absolutely! We love user feedback: **Feature Requests:** 1. Join our [Discord community](https://discord.gg/pogodoc) 2. Post in the #feature-requests channel 3. Vote on existing requests 4. Discuss with other users and our team **Direct Requests:** Email [contact@pogodoc.com](mailto:contact@pogodoc.com) with: * Detailed description of the feature * Your use case and why it's important * Expected behavior or examples * Willingness to beta test **Enterprise Customers:** * Direct input on our roadmap * Custom feature development available * Priority implementation for critical needs ### Are there any video tutorials or courses? Yes! We offer various learning resources: **Video Tutorials:** * [YouTube Channel](https://youtube.com/@pogodoc) - Getting started guides, feature demos * Quick start videos * Template design tutorials * Advanced techniques and best practices **Written Guides:** * [Blog](https://blog.pogodoc.com) - Tutorials, use cases, tips & tricks * Case studies from real users * Industry-specific guides (e.g., invoicing, reports) **Interactive Learning:** * Sample projects in our [GitHub organization](https://github.com/pogodoc) * Code snippets in the dashboard *** ## Additional Resources **Still have questions?** Don't hesitate to reach out: [contact@pogodoc.com](mailto:contact@pogodoc.com) # Custom SDK (/docs/sdks/create-your-own) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # Create Your Own SDK If an official SDK doesn't exist for your preferred programming language, you can easily build your own by wrapping the Pogodoc REST API. This guide explains the API call patterns and workflows used in our official SDKs. This guide follows the implementation patterns from the [TypeScript SDK](https://github.com/Pogodoc/pogodoc-ts/blob/main/src/index.ts). You can reference it while building your own SDK. **Built an SDK?** We'd love to feature it! Submit a PR to add your SDK to our official documentation, or reach out to us at [contact@pogodoc.com](mailto:contact@pogodoc.com). ## Authentication All API requests require authentication using a Bearer token: ```http Authorization: Bearer YOUR_API_TOKEN ``` Set the base URL to: ``` https://api.pogodoc.com ``` **Security Best Practice:** Never hardcode API tokens. Use environment variables or secure configuration management. ## Core Workflows There are three main workflows for document generation: 1. **Standard Generation** - Initialize job, upload data/template, start render, poll for completion 2. **Immediate Render** - Single API call for quick, synchronous rendering 3. **Template Management** - Upload, extract, preview, and save templates *** ## 1. Standard Document Generation This is the recommended workflow for most use cases. It provides reliability and handles larger documents well. ### High-Level Flow ### Initialize Render Job Create a new render job and get presigned URLs for uploading data and templates. **Endpoint:** `POST /documents/init` β†’ [API Reference](/docs/api-reference/initializeRenderJob) * Use `templateId` for saved templates * `presignedTemplateUploadUrl` is only provided if you're using an inline template (not a saved template) * `formatOpts` is optional ### Upload Data to S3 Upload your template data as JSON to the presigned S3 URL. This is a direct S3 upload - do **not** include the Authorization header. ### Upload Template (if inline) If you're using an inline template (not a saved template), upload it to S3. Skip this step if you're using a `templateId` - the template is already stored. ### Start Render Job Trigger the actual rendering process. **Endpoint:** `POST /documents/{jobId}/render` β†’ [API Reference](/docs/api-reference/startRenderJob) Set `shouldWaitForRenderCompletion: true` for synchronous rendering, but note this may timeout for large documents. ### Poll for Job Completion Repeatedly check the job status until it's complete. **Endpoint:** `GET /jobs/{jobId}` β†’ [API Reference](/docs/api-reference/getJobStatus) **Polling Strategy:** * Wait 1 second before first poll * Poll every 500ms * Maximum 60 attempts (30 seconds total) * Return final status even if not "done" ### Implementation Example (Pseudocode) ```javascript async function generateDocument(config) { // Step 1: Initialize const initResponse = await POST("/documents/init", { type: config.renderConfig.type, target: config.renderConfig.target, templateId: config.templateId, formatOpts: config.renderConfig.formatOpts, }); // Step 2: Upload data to S3 await PUT(initResponse.presignedDataUploadUrl, JSON.stringify(config.data), { "Content-Type": "application/json", }); // Step 3: Upload template to S3 (if inline) if (config.template && initResponse.presignedTemplateUploadUrl) { await PUT(initResponse.presignedTemplateUploadUrl, config.template, { "Content-Type": "text/html", }); } // Step 4: Start render await POST(`/documents/${initResponse.jobId}/render`, { shouldWaitForRenderCompletion: false, }); // Step 5: Poll for completion return await pollForCompletion(initResponse.jobId); } async function pollForCompletion(jobId, maxAttempts = 60, intervalMs = 500) { await sleep(1000); // Initial wait for (let i = 0; i < maxAttempts; i++) { const job = await GET(`/jobs/${jobId}`); if (job.status === "done") { return job; } await sleep(intervalMs); } // Return final status even if not complete return await GET(`/jobs/${jobId}`); } ``` *** ## 2. Immediate Render For small documents that need quick, synchronous rendering, use the immediate render endpoint. ### Single API Call **Endpoint:** `POST /documents/immediate-render` β†’ [API Reference](/docs/api-reference/startImmediateRender) **Limitations:** - May timeout for large or complex documents - No progress tracking - Not recommended for production use cases Use the standard generation workflow for reliability. ### Implementation Example (Pseudocode) ```javascript async function generateDocumentImmediate(config) { const response = await POST("/documents/immediate-render", { template: config.template, templateId: config.templateId, data: config.data, type: config.renderConfig.type, target: config.renderConfig.target, formatOpts: config.renderConfig.formatOpts, }); return response; } ``` *** ## 3. Template Management Save and update templates for reuse across multiple document generations. ### Saving a New Template ### Initialize Template Creation Get a template ID and presigned S3 upload URL. **Endpoint:** `GET /templates/init` β†’ [API Reference](/docs/api-reference/initializeTemplateCreation) ### Upload ZIP to S3 Upload your template ZIP file to the presigned URL. ### Extract Template Files Trigger extraction of the ZIP file. **Endpoint:** `PATCH /templates/{templateId}/unzip` β†’ [API Reference](/docs/api-reference/extractTemplateFiles) ### Generate Previews Create PDF and PNG previews using sample data. **Endpoint:** `POST /templates/{templateId}/render-previews` β†’ [API Reference](/docs/api-reference/generateTemplatePreviews) ### Finalize Template Save the template with metadata and get `templateId`. **Endpoint:** `POST /templates/{templateId}` β†’ [API Reference](/docs/api-reference/saveCreatedTemplate) ### Implementation Example (Pseudocode) ```javascript async function saveTemplate(filePath, metadata) { // Step 1: Initialize const initResponse = await GET("/templates/init"); const templateId = initResponse.templateId; // Step 2: Upload ZIP to S3 const fileData = readFile(filePath); const fileSize = getFileSize(filePath); await PUT(initResponse.presignedTemplateUploadUrl, fileData, { "Content-Type": "application/zip", "Content-Length": fileSize, }); // Step 3: Extract files await POST(`/templates/${templateId}/unzip`); // Step 4: Generate previews const previews = await POST(`/templates/${templateId}/render-previews`, { type: metadata.type, data: metadata.sampleData, }); // Step 5: Finalize template await POST(`/templates/${templateId}`, { templateInfo: { title: metadata.title, description: metadata.description, type: metadata.type, categories: metadata.categories, sampleData: metadata.sampleData, sourceCode: metadata.sourceCode, }, previewIds: { pdfJobId: previews.pdfPreview.jobId, pngJobId: previews.pngPreview.jobId, }, }); return templateId; } ``` ### Updating a Template The update flow is identical to saving, except: 1. You get a new `contentId` instead of `templateId` from init 2. Use `PUT /templates/{templateId}` ([API Reference](/docs/api-reference/updateTemplate)) instead of `POST` 3. Pass the original `templateId` in the URL, and the new `contentId` in the body ```javascript async function updateTemplate(templateId, filePath, metadata) { // Get new content ID const initResponse = await GET("/templates/init"); const contentId = initResponse.templateId; // Upload, extract, preview (same as save) // ... // Update template await PUT(`/templates/${templateId}`, { contentId: contentId, templateInfo: { /* metadata */ }, previewIds: { /* preview job IDs */ }, }); return contentId; } ``` *** ## Type Definitions ### Template Types * `react` - React/Vue/Angular/Svelte templates * `ejs` - Embedded JavaScript templates * `html` - Plain HTML templates * `latex` - LaTeX documents (🚧 coming soon) * `docx` - Word documents (🚧 coming soon) * `xlsx` - Excel spreadsheets (🚧 coming soon) * `pptx` - PowerPoint presentations (🚧 coming soon) ### Render Targets * `pdf` - PDF documents * `png` - PNG images * `jpg` - JPEG images (🚧 coming soon) * `html` - HTML output (🚧 coming soon) * `docx` - Word documents (🚧 coming soon) * `xlsx` - Excel spreadsheets (🚧 coming soon) * `pptx` - PowerPoint presentations (🚧 coming soon) ### Format Options ```typescript { format?: 'A3' | 'A4' | 'A5' | 'Letter' | 'Legal' | 'Tabloid'; waitForSelector?: string; // CSS selector to wait for fromPage?: number; // Starting page (partial render) toPage?: number; // Ending page (partial render) } ``` ### Job Status * `initialized` - Job created but not started * `in-progress` - Currently rendering * `done` - Rendering complete * `failed` - Rendering failed (check error details) **Built an SDK?** We'd love to feature it! Submit a PR to add your SDK to our official documentation, or reach out to us at [contact@pogodoc.com](mailto:contact@pogodoc.com). # .NET (/docs/sdks/dotnet) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # .NET SDK Complete documentation for the Pogodoc .NET SDK. This guide covers installation, configuration, all available methods, and advanced usage patterns. New to Pogodoc? Start with the [.NET Quickstart](/docs/get-started/dotnet) guide first. ## Quick Links * [Installation](#installation) * [Client Configuration](#client-configuration) * [Core Methods](#core-methods) * [Template Management](#template-management) * [Using Saved Templates](#using-saved-templates) * [Best Practices](#best-practices) * [Examples](#examples) ## Installation ```bash dotnet add package Pogodoc.Net ``` Or via NuGet Package Manager: ```bash Install-Package Pogodoc.Net ``` ## Client Configuration ### Basic Configuration ```csharp using Pogodoc.Net; var client = new PogodocClient("your-api-token"); ``` ### With Base URL ```csharp var client = new PogodocClient( token: "your-api-token", baseUrl: "https://api.pogodoc.com" ); ``` ### Environment Variables Configure using environment variables: ```csharp // Token from environment variables var token = Environment.GetEnvironmentVariable("POGODOC_API_TOKEN"); var client = new PogodocClient(token); ``` ```bash title="appsettings.json" { "Pogodoc": { "ApiToken": "your_token_here", "BaseUrl": "https://api.pogodoc.com" } } ``` The constructor requires a valid token. Ensure the token is provided either directly or via environment variables. ## Core Methods The SDK provides both synchronous and asynchronous methods for document generation and template management. ### GenerateDocumentAsync() The recommended method for most use cases. Generates a document and polls for completion automatically. ```csharp using Pogodoc.Net; var client = new PogodocClient("your-token"); var result = await client.GenerateDocumentAsync( templateId: "your-template-id", data: new Dictionary { ["name"] = "Jane Doe", ["amount"] = 1299.99 }, renderConfig: new RenderConfig { Type = TemplateType.React, Target = RenderTarget.Pdf } ); Console.WriteLine($"Document URL: {result.Output.Data.Url}"); ``` **Parameters:** * `template` (optional): Raw HTML/template string * `templateId` (optional): ID of a saved template * `data`: Dictionary containing data to populate the template * `renderConfig`: `RenderConfig` object with: * `Type`: Template format type * `Target`: Output format * `FormatOpts` (optional): Format-specific options **Important:** You must provide either `template` or `templateId`, but not both. Exactly one is required. **Returns:** `Task` - Job status with the final output URL ### GenerateDocumentImmediateAsync() For quick, synchronous rendering of small documents. Returns the result immediately without job polling. ```csharp var result = await client.GenerateDocumentImmediateAsync( templateId: "your-template-id", data: new Dictionary { ["name"] = "Jane Doe" }, renderConfig: new RenderConfig { Type = TemplateType.Ejs, Target = RenderTarget.Pdf } ); Console.WriteLine($"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 `GenerateDocumentAsync()` for larger documents or when reliability is critical. Use `GenerateDocumentImmediateAsync()` for small, quick renders. ### StartGenerateDocumentAsync() Lower-level method that only initializes the job. Use this if you want to implement custom polling logic. ```csharp var jobId = await client.StartGenerateDocumentAsync( templateId: "your-template-id", data: new Dictionary { ["name"] = "Jane Doe" }, renderConfig: new RenderConfig { Type = TemplateType.React, Target = RenderTarget.Pdf } ); Console.WriteLine($"Started job: {jobId}"); ``` **Important:** You must provide either `template` or `templateId`, but not both. Exactly one is required. **Returns:** `Task` - The job ID ### PollForJobCompletionAsync() Polls for the completion of a rendering job. Use with `StartGenerateDocumentAsync()` for custom workflows. ```csharp var result = await client.PollForJobCompletionAsync( jobId: jobId, maxAttempts: 60, // default: 60 intervalMs: 500 // default: 500 ); Console.WriteLine($"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) **Returns:** `Task` - The completed job response ## Template Management ### SaveTemplateAsync() Save a new template from a local ZIP file. ```csharp using System.IO; var templateInfo = new TemplateInfo { Title = "My Template", Description = "Invoice template for customers", Type = TemplateType.React, Categories = new[] { "invoice" }, SampleData = new Dictionary { ["name"] = "John Doe", ["amount"] = 1299.99 }, SourceCode = "https://github.com/yourorg/template" }; var templateId = await client.SaveTemplateAsync( filePath: "./path/to/template.zip", templateInfo: templateInfo ); Console.WriteLine($"Template saved with ID: {templateId}"); ``` **Parameters:** * `filePath`: Local file path to the ZIP file * `templateInfo`: Template metadata object **Returns:** `Task` - The new template ID ### SaveTemplateFromStreamAsync() Core method for saving templates from a stream. Useful for handling uploads in web applications. ```csharp using (var fileStream = File.OpenRead("./path/to/template.zip")) { var templateId = await client.SaveTemplateFromStreamAsync( stream: fileStream, templateInfo: templateInfo ); Console.WriteLine($"Template saved: {templateId}"); } ``` ### UpdateTemplateAsync() Update an existing template with a new version from a ZIP file. ```csharp var updateInfo = new TemplateInfo { Title = "My Updated Template", Description = "Updated invoice template", Type = TemplateType.React, Categories = new[] { "invoice", "updated" }, SampleData = new Dictionary { ["name"] = "John Doe", ["amount"] = 1599.99 } }; var contentId = await client.UpdateTemplateAsync( templateId: "existing-template-id", filePath: "./path/to/new-version.zip", templateInfo: updateInfo ); Console.WriteLine($"Template updated. New content ID: {contentId}"); ``` **Returns:** `Task` - Updated template content ID ### UpdateTemplateFromStreamAsync() Update a template from a stream. ```csharp using (var fileStream = File.OpenRead("./path/to/new-version.zip")) { var contentId = await client.UpdateTemplateFromStreamAsync( templateId: "existing-template-id", stream: fileStream, templateInfo: updateInfo ); Console.WriteLine($"New content ID: {contentId}"); } ``` ## Template Types Pogodoc supports multiple template formats for different use cases: | Type | Description | Best For | | ---------- | ------------------------------ | ------------------------------------- | | `React` | Any frontend JS framework | Complex layouts, reusable components | | `Ejs` | Embedded JavaScript templates | Simple variable substitution | | `Latex` 🚧 | LaTeX for scientific documents | Academic papers, mathematical content | | `Docx` 🚧 | Microsoft Word templates | Business documents, form letters | | `Xlsx` 🚧 | Microsoft Excel templates | Spreadsheets, data reports | | `Pptx` 🚧 | Microsoft PowerPoint templates | Presentations, 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](/docs/templates/js-framework) 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](/docs/templates/js-framework) Quick example of using a React template: ```csharp // Upload your built and zipped React template var templateId = await client.SaveTemplateAsync( filePath: "./my-react-template.zip", templateInfo: new TemplateInfo { Title = "Invoice Template", Type = TemplateType.React, Categories = new[] { "invoice" } } ); // Generate documents using the template var result = await client.GenerateDocumentAsync( templateId: templateId, data: new Dictionary { ["customer"] = new { Name = "Jane Smith" }, ["items"] = new[] { new { Name = "Service A", Price = 150.00 }, new { Name = "Service B", Price = 250.00 } }, ["total"] = 400.00 }, renderConfig: new RenderConfig { Type = TemplateType.React, Target = RenderTarget.Pdf } ); Console.WriteLine($"Document URL: {result.Output.Data.Url}"); ``` ### EJS/HTML Template EJS/HTML templates can be provided as inline strings: ```csharp var result = await client.GenerateDocumentAsync( template: @"

Hello <%= name %>

Your order #<%= orderId %> has been confirmed.

<% if (premium) { %>

Thank you for being a premium member!

<% } %> ", data: new Dictionary { ["name"] = "John Doe", ["orderId"] = 12345, ["premium"] = true }, renderConfig: new RenderConfig { Type = TemplateType.Ejs, Target = RenderTarget.Pdf } ); ``` ## Render Targets Generate documents in multiple output formats: | Target | Description | Use Cases | | --------- | ------------------------ | -------------------------------------- | | `Pdf` | PDF documents | Invoices, reports, printable documents | | `Png` | PNG images | Social media graphics, thumbnails | | `Jpg` 🚧 | JPEG images | Compressed images for web | | `Html` 🚧 | HTML output | Web previews, email content | | `Docx` 🚧 | Word documents | Editable business documents | | `Xlsx` 🚧 | Excel spreadsheets | Data reports, financial documents | | `Pptx` 🚧 | PowerPoint presentations | Slides, 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: ```csharp var result = await client.GenerateDocumentAsync( templateId: "invoice-template", data: invoiceData, renderConfig: new RenderConfig { Type = TemplateType.React, Target = RenderTarget.Pdf, FormatOpts = new FormatOptions { Format = "A4", WaitForSelector = ".ready", FromPage = 1, ToPage = 5 } } ); ``` ### Available Format Options | Option | Type | Description | | ----------------- | -------- | ------------------------------------------------ | | `Format` | `string` | Page format (A3, A4, A5, Letter, Legal, Tabloid) | | `WaitForSelector` | `string` | CSS selector to wait for before rendering | | `FromPage` | `int?` | Starting page number for partial renders | | `ToPage` | `int?` | Ending 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](https://app.pogodoc.com/templates) and create a new template. Save it and copy the template ID. ### Reference the Template ```csharp var result = await client.GenerateDocumentAsync( templateId: "your-template-id", data: new Dictionary { ["name"] = "John Doe", ["amount"] = 1299.99 }, renderConfig: new RenderConfig { Target = RenderTarget.Pdf } ); ``` ## Best Practices ### 1. Use Configuration Files Store API tokens in configuration files: ```csharp // appsettings.json { "Pogodoc": { "ApiToken": "your_token_here" } } // Program.cs var token = configuration["Pogodoc:ApiToken"]; var client = new PogodocClient(token); ``` ### 2. Use Saved Templates For production, use saved templates instead of inline templates: ```csharp // βœ… Good var result = await client.GenerateDocumentAsync( templateId: "invoice-v2", data: data, renderConfig: new RenderConfig { Target = RenderTarget.Pdf } ); // ❌ Less ideal - template in code var result = await client.GenerateDocumentAsync( template: "...", data: data, renderConfig: new RenderConfig { Type = TemplateType.Html, Target = RenderTarget.Pdf } ); ``` ### 3. Error Handling Always wrap SDK calls in try-catch blocks: ```csharp try { var result = await client.GenerateDocumentAsync( templateId: "invoice", data: data, renderConfig: new RenderConfig { Target = RenderTarget.Pdf } ); Console.WriteLine($"Document URL: {result.Output.Data.Url}"); } catch (Exception ex) { Console.WriteLine($"Document generation failed: {ex.Message}"); // Handle error appropriately } ``` ### 4. Use Dependency Injection Inject the client as a singleton in ASP.NET Core: ```csharp // Program.cs or Startup.cs services.AddSingleton(sp => { var token = configuration["Pogodoc:ApiToken"]; return new PogodocClient(token); }); // Controller public class InvoiceController : ControllerBase { private readonly IPogodocClient _pogodocClient; public InvoiceController(IPogodocClient pogodocClient) { _pogodocClient = pogodocClient; } [HttpPost("generate")] public async Task GenerateInvoice([FromBody] InvoiceData data) { var result = await _pogodocClient.GenerateDocumentAsync( templateId: "invoice-template", data: data.ToDictionary(), renderConfig: new RenderConfig { Target = RenderTarget.Pdf } ); return Ok(new { url = result.Output.Data.Url }); } } ``` ## Examples ### Invoice Generation ```csharp public async Task GenerateInvoiceAsync( PogodocClient client, InvoiceData invoiceData) { var result = await client.GenerateDocumentAsync( templateId: "invoice-template", data: new Dictionary { ["invoiceNumber"] = invoiceData.Number, ["customer"] = invoiceData.Customer, ["items"] = invoiceData.Items, ["subtotal"] = invoiceData.Subtotal, ["tax"] = invoiceData.Tax, ["total"] = invoiceData.Total, ["date"] = DateTime.Now.ToString("MM/dd/yyyy") }, renderConfig: new RenderConfig { Target = RenderTarget.Pdf, FormatOpts = new FormatOptions { Format = "A4" } } ); return result.Output.Data.Url; } ``` ### Social Media Graphics ```csharp public async Task GenerateSocialGraphicAsync( PogodocClient client, PostData post) { var result = await client.GenerateDocumentAsync( templateId: "social-media-card", data: new Dictionary { ["title"] = post.Title, ["author"] = post.Author, ["image"] = post.FeaturedImage }, renderConfig: new RenderConfig { Target = RenderTarget.Png } ); return result.Output.Data.Url; } ``` ### Batch Document Generation ```csharp public async Task> GenerateMultipleDocumentsAsync( PogodocClient client, List> dataList) { var urls = new List(); foreach (var data in dataList) { try { var result = await client.GenerateDocumentAsync( templateId: "report-template", data: data, renderConfig: new RenderConfig { Type = TemplateType.React, Target = RenderTarget.Pdf } ); urls.Add(result.Output.Data.Url); } catch (Exception ex) { Console.WriteLine($"Failed to generate document: {ex.Message}"); continue; } } return urls; } ``` ### Using with Dependency Injection ```csharp public class DocumentService : IDocumentService { private readonly IPogodocClient _client; private readonly ILogger _logger; public DocumentService( IPogodocClient client, ILogger logger) { _client = client; _logger = logger; } public async Task GenerateDocumentAsync( string templateId, object data) { try { var result = await _client.GenerateDocumentAsync( templateId: templateId, data: ConvertToDict(data), renderConfig: new RenderConfig { Target = RenderTarget.Pdf } ); _logger.LogInformation( "Generated document: {Url}", result.Output.Data.Url ); return result.Output.Data.Url; } catch (Exception ex) { _logger.LogError(ex, "Failed to generate document"); throw; } } private Dictionary ConvertToDict(object data) { // Convert object to dictionary using your preferred method // (e.g., System.Text.Json, Newtonsoft.Json, reflection) return JsonSerializer.Deserialize>( JsonSerializer.Serialize(data) ); } } ``` ## Next Steps # Golang (/docs/sdks/golang) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # 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](/docs/get-started/golang) guide first. ## Quick Links * [Installation](#installation) * [Client Configuration](#client-configuration) * [Core Methods](#core-methods) * [Template Management](#template-management) * [Using Saved Templates](#using-saved-templates) * [Best Practices](#best-practices) * [Examples](#examples) ## Installation ```bash go get github.com/Pogodoc/pogodoc-go ``` ## Client Configuration ### Basic Configuration ```go 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: | Method | Description | | --------------------------------------------- | --------------------------------------------------------- | | `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: ```go // Token from environment variables client, err := pogodoc.PogodocClientInit() if err != nil { log.Fatal(err) } ``` ```bash title=".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. ```go ctx := context.Background() template := `

Hello <%= name %>

` 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. ```go 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. ```go 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. ```go 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. ```go 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. ```go 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. ```go 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. ```go contentId, err := client.UpdateTemplateFromFileStream("existing-template-id", fsProps, metadata, ctx) ``` ## Template Types Pogodoc supports multiple template formats for different use cases: | Type | Description | Best For | | ---------- | ------------------------------ | ------------------------------------- | | `react` | Any frontend JS framework | Complex layouts, reusable components | | `ejs` | Embedded JavaScript templates | Simple variable substitution | | `latex` 🚧 | LaTeX for scientific documents | Academic papers, mathematical content | | `docx` 🚧 | Microsoft Word templates | Business documents, form letters | | `xlsx` 🚧 | Microsoft Excel templates | Spreadsheets, data reports | | `pptx` 🚧 | Microsoft PowerPoint templates | Presentations, 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](/docs/templates/js-framework) 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](/docs/templates/js-framework) Quick example of using a React template: ```go // 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: ```go template := `

Hello <%= name %>

Your order #<%= orderId %> has been confirmed.

<% if (premium) { %>

Thank you for being a premium member!

<% } %> ` 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: | Target | Description | Use Cases | | --------- | ------------------------ | -------------------------------------- | | `pdf` | PDF documents | Invoices, reports, printable documents | | `png` | PNG images | Social media graphics, thumbnails | | `jpg` 🚧 | JPEG images | Compressed images for web | | `html` 🚧 | HTML output | Web previews, email content | | `docx` 🚧 | Word documents | Editable business documents | | `xlsx` 🚧 | Excel spreadsheets | Data reports, financial documents | | `pptx` 🚧 | PowerPoint presentations | Slides, 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: ```go 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 | Option | Type | Description | | ----------------- | --------- | ------------------------------------------------ | | `Format` | `*string` | Page format (A3, A4, A5, Letter, Legal, Tabloid) | | `WaitForSelector` | `*string` | CSS selector to wait for before rendering | | `FromPage` | `*int` | Starting page number for partial renders | | `ToPage` | `*int` | Ending 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](https://app.pogodoc.com/templates) and create a new template. Save it and copy the template ID. ### Reference the Template ```go 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: ```go // βœ… 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: ```go // βœ… 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 := `...` 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: ```go 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: ```go // With timeout ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second) defer cancel() result, err := client.GenerateDocument(props, ctx) ``` ## Examples ### Invoice Generation ```go 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 ```go 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 ```go 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 # Overview (/docs/sdks) import { Card, Cards } from "fumadocs-ui/components/card"; # SDKs Overview Pogodoc provides official SDKs for popular programming languages, making it easy to integrate document generation into your applications. Each SDK is fully typed, well-documented, and follows best practices for the respective language. ## Available SDKs # PHP (/docs/sdks/php) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # PHP SDK Complete documentation for the Pogodoc PHP SDK. This guide covers installation, configuration, all available methods, and advanced usage patterns. New to Pogodoc? Start with the [PHP Quickstart](/docs/get-started/php) guide first. ## Quick Links * [Installation](#installation) * [Client Configuration](#client-configuration) * [Core Methods](#core-methods) * [Template Management](#template-management) * [Using Saved Templates](#using-saved-templates) * [Best Practices](#best-practices) * [Examples](#examples) ## Installation ```bash composer require pogodoc/pogodoc-php ``` ## Client Configuration ### Basic Configuration ```php The constructor will throw an `InvalidArgumentException` 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. ```php $response = $client->generateDocument([ 'templateId' => 'your-template-id', 'data' => [ 'name' => 'Jane Doe', 'amount' => 1299.99, ], 'renderConfig' => [ 'type' => 'react', 'target' => 'pdf', ] ]); echo "Document URL: " . $response->output->data->url; ``` **Parameters (array):** * `template` (optional): Raw HTML/template string * `templateId` (optional): ID of a saved template * `data`: Array containing data to populate the template * `renderConfig`: Configuration array with: * `type`: Template format type * `target`: Output format * `formatOpts` (optional): Format-specific options **Important:** You must provide either `template` or `templateId`, 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. ```php $response = $client->generateDocumentImmediate([ 'templateId' => 'your-template-id', 'data' => ['name' => 'Jane Doe'], 'renderConfig' => [ 'type' => 'ejs', 'target' => 'pdf', ] ]); echo "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. ```php $jobId = $client->startGenerateDocument([ 'templateId' => 'your-template-id', 'data' => ['name' => 'Jane Doe'], 'renderConfig' => [ 'type' => 'react', 'target' => 'pdf', ] ]); echo "Started job: " . $jobId; ``` **Important:** You must provide either `template` or `templateId`, but not both. Exactly one is required. **Returns:** `string` - The job ID ### pollForJobCompletion() Polls for the completion of a rendering job. Use with `startGenerateDocument()` for custom workflows. ```php $result = $client->pollForJobCompletion( $jobId, 60, // maxAttempts (default: 60) 500 // intervalMs (default: 500) ); echo "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. ```php $templateId = $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', ]); echo "Template saved with ID: " . $templateId; ``` **Parameters (array):** * `path`: Local file path to the ZIP file * `title`: Template title * `description`: Template description * `type`: Template format type (see [Template Types](#template-types)) * `categories`: Array of category strings * `sampleData`: Sample data for generating previews * `sourceCode` (optional): Link to source code **Returns:** `string` - The new template ID ### saveTemplateFromFileStream() Core method for saving templates from a stream. Useful for handling uploads in web applications. ```php $zipStream = fopen('./path/to/template.zip', 'rb'); $zipLength = filesize('./path/to/template.zip'); $templateId = $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. ```php $contentId = $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, ], ]); echo "Template updated. New content ID: " . $contentId; ``` **Returns:** `string` - The content ID of the new template version ### updateTemplateFromFileStream() Update a template from a file stream. ```php $contentId = $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: | Type | Description | Best For | | ---------- | ------------------------------ | ------------------------------------- | | `react` | Any frontend JS framework | Complex layouts, reusable components | | `ejs` | Embedded JavaScript templates | Simple variable substitution | | `latex` 🚧 | LaTeX for scientific documents | Academic papers, mathematical content | | `docx` 🚧 | Microsoft Word templates | Business documents, form letters | | `xlsx` 🚧 | Microsoft Excel templates | Spreadsheets, data reports | | `pptx` 🚧 | Microsoft PowerPoint templates | Presentations, 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](/docs/templates/js-framework) 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](/docs/templates/js-framework) Quick example of using a React template: ```php // Upload your built and zipped React template $templateId = $client->saveTemplate([ 'path' => './my-react-template.zip', 'title' => 'Invoice Template', 'type' => 'react', 'categories' => ['invoice'], ]); // Generate documents using the template $result = $client->generateDocument([ 'templateId' => $templateId, 'data' => [ 'customer' => ['name' => 'Jane Smith'], 'items' => [ ['name' => 'Service A', 'price' => 150.00], ['name' => 'Service B', 'price' => 250.00], ], 'total' => 400.00, ], 'renderConfig' => [ 'type' => 'react', 'target' => 'pdf', ], ]); echo "Document URL: " . $result->output->data->url; ``` ### EJS/HTML Template EJS/HTML templates can be provided as inline strings: ```php $response = $client->generateDocument([ 'template' => '

Hello <%= name %>

Your order #<%= orderId %> has been confirmed.

<% if (premium) { %>

Thank you for being a premium member!

<% } %> ', 'data' => [ 'name' => 'John Doe', 'orderId' => 12345, 'premium' => true, ], 'renderConfig' => [ 'type' => 'ejs', 'target' => 'pdf', ], ]); ``` ## Render Targets Generate documents in multiple output formats: | Target | Description | Use Cases | | --------- | ------------------------ | -------------------------------------- | | `pdf` | PDF documents | Invoices, reports, printable documents | | `png` | PNG images | Social media graphics, thumbnails | | `jpg` 🚧 | JPEG images | Compressed images for web | | `html` 🚧 | HTML output | Web previews, email content | | `docx` 🚧 | Word documents | Editable business documents | | `xlsx` 🚧 | Excel spreadsheets | Data reports, financial documents | | `pptx` 🚧 | PowerPoint presentations | Slides, 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: ```php $result = $client->generateDocument([ 'templateId' => 'invoice-template', 'data' => $invoiceData, 'renderConfig' => [ 'type' => 'react', 'target' => 'pdf', 'formatOpts' => [ 'format' => 'A4', 'waitForSelector' => '.ready', 'fromPage' => 1, 'toPage' => 5, ], ], ]); ``` ### Available Format Options | Option | Type | Description | | ----------------- | -------- | ------------------------------------------------ | | `format` | `string` | Page format (A3, A4, A5, Letter, Legal, Tabloid) | | `waitForSelector` | `string` | CSS selector to wait for before rendering | | `fromPage` | `int` | Starting page number for partial renders | | `toPage` | `int` | Ending 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](https://app.pogodoc.com/templates) and create a new template. Save it and copy the template ID. ### Reference the Template ```php $response = $client->generateDocument([ 'templateId' => 'your-template-id', 'data' => [ 'name' => 'John Doe', 'amount' => 1299.99, ], 'renderConfig' => [ 'target' => 'pdf', ], ]); ``` ## Best Practices ### 1. Environment Variables Always store API tokens in environment variables: ```php // βœ… Good $client = new PogodocSdk(); // ❌ Bad - hardcoded token $client = new PogodocSdk('sk-abc123...'); ``` ### 2. Use Saved Templates For production, use saved templates instead of inline templates: ```php // βœ… Good $result = $client->generateDocument([ 'templateId' => 'invoice-v2', 'data' => $data, 'renderConfig' => ['target' => 'pdf'], ]); // ❌ Less ideal - template in code $result = $client->generateDocument([ 'template' => '...', 'data' => $data, 'renderConfig' => ['type' => 'html', 'target' => 'pdf'], ]); ``` ### 3. Error Handling Always wrap SDK calls in try-catch blocks: ```php try { $result = $client->generateDocument($options); echo "Document URL: " . $result->output->data->url; } catch (Exception $e) { error_log("Document generation failed: " . $e->getMessage()); // Handle error appropriately } ``` ### 4. Resource Management Close file streams after use: ```php $zipStream = fopen('./template.zip', 'rb'); try { $templateId = $client->saveTemplateFromFileStream([ 'payload' => $zipStream, // ... other params ]); } finally { fclose($zipStream); } ``` ## Examples ### Invoice Generation ```php function generateInvoice($client, $invoiceData) { $response = $client->generateDocument([ 'templateId' => 'invoice-template', 'data' => [ 'invoiceNumber' => $invoiceData['number'], 'customer' => $invoiceData['customer'], 'items' => $invoiceData['items'], 'subtotal' => $invoiceData['subtotal'], 'tax' => $invoiceData['tax'], 'total' => $invoiceData['total'], 'date' => date('Y-m-d'), ], 'renderConfig' => [ 'target' => 'pdf', 'formatOpts' => [ 'format' => 'A4', ], ], ]); return $response->output->data->url; } ``` ### Social Media Graphics ```php function generateSocialGraphic($client, $post) { $response = $client->generateDocument([ 'templateId' => 'social-media-card', 'data' => [ 'title' => $post['title'], 'author' => $post['author'], 'image' => $post['featured_image'], ], 'renderConfig' => [ 'target' => 'png', ], ]); return $response->output->data->url; } ``` ### Batch Document Generation ```php function generateMultipleDocuments($client, $dataList) { $urls = []; foreach ($dataList as $data) { try { $result = $client->generateDocument([ 'templateId' => 'report-template', 'data' => $data, 'renderConfig' => [ 'type' => 'react', 'target' => 'pdf', ], ]); $urls[] = $result->output->data->url; } catch (Exception $e) { error_log("Failed to generate document: " . $e->getMessage()); continue; } } return $urls; } ``` ## Next Steps # Python (/docs/sdks/python) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; # 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](/docs/get-started/python) guide first. ## Quick Links * [Installation](#installation) * [Client Configuration](#client-configuration) * [Core Methods](#core-methods) * [Template Management](#template-management) * [Using Saved Templates](#using-saved-templates) * [Best Practices](#best-practices) * [Examples](#examples) ## Installation ```bash pip install pogodoc ``` ## Client Configuration ### Basic Configuration ```python from pogodoc import PogodocClient client = PogodocClient(token='your-api-token') ``` ### Environment Variables The SDK automatically reads environment variables: ```python # Token from environment variables client = PogodocClient() ``` ```bash title=".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. ```python 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. ```python 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. ```python 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. ```python 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. ```python 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. ```python 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. ```python 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. ```python 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: | Type | Description | Best For | | ---------- | ------------------------------ | ------------------------------------- | | `react` | Any frontend JS framework | Complex layouts, reusable components | | `ejs` | Embedded JavaScript templates | Simple variable substitution | | `latex` 🚧 | LaTeX for scientific documents | Academic papers, mathematical content | | `docx` 🚧 | Microsoft Word templates | Business documents, form letters | | `xlsx` 🚧 | Microsoft Excel templates | Spreadsheets, data reports | | `pptx` 🚧 | Microsoft PowerPoint templates | Presentations, 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](/docs/templates/js-framework) 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](/docs/templates/js-framework) Quick example of using a React template: ```python # 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: ```python result = client.generate_document( template='''

Hello <%= name %>

Your order #<%= orderId %> has been confirmed.

<% if (premium) { %>

Thank you for being a premium member!

<% } %> ''', data={ 'name': 'John Doe', 'orderId': 12345, 'premium': True, }, render_config=RenderConfig( type='ejs', target='pdf', ) ) ``` ## Render Targets Generate documents in multiple output formats: | Target | Description | Use Cases | | --------- | ------------------------ | -------------------------------------- | | `pdf` | PDF documents | Invoices, reports, printable documents | | `png` | PNG images | Social media graphics, thumbnails | | `jpg` 🚧 | JPEG images | Compressed images for web | | `html` 🚧 | HTML output | Web previews, email content | | `docx` 🚧 | Word documents | Editable business documents | | `xlsx` 🚧 | Excel spreadsheets | Data reports, financial documents | | `pptx` 🚧 | PowerPoint presentations | Slides, 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: ```python 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 | Option | Type | Description | | ----------------- | ----- | ------------------------------------------------ | | `format` | `str` | Page format (A3, A4, A5, Letter, Legal, Tabloid) | | `waitForSelector` | `str` | CSS selector to wait for before rendering | | `fromPage` | `int` | Starting page number for partial renders | | `toPage` | `int` | Ending 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](https://app.pogodoc.com/templates) and create a new template. Save it and copy the template ID. ### Reference the Template ```python 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: ```python # βœ… Good client = PogodocClient() # ❌ Bad - hardcoded token client = PogodocClient(token='sk-abc123...') ``` ### 2. Use Saved Templates For production, use saved templates instead of inline templates: ```python # βœ… 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='...', data=data, render_config=RenderConfig(type='html', target='pdf') ) ``` ### 3. Error Handling Always wrap SDK calls in try-except blocks: ```python 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: ```python 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 ```python 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 ```python 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 ```python 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 # TypeScript (/docs/sdks/typescript) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # 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](/docs/get-started/typescript) guide first. ## Quick Links * [Installation](#installation) * [Client Configuration](#client-configuration) * [Core Methods](#core-methods) * [Template Management](#template-management) * [Using Saved Templates](#using-saved-templates) * [Best Practices](#best-practices) * [Examples](#examples) ## 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 ```typescript import { PogodocClient } from "@pogodoc/sdk"; const client = new PogodocClient({ token: "your-api-token", }); ``` ### Configuration Options | Option | Type | Default | Description | | ------- | -------- | ------- | ------------------------------------ | | `token` | `string` | - | **Required**. Your Pogodoc API token | ### Environment Variables The SDK automatically reads environment variables: ```typescript // Token and base URL from environment variables const client = new PogodocClient(); ``` ```bash title=".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. ```typescript 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` with the final job status including output URL ### generateDocumentImmediate() For quick, synchronous rendering of small documents. Returns the result immediately without job polling. ```typescript 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. ```typescript 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` - The job ID ### pollForJobCompletion() Polls for the completion of a rendering job. Use with `startGenerateDocument()` for custom workflows. ```typescript 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. ```typescript 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](#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` - The new template ID ### saveTemplateFromFileStream() Core method for saving templates from a stream. Useful for handling uploads in web applications. ```typescript 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. ```typescript 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` - The content ID of the new template version ### updateTemplateFromFileStream() Update a template from a file stream. ```typescript 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: | Type | Description | Best For | | ---------- | ------------------------------ | ------------------------------------- | | `react` | Any frontend JS framework | Complex layouts, reusable components | | `ejs` | Embedded JavaScript templates | Simple variable substitution | | `latex` 🚧 | LaTeX for scientific documents | Academic papers, mathematical content | | `docx` 🚧 | Microsoft Word templates | Business documents, form letters | | `xlsx` 🚧 | Microsoft Excel templates | Spreadsheets, data reports | | `pptx` 🚧 | Microsoft PowerPoint templates | Presentations, 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](/docs/templates/js-framework) 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](/docs/templates/js-framework) Quick example of using a React template: ```typescript // 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: ```typescript const result = await client.generateDocument({ template: `

Hello <%= name %>

Your order #<%= orderId %> has been confirmed.

<% if (premium) { %>

Thank you for being a premium member!

<% } %> `, data: { name: "John Doe", orderId: 12345, premium: true, }, renderConfig: { type: "ejs", target: "pdf", }, }); ``` ## Render Targets Generate documents in multiple output formats: | Target | Description | Use Cases | | --------- | ------------------------ | -------------------------------------- | | `pdf` | PDF documents | Invoices, reports, printable documents | | `png` | PNG images | Social media graphics, thumbnails | | `jpg` 🚧 | JPEG images | Compressed images for web | | `html` 🚧 | HTML output | Web previews, email content | | `docx` 🚧 | Word documents | Editable business documents | | `xlsx` 🚧 | Excel spreadsheets | Data reports, financial documents | | `pptx` 🚧 | PowerPoint presentations | Slides, presentations | 🚧 **Coming Soon:** JPG, HTML, DOCX, XLSX, and PPTX render targets are currently in development and will be available soon. ### Specifying Output Format ```typescript 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: ```typescript 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 | Option | Type | Description | | ----------------- | -------- | ------------------------------------------------ | | `format` | `string` | Page format (A3, A4, A5, Letter, Legal, Tabloid) | | `waitForSelector` | `string` | CSS selector to wait for before rendering | | `fromPage` | `number` | Starting page number for partial renders | | `toPage` | `number` | Ending page number for partial renders | ### Personal Upload URL You can provide your own S3 presigned URL to upload the generated document to your storage: ```typescript 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: ```typescript import type { PogodocClient, GenerateDocumentProps, RenderTarget, TemplateFormatType, SaveTemplateMetadata, UpdateTemplateProps, Categories, } from "@pogodoc/sdk"; ``` ### GenerateDocumentProps ```typescript 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 ```typescript type TemplateFormatType = | "docx" | "xlsx" | "pptx" | "ejs" | "html" | "latex" | "react"; ``` ### RenderTarget ```typescript type RenderTarget = "pdf" | "html" | "docx" | "xlsx" | "pptx" | "png" | "jpg"; ``` ### SaveTemplateMetadata ```typescript 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](https://app.pogodoc.com/templates) and create a new template. Save it and copy the template ID. ### Reference the Template ```typescript 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: ```typescript // βœ… 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: ```typescript // βœ… Good const result = await client.generateDocument({ templateId: "invoice-v2", data, renderConfig: { target: "pdf" }, }); // ❌ Less ideal - template in code const result = await client.generateDocument({ template: `...`, data, renderConfig: { type: "html", target: "pdf" }, }); ``` ### 3. Error Handling Always wrap SDK calls in try-catch blocks: ```typescript 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: ```typescript 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 ```typescript 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 ```typescript 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 ```typescript 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 (

{title}

{metrics.map(metric => (

{metric.name}

{metric.value}

))} {charts.map(chart => ( ))}
); } `, data: reportData, renderConfig: { type: "react", target: "pdf", options: { format: "A4", landscape: true, }, }, }); return response.output?.data.url; }; ``` ## Next Steps # EJS/HTML Templates (/docs/templates/ejs) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # EJS/HTML Templates [EJS (Embedded JavaScript)](https://ejs.co/) and plain HTML templates provide a simple, straightforward way to create documents without the complexity of a JavaScript framework build process. Perfect for invoices, receipts, certificates, and other documents with straightforward layouts. EJS templates are ideal for simple documents with variable substitution. For complex layouts with reusable components, consider using [JavaScript Framework Templates](/docs/templates/js-framework). ## Overview EJS and HTML templates offer: * **No build process required** - Write and use immediately * **Simple syntax** - Easy to learn and maintain * **Inline templates** - Pass templates directly in API calls * **Quick iteration** - Fast development cycle ## Template Types ### EJS Templates EJS (Embedded JavaScript) allows you to embed JavaScript expressions and logic directly in your HTML: ```html

Hello, <%= customerName %>!

<% if (isPremium) { %>

Thank you for being a premium member!

<% } %> ``` ### Plain HTML Templates Plain HTML with no templating logic, useful for static content: ```html

Certificate of Completion

This certifies that the holder has completed the course.

``` *** ## Creating EJS Templates ## Write Your Template Create an HTML file with EJS syntax for dynamic content. ```html title="invoice-template.ejs" Invoice

INVOICE

Invoice #<%= invoiceNumber %>

Date: <%= date %>

Bill To:

<%= customer.name %>

<%= customer.address %>

<%= customer.city %>, <%= customer.state %> <%= customer.zip %>

<% items.forEach(function(item) { %> <% }); %>
Description Quantity Price Total
<%= item.description %> <%= item.quantity %> $<%= item.price.toFixed(2) %> $<%= (item.quantity * item.price).toFixed(2) %>
Subtotal: $<%= subtotal.toFixed(2) %>
Tax (<%= taxRate %>%): $<%= tax.toFixed(2) %>
Total: $<%= total.toFixed(2) %>
```
```html title="receipt-template.ejs" Receipt

<%= storeName %>

<%= storeAddress %>

Tel: <%= storePhone %>

Receipt #<%= receiptNumber %>

<%= date %> <%= time %>

<% items.forEach(function(item) { %>
<%= item.name %> x<%= item.quantity %> $<%= (item.price * item.quantity).toFixed(2) %>
<% }); %>
Subtotal: $<%= subtotal.toFixed(2) %>
Tax: $<%= tax.toFixed(2) %>
TOTAL: $<%= total.toFixed(2) %>
Payment Method: <%= paymentMethod %>
```
```html title="certificate-template.ejs" Certificate
CERTIFICATE
of <%= certificateType %>

This is to certify that

<%= recipientName %>
has successfully completed
<%= courseName %>
<%= description %>

Awarded on <%= date %>

Certificate ID: <%= certificateId %>

<%= instructorName %>

Instructor

<%= organizationName %>

Organization

```
**Pro Tip:** For faster development, first create your template as a plain HTML with data filled. Then, replace your data with EJS placeholders. **Pro Tip:** To preview how Pogodoc will render a PDF document you can use `Ctrl/Cmd + P` in your browser and preview how it would look like.
## Use as Inline Template You can pass EJS templates directly in the [SDKs](/docs/sdks) or our [API](/docs/api-reference/saveCreatedTemplate). ## Save as Template (Best Practice) For templates you'll reuse, save them to your Pogodoc account. Follow ["Creating Templates"](/docs/templates#creating-templates). Or, save templates through the [SDKs](/docs/sdks) or our [API](/docs/api-reference/saveCreatedTemplate).
## EJS Syntax Reference ### Variables Output a variable value: ```html

Hello, <%= name %>!

``` ### Unescaped Output Output raw HTML (be careful with user input): ```html
<%- htmlContent %>
``` ### Conditionals ```html <% if (isPremium) { %>

Premium member benefits

<% } else { %>

Upgrade to premium

<% } %> ``` ### Loops ```html
    <% items.forEach(function(item) { %>
  • <%= item.name %> - $<%= item.price %>
  • <% }); %>
``` ### Functions ```html <% function formatPrice(price) { return '$' + price.toFixed(2); } %>

Total: <%= formatPrice(total) %>

``` ### Comments ```html <%# This is a comment and won't appear in output %> ``` ## Best Practices ### 1. Use Inline Styles CSS classes may not work reliably in PDFs. Always use inline styles or `
Content
``` ### 2. Include DOCTYPE and Charset Always include proper HTML document structure: ```html Document Title ``` ### 3. Use Absolute Units Use pixels (px) or points (pt) instead of relative units: ```html
``` ### 4. Validate Data Always check if data exists before using it: ```html <% if (customer && customer.name) { %>

Customer: <%= customer.name %>

<% } %> ``` ### 5. Format Numbers Use JavaScript functions to format numbers properly: ```html

Price: $<%= price.toFixed(2) %>

Discount: <%= (discount * 100).toFixed(0) %>%

Total: $<%= total.toLocaleString('en-US', {minimumFractionDigits: 2}) %>

``` ### 6. Handle Arrays Safely Check if arrays exist and have items: ```html <% if (items && items.length > 0) { %>
    <% items.forEach(function(item) { %>
  • <%= item.name %>
  • <% }); %>
<% } else { %>

No items found.

<% } %> ``` ## Common Patterns ### Tables with Totals ```html <% items.forEach(function(item) { %> <% }); %>
Item Price
<%= item.name %> $<%= item.price.toFixed(2) %>
Total: $<%= total.toFixed(2) %>
``` ### Conditional Styling ```html
Status: <%= isPaid ? 'Paid' : 'Unpaid' %>
``` ### Date Formatting ```html <% var date = new Date(); var formattedDate = date.toLocaleDateString('en-US', { year: 'numeric', month: 'long', day: 'numeric' }); %>

Date: <%= formattedDate %>

``` ### Multi-Page Documents ```html

Page 1

Content for first page

Page 2

Content for second page

Page 3

Content for last page

``` ## Troubleshooting ### Template Not Rendering * Verify EJS syntax is correct (matching `<%` and `%>`) * Check for JavaScript errors in conditional logic * Ensure all variables exist in the data object * Test template syntax using an online EJS tester ### Variables Not Showing * Confirm variable names match exactly (case-sensitive) * Check that data is being passed correctly * Use `<%= JSON.stringify(data) %>` to debug data structure ### Styling Issues * Use inline styles or `

Certificate of Achievement

This certificate is awarded to

Outstanding Performance

Presented this day

``` ## Examples ## Next Steps # Managing Templates (/docs/templates) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # Managing Templates The Pogodoc Dashboard provides a powerful interface for creating, editing, and managing your document templates. Whether you're building templates from scratch, editing existing ones, or using community templates, the dashboard makes it easy to manage your entire template library. The visual editor, AI Doc, and preview features are available for **EJS/HTML templates only**. React/JavaScript framework templates can be uploaded but will not have preview or visual editing capabilities. ## Template Dashboard Overview Access your templates at [app.pogodoc.com/templates](https://app.pogodoc.com/templates). The dashboard is divided into two main sections: * **My Templates** - Your personal template library * **Community** - Curated templates from Pogodoc and the community *** ## Creating Templates There are multiple ways to create templates in the Pogodoc Dashboard: ### Start a New Template Click the **"+"** button or the large **"Create Template"** card to begin. New Template Button You'll be presented with the Create/Edit template workflow. ### Create/Edit Workflow There are multiple features that this workflow offers: * **Create from scratch** - Start from blank * **Use AI Doc** - Describe your template and let AI generate it * **Upload from mobile** - Scan a physical document with your phone * **Upload existing** - Upload a ZIP file (for JS framework templates or existing EJS/HTML templates) * **Editor** - Edit templates with a no-code drag and drop editor * **Sample Data** - Edit sample data that will fill your template Create Workflow Here you can start by uploading a template. It must be a `.zip` folder that includes your template. This is a requirement for both EJS/HTML templates and JS Framework templates. Or, you can start talking with AI Doc and describe the template you want. ### Use AI Doc (EJS/HTML Only) The AI chatbot helps you create or modify templates using natural language. AI Chatbot Interface **How it works:** 1. Describe what you want: *"Create an invoice template with line items, totals, and a company logo section"* 2. The chatbot generates the HTML/EJS code 3. Preview updates in real-time on the right side 4. Refine with follow-up requests: *"Make the header blue and add tax calculation"* 5. Continue iterating until satisfied **Example prompts:** * "Create a receipt template for a coffee shop" * "Add a signature line at the bottom" * "Change the table styling to have alternating row colors" * "Add a watermark that says 'PAID' when status is paid" #### Advanced Chatbot Features **Upload Images or Files** Upload reference documents to help the AI understand your desired template: Upload Document * Option 1: Click the **Upload file from computer** button in the chat interface\\ * Option 2: Drag and drop files directly into the chat, or paste them in the chat * Option 3: Click on **Upload file from phone** to upload from your mobile device: 1. Scan the QR code with your phone's camera 2. Open the link 3. Take a picture of your document, select an image from your gallery or upload a file 4. Click on "Send to AI Doc" 5. The image will pop-up in your chat Scan QR **Pro Tip:** For best results, photograph documents on a flat surface with good lighting and minimal shadows. AI Doc analyzes your document and: * Extracts the layout and structure * Identifies text fields and data placeholders * Recreates the styling (fonts, colors, spacing) * Generates clean EJS/HTML code Supported file types: * Images (PNG, JPG, PDF) * Documents (PDF, Word, Excel) * Existing templates for reference **Version History During Creation** The chatbot automatically saves each response as a version: * Every AI response creates a new version * Click **"Revert"** to go back to any previous response * Compare different iterations side-by-side * No changes are lost - all versions are preserved during creation Restore version This lets you experiment freely and return to earlier versions if needed. **Select AI Models** Choose from different AI models for template generation. Switch models mid-conversation if one works better for your use case. Some model may **require** a different subscription plan. **Note:** AI chatbot features are only available for EJS/HTML templates. React templates must be built using your local development environment. ### Use the Visual Editor (EJS/HTML Only) Switch to the **"Editor"** tab for a no-code visual editing experience. You can switch to the "Preview" tab at any time to preview how your document will look like, when it is filled with the data found in the "Data" Visual Editor Interface **Note:** When you want to create placeholders for your data. The text element you create with your editor must have EJS nomenclature. Follow [EJS documentation](https://ejs.co/). The visual editor provides: #### Text Styling * Font family, size, and color * Bold, italic, underline * Text alignment * Line height and spacing #### Layout Management * Add/remove sections * Adjust margins and padding * Set widths and heights * Position elements #### Design Elements * Background colors * Borders and border radius * Shadows and effects * Box sizing #### Images & Media * Upload images * Position and resize * Add alt text * Image styling #### Tables * Insert tables * Style headers and cells * Add/remove rows and columns * Cell padding and borders #### Dynamic Content * Insert data placeholders * Add conditional sections * Loop through arrays * Format numbers and dates The visual editor generates clean EJS/HTML code that you can further customize in the code view if needed. ### Edit Sample Data Switch to the **"Data"** tab to define the sample data for your template. Data Editor The data editor lets you: * Edit JSON directly with syntax highlighting * Define the structure of data your template expects * Test different data scenarios * See live preview updates in the "Preview" tab as you change data **Example data structure:** ```json { "my_company_info": { "logo": "https://image_link.png", "name": "Kodhen DOOEL Skopje", "address": "Mito HadΕΎivasiliev Jasmin br.18", "city": "Skopje", "zip": "1000", "country": "North Macedonia" }, "bill_to_company": { "name": "CODE CHEMISTRY INC.", "address": "Apt 14, 3670 Rue Saint-Hubert", "city": "Montreal, Quebec", "zip": "H2L0G5", "country": "Canada" }, "invoice_info": { "number": "1101", "date": "02-03-2020", "due_payment": "02-03-2020", "due_amount": "1.00", "currency": "$", "currency_code": "USD" }, "items": [ { "name": "Development hours 1", "price": "1.00", "amount": "1.00", "quantity": 1 } ] } ``` This sample data is used to generate the preview when you save your template. ### Preview Your Template Click the **"Preview"** tab to see how your template renders. Template Preview Preview is only available for EJS/HTML templates. React templates must be tested locally before uploading. ### Save Your Template Click **"Save Template"** to finalize and save to your library. Save Template Dialog You'll need to provide: #### Required Information * **Title** - A descriptive name for your template * **Type** - Select template type: * `ejs` - EJS templates * `html` - Plain HTML templates * `react` - JavaScript framework templates * `latex`, `docx`, `xlsx`, `pptx` (coming soon) #### Optional Metadata * **Category** - Tag your template (invoice, cv, receipt, certificate, etc.) * **Description** - Detailed explanation of the template's purpose After saving, you'll receive: * A unique **Template ID** for API usage * Access to edit or delete the template Template IDs are immutable and can be used immediately in your API calls. *** ## Managing Your Templates Access all your templates from the **"My Templates"** tab. ### Template Actions Template Options Each template card provides quick actions and detailed view: #### 1. Edit Template Click on any template to open it in the create/edit workflow. You can: * Modify the design using the chatbot or visual editor * Update sample data * Change template metadata #### 2. Download Template Download the template files for local editing or backup: * **Download Template** - Get the ZIP file containing your template * **Download Sample Data** - Get the JSON file with sample data #### 3. Copy Template ID Quickly copy the `template ID` to use in your code with SDKs or our API. #### 4. Use Generated Code This tab offers a quick code snippet that you can use through our [SDKs](/docs/sdks). Simply copy and paste the code into your application! #### 5. Favorite Templates Star your most-used templates for quick access. Favorites appear at the top of your template list. #### 6. Delete Template Remove templates you no longer need. This action is permanent and cannot be undone. **Warning:** Deleting a template does not affect documents already generated from it, but the template ID will no longer work for new documents. ### Sorting and Filtering Organize your templates using: * **Sort by:** Name, Date Created, Date Modified, Most Used * **Filter by Type:** EJS, HTML, React, All * **Search:** Find templates by name or description * **Favorites only:** Show only starred templates *** ## Community Templates Access professionally designed templates from the **"Community"** tab. ### What are Community Templates? Community templates are: * **Curated by Pogodoc** - High-quality templates built by our team * **Community contributed** - Templates shared by other Pogodoc users * **Free to use** - Available to all Pogodoc users * **Customizable** - Clone and modify to fit your needs If you want to use a community template. Click on **"Clone"** and this template will apear in "My Templates". Then you can continue editing your template. Community templates are starting points. Feel free to customize them extensively to match your specific requirements. *** ## Best Practices ### 1. Use Descriptive Names Give your templates clear, descriptive names: ``` βœ… Good: "Invoice - Modern Blue Theme" ❌ Bad: "Template 1" ``` ### 2. Organize with Categories Use categories to group similar templates. ### 3. Maintain Sample Data Keep sample data up-to-date and realistic: * Use real-world examples * Include edge cases (long names, many items, etc.) * Test with actual data before deploying ### 4. Document Your Templates Add detailed descriptions: * What the template is for * Required data fields * Special formatting requirements * Any custom logic or calculations ### 5. Test Before Production Always test templates thoroughly: * Generate PDFs with various data sets * Check page breaks and layout * Verify all data placeholders work * Test on mobile and desktop ### 6. Backup Important Templates Download template files for backup: * Keep local copies of critical templates * Store sample data separately * Document any custom configurations ## Troubleshooting ### Template Won't Save * Check all required fields are filled * Ensure sample data is valid JSON * Verify template syntax is correct * Try refreshing the page ### Preview Not Showing * EJS/HTML templates only support preview * Check for syntax errors in your template * Verify sample data is properly formatted * Clear browser cache and reload ### Code Snippets Not Copying * Try using the manual copy button * Check browser clipboard permissions * Refresh the page and try again *** ## Next Steps # JavaScript Framework Templates (/docs/templates/js-framework) import { Card, Cards } from "fumadocs-ui/components/card"; import { Step, Steps } from "fumadocs-ui/components/steps"; import { Callout } from "fumadocs-ui/components/callout"; import { Tab, Tabs } from "fumadocs-ui/components/tabs"; # JavaScript Framework Templates Pogodoc allows you to leverage the power and flexibility of React, Vue, Angular, Svelte, or any JavaScript framework to create dynamic and complex document templates. This guide will walk you through the process of setting up a JavaScript framework project to be used as a Pogodoc template. Any JavaScript framework that builds to static HTML works! This guide uses React as an example, but the same principles apply to Vue, Angular, Svelte, and others. ## Overview Unlike simple template strings (like EJS or HTML), JavaScript framework templates require: 1. A build process to compile your components 2. Packaging the build output as a ZIP file 3. Uploading the ZIP to Pogodoc ## Project Setup While you can use any React setup (like Create React App, Next.js in static export mode, or a custom webpack configuration), we recommend using **Vite** for a fast and straightforward setup. Create a new React project with TypeScript using Vite: ```bash npm create vite@latest my-react-template -- --template react-ts cd my-react-template npm install ``` ```bash npm create vite@latest my-vue-template -- --template vue-ts cd my-vue-template npm install ``` ```bash npm create vite@latest my-svelte-template -- --template svelte-ts cd my-svelte-template npm install ``` This creates a new directory with a basic project structure. ## Accessing Template Data When Pogodoc renders your template, it injects the JSON data you provide into the `window` object under the `__POGODOC_DATA__` property. To access this data in a type-safe way, create a helper file. Create `src/config.ts`: ```typescript title="src/config.ts" declare global { interface Window { // eslint-disable-next-line @typescript-eslint/no-explicit-any __POGODOC_DATA__: any; } } export const pogodocData = window.__POGODOC_DATA__; ``` This declares a global `__POGODOC_DATA__` property on the window object and exports the data for easy use throughout your application. You can also create a proper TypeScript interface for your data instead of using `any` for better type safety. ## Create Your Template Now you can import and use the data in any of your components. ```typescript title="src/App.tsx" import { pogodocData } from './config'; function App() { return (

Invoice for {pogodocData.customer.name}

{pogodocData.items.map((item: any, i: number) => ( ))}
Item Price
{item.name} \${item.price.toFixed(2)}

Total: \${pogodocData.total.toFixed(2)}

); } export default App; ```
```vue title="src/App.vue" ``` ```svelte title="src/App.svelte"

Invoice for {pogodocData.customer.name}

{#each pogodocData.items as item, i} {/each}
Item Price
{item.name} \${item.price.toFixed(2)}

Total: \${pogodocData.total.toFixed(2)}

```
## Build Your Template After creating your template, build it to generate the static HTML, CSS, and JavaScript files. Run the build command: ```bash npm run build ``` This creates a `dist` directory containing your bundled application. ## Package as ZIP Zip the **contents** of the `dist` folder (not the `dist` folder itself). ```bash cd dist zip -r ../my-template.zip . cd .. ``` **Important:** Only the contents of the `dist` folder should be zipped, not the `dist` folder itself. The root of your ZIP should contain `index.html`, not a `dist/` folder. ## Upload to Pogodoc Save your template to your Pogodoc account. Follow ["Creating Templates"](/docs/templates#creating-templates). Or, save templates through the [SDKs](/docs/sdks) or our [API](/docs/api-reference/saveCreatedTemplate). ## Generate Documents Now you can generate documents using the `templateId` of your saved template.
## Best Practices ### 1. Inline Styles For documents (especially PDFs), use inline styles instead of CSS classes: ```typescript // βœ… Good - inline styles
Content
// ❌ Bad - CSS classes might not work
Content
``` ### 2. Absolute Units Use absolute units (px, pt, cm) instead of relative units (rem, em, %) for consistent sizing: ```typescript // βœ… Good - absolute units
Content
// ❌ Bad - relative units
Content
``` ### 3. Avoid External Resources Include all assets (images, fonts) in your ZIP or use data URLs: ```typescript // βœ… Good - base64 image Logo // ❌ Bad - external URL might not load Logo ``` ### 4. Test Locally Before uploading, test your template locally: ```bash npm run build npm run develop ``` Make sure it renders correctly in the browser before uploading to Pogodoc. **Pro Tip:** To preview how Pogodoc will render a PDF document you can use `Ctrl/Cmd + P` in your browser and preview how it would look like. ## Framework-Specific Tips ### React * Use `create-react-app` or `vite` for setup * Avoid hooks that depend on browser APIs (like `useEffect` with timers) * Use React 18+ for best compatibility ### Vue * Use `create-vue` or `vite` for setup * Avoid lifecycle hooks that depend on browser timing * Use Vue 3+ for best compatibility ### Angular * Use Angular CLI for setup * Configure for production build with `ng build --prod` * Disable animations that might not work in PDF rendering ### Svelte * Use `vite` with Svelte template * Avoid stores that depend on browser APIs * Use Svelte 3+ for best compatibility ## Troubleshooting ### Template Not Rendering * Check that `index.html` is at the root of your ZIP * Verify `window.__POGODOC_DATA__` is being accessed correctly * Check browser console for errors in preview ### Styling Issues * Ensure all styles are inline or in `