PHP
Complete reference for the Pogodoc PHP SDK with types, advanced configuration, and examples
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 guide first.
Quick Links
- Installation
- Client Configuration
- Core Methods
- Template Management
- Using Saved Templates
- Best Practices
- Examples
Installation
composer require pogodoc/pogodoc-phpClient Configuration
Basic Configuration
<?php
require __DIR__ . '/vendor/autoload.php';
use PogodocSdk\PogodocSdk;
$client = new PogodocSdk('your-api-token');Environment Variables
The SDK automatically reads environment variables:
// Token from environment variables
$client = new PogodocSdk();POGODOC_API_TOKEN=your_token_here
POGODOC_BASE_URL=https://api.pogodoc.com # OptionalThe 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.
$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 stringtemplateId(optional): ID of a saved templatedata: Array containing data to populate the templaterenderConfig: Configuration array with:type: Template format typetarget: Output formatformatOpts(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.
$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.
$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.
$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 pollmaxAttempts: 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.
$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 filetitle: Template titledescription: Template descriptiontype: Template format type (see Template Types)categories: Array of category stringssampleData: Sample data for generating previewssourceCode(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.
$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.
$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.
$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 for detailed setup instructions.
🚧 Coming Soon: LaTeX, DOCX, XLSX, and PPTX template types are currently in development and will be available soon.
JavaScript Framework Templates
JavaScript framework templates require a build process and must be uploaded as ZIP files. See the complete guide: JavaScript Framework Templates
Quick example of using a React template:
// Upload your built and zipped React template
$templateId = $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:
$response = $client->generateDocument([
'template' => '
<h1>Hello <%= name %></h1>
<p>Your order #<%= orderId %> has been confirmed.</p>
<% if (premium) { %>
<p>Thank you for being a premium member!</p>
<% } %>
',
'data' => [
'name' => 'John Doe',
'orderId' => 12345,
'premium' => true,
],
'renderConfig' => [
'type' => 'ejs',
'target' => 'pdf',
],
]);Render Targets
Generate documents in multiple output formats:
| 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:
$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 and create a new template. Save it and copy the template ID.
Reference the Template
$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:
// ✅ 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:
// ✅ Good
$result = $client->generateDocument([
'templateId' => 'invoice-v2',
'data' => $data,
'renderConfig' => ['target' => 'pdf'],
]);
// ❌ Less ideal - template in code
$result = $client->generateDocument([
'template' => '<html>...</html>',
'data' => $data,
'renderConfig' => ['type' => 'html', 'target' => 'pdf'],
]);3. Error Handling
Always wrap SDK calls in try-catch blocks:
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:
$zipStream = fopen('./template.zip', 'rb');
try {
$templateId = $client->saveTemplateFromFileStream([
'payload' => $zipStream,
// ... other params
]);
} finally {
fclose($zipStream);
}Examples
Invoice Generation
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
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
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;
}