### Create Browser Instance Example Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Example of creating a browser instance with custom arguments and protocol timeout. ```javascript const browser = await createBrowser({ browserArgs: ['--disable-dev-shm-usage'], protocolTimeout: 120000, }); ``` -------------------------------- ### Install polotno-node Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/README.md Install the polotno-node library using npm. This is the first step before using the library in your Node.js project. ```bash npm install polotno-node ``` -------------------------------- ### Install FFmpeg on Windows Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToVideoBase64.md Instructions for installing FFmpeg on Windows. Download the binaries from the official FFmpeg website. This is required for video export. ```bash # Download from https://ffmpeg.org/download.html ``` -------------------------------- ### Install FFmpeg on macOS, Ubuntu, and Windows Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/errors.md Resolves 'FFmpeg: No such file or directory' errors by ensuring FFmpeg is installed and accessible in the system's PATH. Includes installation commands for different operating systems. ```bash # macOS brew install ffmpeg # Ubuntu/Debian apt-get install ffmpeg # Windows (download from https://ffmpeg.org/download.html) # Or use Chocolatey: choco install ffmpeg ``` ```bash ffmpeg -version ffprobe -version ``` -------------------------------- ### Browser Setup Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/COMPLETION_REPORT.txt Details on setting up a browser environment for Polotno operations, crucial for rendering and manipulation. ```APIDOC ## createBrowser ### Description Sets up a browser environment required for Polotno operations that involve rendering or interacting with browser-like functionalities. ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import Polotno from '@polotno/polotno-node'; await Polotno.createBrowser({ // browser configuration options }); ``` ### Response #### Success Response None (operates as a side effect) #### Response Example None ``` -------------------------------- ### Docker Memory Limits Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/instance-lifecycle.md A Dockerfile example that installs Chromium and FFmpeg, sets Node.js memory limits using NODE_OPTIONS, and prepares the application for containerized deployment. ```bash # Dockerfile with memory limits FROM node:18-alpine RUN apk add --no-cache chromium ffmpeg WORKDIR /app COPY package.json . RUN npm install # Limit memory to container allocation ENV NODE_OPTIONS=--max-old-space-size=2048 COPY . . CMD ["node", "server.js"] ``` -------------------------------- ### Custom Puppeteer Setup with Polotno Args Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/args.md Shows how to integrate polotno-node's optimized `args` with a custom Puppeteer setup, combining them with arguments from `@sparticuz/chromium` for a comprehensive browser configuration. ```javascript const { args } = require('polotno-node'); const chromium = require('@sparticuz/chromium'); const puppeteer = require('puppeteer-core'); // Combine chromium.args with polotno-node's args const browser = await puppeteer.launch({ args: [...chromium.args, ...args], defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath(), headless: true, ignoreHTTPSErrors: true, }); const instance = await createInstance({ key: 'your-key', browser, }); ``` -------------------------------- ### Install FFmpeg on Ubuntu/Debian Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToVideoBase64.md Install FFmpeg on Ubuntu or Debian systems using apt-get. This is required for video export. ```bash apt-get install ffmpeg ``` -------------------------------- ### Export Polotno JSON to PNG Source: https://github.com/polotno-project/polotno-node/blob/master/README.md This example demonstrates how to create a Polotno instance, load a JSON design, and export it as a PNG image. Ensure you have a 'polotno.json' file in your project. ```javascript const fs = require('fs'); const { createInstance } = require('polotno-node'); async function run() { // create working instance const instance = await createInstance({ // this is a demo key just for that project // (!) please don't use it in your projects // to create your own API key please go here: https://polotno.dev/cabinet key: 'nFA5H9elEytDyPyvKL7T', }); // load sample json const json = JSON.parse(fs.readFileSync('polotno.json')); const imageBase64 = await instance.jsonToImageBase64(json); fs.writeFileSync('out.png', imageBase64, 'base64'); // close instance instance.close(); } run(); ``` -------------------------------- ### Low-Latency Streaming with Progress Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToVideoDataURL.md This example demonstrates how to optimize for low-latency video streaming by adjusting `fps` and `pixelRatio`. It also includes an `onProgress` callback to monitor the rendering status. ```javascript const dataUrl = await instance.jsonToVideoDataURL(json, { fps: 24, // Balanced FPS for lower latency pixelRatio: 1, onProgress: (progress, frameTime) => { console.log(`Rendered ${Math.round(progress * 100)}%`); }, }); // Use in video player res.json({ videoUrl: dataUrl }); ``` -------------------------------- ### Install @sparticuz/chromium-min Source: https://github.com/polotno-project/polotno-node/blob/master/README.md Installs the @sparticuz/chromium-min package to reduce function size, useful for cloud providers with deployment limits. Ensure chromium binary caching is enabled. ```bash npm install @sparticuz/chromium-min ``` -------------------------------- ### Export First Page as PNG Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToImageBase64.md This example demonstrates how to export the first page of a Polotno design as a PNG image data URL and save it to a file. ```javascript const { createInstance } = require('polotno-node'); const fs = require('fs'); const instance = await createInstance({ key: 'your-key' }); const json = JSON.parse(fs.readFileSync('design.json')); const dataUrl = await instance.jsonToImageBase64(json); // dataUrl is "data:image/png;base64,iVBORw0KGgo..." const base64 = dataUrl.split('base64,')[1]; fs.writeFileSync('output.png', base64, 'base64'); await instance.close(); ``` -------------------------------- ### Usage Example: Creating and Converting JSON to Image Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Demonstrates how to construct a RenderJSON object and use it to generate a base64 encoded image. Requires an instance of Polotno. ```javascript const json = { pages: [ { id: 'page-1', width: 1920, height: 1080, children: [ // Design elements here ], }, ], audios: [ { id: 'audio-1', src: 'https://example.com/audio.mp3', }, ], }; const imageBase64 = await instance.jsonToImageBase64(json); ``` -------------------------------- ### Instance Management Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/COMPLETION_REPORT.txt APIs for managing Polotno instances, including creation and browser setup. ```APIDOC ## createInstance() ### Description Main entry point for creating a Polotno instance. This function initializes the necessary components for rendering and exporting content. ### Method (Not specified, likely a function call in a Node.js environment) ### Endpoint (Not applicable, SDK function) ### Parameters (Details not provided in source, but mentioned as 'Complete with all options') ### Request Example (Not provided in source) ### Response (Not provided in source) ## createBrowser() ### Description Creates a browser instance for Polotno operations. This is a prerequisite for many rendering and export tasks. ### Method (Not specified, likely a function call in a Node.js environment) ### Endpoint (Not applicable, SDK function) ### Parameters (Details not provided in source, but mentioned as 'Complete with all options') ### Request Example (Not provided in source) ### Response (Not provided in source) ## args (exported constant) ### Description Provides a constant list of browser arguments used by Polotno. This is useful for understanding or customizing browser launch configurations. ### Method (Not specified, likely an exported constant) ### Endpoint (Not applicable, SDK constant) ### Parameters (Not applicable) ### Request Example (Not provided in source) ### Response (Not provided in source) ## createPage() ### Description Manually creates a page within a Polotno instance. This is an advanced usage scenario for more granular control over the rendering environment. ### Method (Not specified, likely a method on a Polotno instance) ### Endpoint (Not applicable, SDK function) ### Parameters (Details not provided in source, but mentioned as 'with advanced usage') ### Request Example (Not provided in source) ### Response (Not provided in source) ``` -------------------------------- ### Install FFmpeg on macOS Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToVideoBase64.md Install FFmpeg on macOS using Homebrew. This is required for video export. ```bash brew install ffmpeg ``` -------------------------------- ### Example Usage of RenderOptions Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Demonstrates how to use the RenderOptions to export a JSON object to a base64 encoded image. This example shows setting specific options like pageId, pixelRatio, mimeType, quality, and skipFontError. ```javascript const imageBase64 = await instance.jsonToImageBase64(json, { pageId: 'page-123', pixelRatio: 2, mimeType: 'image/jpeg', quality: 0.9, skipFontError: true, }); ``` -------------------------------- ### Verify Polotno Node Installation Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/errors.md Check if the necessary Polotno client files are present in `node_modules/polotno-node/dist/`. This is a prerequisite for resolving 'ReferenceError: store is not defined'. ```javascript // Ensure polotno-node dist files exist: // node_modules/polotno-node/dist/index.html // node_modules/polotno-node/dist/assets/* ``` -------------------------------- ### Usage Example for Video/GIF Export Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Shows how to use VideoRenderOptions to export a JSON canvas to a video base64 string, configuring frames per second, pixel ratio, and a progress callback. ```javascript const videoBase64 = await instance.jsonToVideoBase64(json, { fps: 60, // Smooth 60 FPS pixelRatio: 2, onProgress: (progress, frameTime) => { console.log(`${Math.round(progress * 100)}% (${frameTime}ms per frame)`) }, }); ``` -------------------------------- ### Configure Polotno Settings using window.config Source: https://github.com/polotno-project/polotno-node/blob/master/README.md Access and modify Polotno settings globally via `window.config` before loading JSON or exporting. Example shows enabling vertical text resizing. ```js const url = await instance.run(async (json) => { // you can use global "config" object that has some functions from "polotno/config" module window.config.setTextVerticalResizeEnabled(true); // you can use global "store" object store.loadJSON(json); return store.toDataURL(); }, json); ``` -------------------------------- ### Correct Usage: Single Page with run() Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/run.md This example shows the correct way to use `run()`, ensuring all operations occur within the same page context. All logic, including the final export, is performed within a single `run()` call. ```javascript // ✅ RIGHT - Same page context const imageBase64 = await instance.run(async (json) => { store.loadJSON(json); await store.waitLoading(); return await store.toImageBase64(); }, json); ``` -------------------------------- ### Browser Arguments Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/COMPLETION_REPORT.txt Information about the arguments that can be passed during browser setup for fine-grained control. ```APIDOC ## args ### Description Provides details on the arguments that can be used when setting up the browser environment with `createBrowser`. ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import Polotno from '@polotno/polotno-node'; await Polotno.createBrowser({ args: [ '--no-sandbox', '--disable-setuid-sandbox' ] }); ``` ### Response #### Success Response None (describes configuration options) #### Response Example None ``` -------------------------------- ### Create Polotno Instance with Request Interceptor Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Example of creating a Polotno instance with an API key, parallel pages, font caching, and a request interceptor to modify headers for Google Fonts requests. ```javascript const instance = await createInstance({ key: 'your-key', useParallelPages: true, useFontCache: true, requestInterceptor: (request) => { if (request.url().includes('fonts.googleapis.com')) { request.continue({ headers: { ...request.headers(), 'User-Agent': 'Custom' }, }); } else { request.continue(); } }, }); ``` -------------------------------- ### AWS Lambda Configuration Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/instance-lifecycle.md Example of creating a Polotno instance with parallel pages enabled, suitable for AWS Lambda. Includes recommended Lambda settings for memory, timeout, and ephemeral storage. ```javascript // Lambda constraints const instance = await createInstance({ key: 'your-key', useParallelPages: true, // OK for Lambda }); // Recommended settings: // Memory: 3008 MB (max, needed for complex designs) // Timeout: 300 seconds (5 minutes, increase for videos) // Ephemeral storage: 10240 MB (max, for temp files) ``` -------------------------------- ### Incorrect Usage: Multiple Pages with run() Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/run.md This example demonstrates the wrong way to use `run()`, resulting in two separate pages and loss of the first export. Ensure all operations are within a single `run()` call to maintain context. ```javascript // ❌ WRONG - Two separate pages, first export is lost await instance.run(async (json) => { store.loadJSON(json); await store.waitLoading(); }, json); const imageBase64 = await instance.jsonToImageBase64(json); // Different page! ``` -------------------------------- ### Add Custom Arguments to Polotno Setup Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/args.md Demonstrates how to append custom command-line arguments to the existing `args` from polotno-node and `@sparticuz/chromium` when launching Puppeteer. This is useful for environment-specific configurations like AWS Lambda. ```javascript const { args } = require('polotno-node'); const chromium = require('@sparticuz/chromium'); const customArgs = [ '--disable-dev-shm-usage', // AWS Lambda '--single-process', // Development/testing ]; const browser = await puppeteer.launch({ args: [...chromium.args, ...args, ...customArgs], defaultViewport: chromium.defaultViewport, executablePath: await chromium.executablePath(), headless: true, }); ``` -------------------------------- ### Configure Custom Client URL Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/errors.md Set a custom URL for the Polotno client if not using the default installation. Ensure the URL is publicly accessible and serves the correct HTML structure. ```javascript const instance = await createInstance({ key: 'your-key', url: 'https://your-domain.com/editor', // Ensure this URL: // 1. Is publicly accessible // 2. Returns HTML with
// 3. Has window.store available }); ``` -------------------------------- ### Filter Arguments for Custom Setup Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/args.md Illustrates how to filter the default `args` array to remove specific arguments, such as disabling the GPU, before passing them to Puppeteer's `launch` configuration. This allows for fine-tuning browser behavior. ```javascript const { args } = require('polotno-node'); // Remove GPU disabling for hardware acceleration const customArgs = args.filter(arg => arg !== '--disable-gpu'); const browser = await puppeteer.launch({ args: [...chromium.args, ...customArgs], // ... other options }); ``` -------------------------------- ### API Server for Design Export (Express.js) Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/README.md This example sets up an Express.js server to handle design export requests. It supports exporting to PDF or PNG based on the 'format' field in the request body. Ensure the POLOTNO_KEY is set and the server listens on port 3000. ```javascript const express = require('express'); const { createInstance } = require('polotno-node'); const app = express(); const instance = await createInstance({ key: process.env.POLOTNO_KEY }); app.post('/api/export', async (req, res) => { try { const { json, format } = req.body; let result; if (format === 'pdf') { result = await instance.jsonToPDFBase64(json); res.set('Content-Type', 'application/pdf'); } else { result = await instance.jsonToImageBase64(json); res.set('Content-Type', 'image/png'); } res.send(Buffer.from(result, 'base64')); } catch (error) { res.status(400).json({ error: error.message }); } }); app.listen(3000); ``` -------------------------------- ### InstanceOptions Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Configuration for instance creation with `createInstance()`. ```APIDOC ## InstanceOptions Configuration for instance creation with `createInstance()`. ### Properties | Property | Type | Default | Description | |---|---|---|---| | key | `string` | — | Polotno API key. Required unless using custom client with `url` | | url | `string` | Built-in client | URL of custom Polotno Client Editor. If provided, `key` is optional | | useParallelPages | `boolean` | `true` | Enable parallel page creation for concurrent renders. `false` = single page, sequential only | | browserArgs | `string[]` | `[]` | Additional browser arguments appended to defaults | | browser | `Browser` | Auto-created | Puppeteer browser instance. If not provided, `createBrowser()` is called | | requestInterceptor | `function` | — | Function to intercept network requests: `(request: Request) => void`. Useful for modifying headers or blocking resources | | useFontCache | `boolean` | `true` | Cache Google Fonts in memory and disk across renders. Improves performance for parallel renders | ### Usage ```javascript const instance = await createInstance({ key: 'your-key', useParallelPages: true, useFontCache: true, requestInterceptor: (request) => { if (request.url().includes('fonts.googleapis.com')) { request.continue({ headers: { ...request.headers(), 'User-Agent': 'Custom' }, }); } else { request.continue(); } }, }); ``` ``` -------------------------------- ### Use with createBrowser() Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/args.md Demonstrates how to use the `createBrowser` function, which internally utilizes the optimized `args` from polotno-node. No explicit handling of `args` is needed when using this function. ```javascript const { createBrowser } = require('polotno-node'); // createBrowser() automatically uses args internally const browser = await createBrowser(); ``` -------------------------------- ### Install Google Chrome on EC2 Source: https://github.com/polotno-project/polotno-node/blob/master/README.md Installs Google Chrome on an EC2 instance to resolve font loading issues. This is a workaround for EC2 environments. ```bash curl https://intoli.com/install-google-chrome.sh | bash ``` -------------------------------- ### Create Browser with Default Settings Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/createBrowser.md Creates a browser instance using default Polotno Node settings. This instance can then be used with createInstance. ```javascript const { createBrowser } = require('polotno-node'); const browser = await createBrowser(); // Use with createInstance const instance = await createInstance({ key: 'your-key', browser, }); await instance.close(); ``` -------------------------------- ### Instance Creation Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/COMPLETION_REPORT.txt Documentation for creating a new Polotno instance, which is the primary entry point for most operations. ```APIDOC ## createInstance ### Description Creates a new instance of the Polotno editor. This is the primary entry point for interacting with the library. ### Method Not applicable (SDK function) ### Endpoint Not applicable (SDK function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```javascript import Polotno from '@polotno/polotno-node'; const instance = Polotno.createInstance({ // configuration options }); ``` ### Response #### Success Response - **instance** (object) - A Polotno instance object. #### Response Example ```json { "//": "Polotno instance object" } ``` ``` -------------------------------- ### BrowserOptions Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/types.md Configuration for browser instance creation with `createBrowser()`. ```APIDOC ## BrowserOptions Configuration for browser instance creation with `createBrowser()`. ### Properties | Property | Type | Default | Description | |---|---|---|---| | browserArgs | `string[]` | `[]` | Additional Chrome arguments to append to optimized defaults. Examples: `'--disable-dev-shm-usage'`, `'--single-process' | | headless | `'new' | boolean` | `'new'` | Headless mode. Use `'new'` for newer Chrome versions | | protocolTimeout | `number` | `3600000` | Protocol communication timeout (ms). Default 1 hour for large renders | | ignoreHTTPSErrors | `boolean` | `true` | Ignore HTTPS certificate errors | | executablePath | `string` | Auto | Path to Chrome/Chromium executable. Auto-detected on Linux | ### Usage ```javascript const browser = await createBrowser({ browserArgs: ['--disable-dev-shm-usage'], protocolTimeout: 120000, }); ``` ``` -------------------------------- ### Create Polotno Instance with Options Source: https://github.com/polotno-project/polotno-node/blob/master/README.md Configure Polotno Node instance with various options like API key, parallel page rendering, custom client editor URL, browser instance, browser arguments, font caching, and request interception. ```javascript const { createInstance } = require('polotno-node'); const instance = await createInstance({ // this is a demo key just for that project // (!) please don't use it in your projects // to create your own API key please go here: https://polotno.dev/cabinet key: 'nFA5H9elEytDyPyvKL7T', // useParallelPages - use parallel pages to speed up rendering // you can use false only for sequential calls // it may break rendering if you call many parallel requests // default is true useParallelPages: false, // url - url of the Polotno Client Editor // client editor is just simple public html page that have `store` as global variable // by default it will run local build url: 'https://yourappdomain.com/client', // browser - puppeteer browser instance // by default it will use chrome-aws-lambda // useful to set your own rendering props or use browserless browser: browser, // browserArgs - additional browser arguments to append to default args // see "Custom Browser Arguments" section for more details browserArgs: ['--custom-arg'], // useFontCache - cache Google Fonts responses (in memory + on disk in the // OS temp folder, shared across processes) and serve them to every page. // Every page starts with an empty HTTP cache, so without it each render // re-downloads the same fonts and bursts of parallel renders may get // throttled by Google Fonts (fonts time out and text falls back to a // default font). Default is true. useFontCache: true, // requestInterceptor - optional function to intercept and modify network requests // Useful when you need to: // - Modify headers like User-Agent to access protected image resources // - Add authentication tokens or credentials to requests // - Log or monitor network traffic requestInterceptor: (request) => { const targetUrl = request.url(); if (/ .(png|jpe?g)(\?|$)/i.test(targetUrl)) { console.log(`Modifying User-Agent for image request: ${targetUrl}`); request.continue({ headers: { ...request.headers(), 'User-Agent': 'MyCustomApprovedAgent/1.0', }, }); } else { request.continue(); } }, }); ``` -------------------------------- ### Basic Polotno Node Instance Creation Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/createInstance.md Creates a Polotno Node instance with default settings and demonstrates converting a JSON design to a PNG image. ```javascript const { createInstance } = require('polotno-node'); const fs = require('fs'); const instance = await createInstance({ key: 'your-polotno-api-key', }); const json = JSON.parse(fs.readFileSync('design.json')); const imageBase64 = await instance.jsonToImageBase64(json); fs.writeFileSync('output.png', imageBase64, 'base64'); await instance.close(); ``` -------------------------------- ### Sequential Rendering with Await Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/errors.md When `useParallelPages` is false, ensure each render operation is awaited before starting the next to avoid concurrency issues. ```javascript const instance = await createInstance({ key: 'your-key', useParallelPages: false, // Single page mode }); // Wait for each render to complete const img1 = await instance.jsonToImageBase64(json1); const img2 = await instance.jsonToImageBase64(json2); ``` -------------------------------- ### Create Polotno Browser Configuration Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/configuration.md Configure a Polotno browser instance with custom arguments, headless mode, protocol timeouts, HTTPS error handling, and custom executable paths. ```javascript const browser = await createBrowser({ // Custom Arguments browserArgs: ['--disable-dev-shm-usage', '--single-process'], // Browser Behavior headless: 'new', // Headless mode protocolTimeout: 3600000, // 1 hour (default) ignoreHTTPSErrors: true, // Ignore HTTPS errors executablePath: '/path/to/chrome', // Custom Chrome path // ...any puppeteer.launch() options }); ``` -------------------------------- ### Convert Node.js Buffer to Base64 and Hex Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToBlob.md Shows how to convert the Buffer object returned by jsonToBlob into a base64 or hex string, and how to get the buffer's size in bytes. ```javascript const buffer = await instance.jsonToBlob(json); // Convert to base64 const base64 = buffer.toString('base64'); // Convert to hex const hex = buffer.toString('hex'); // Get buffer size console.log(`Image size: ${buffer.length} bytes`); ``` -------------------------------- ### Reuse Browser Across Multiple Instances Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/createBrowser.md Demonstrates how to create a single browser instance and reuse it for multiple Polotno rendering instances. This is efficient for parallel processing of renders. ```javascript const { createBrowser, createInstance } = require('polotno-node'); const browser = await createBrowser(); const instance1 = await createInstance({ key: 'key1', browser, useParallelPages: true, }); const instance2 = await createInstance({ key: 'key2', browser, useParallelPages: true, }); // Parallel renders across both instances await Promise.all([ instance1.jsonToImageBase64(json1), instance2.jsonToImageBase64(json2), ]); await instance1.close(); await instance2.close(); await browser.close(); ``` -------------------------------- ### Periodic Instance Reboot for Long-Running Servers Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/instance-lifecycle.md Implement a reboot mechanism for long-running Polotno instances to prevent memory accumulation. This example restarts the instance after a set number of renders. ```javascript const INSTANCE_REBOOT_INTERVAL = 1000; // Restart every 1000 renders let renderCount = 0; let instance = await createInstance({ key: 'your-key' }); async function render(json) { const result = await instance.jsonToImageBase64(json); renderCount++; if (renderCount >= INSTANCE_REBOOT_INTERVAL) { await instance.close(); instance = await createInstance({ key: 'your-key' }); renderCount = 0; } return result; } ``` -------------------------------- ### Stream Polotno Buffer to HTTP Response with Express Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/jsonToBlob.md This example illustrates streaming the Buffer directly to an HTTP response using Express. It sets the appropriate Content-Type and Content-Length headers. ```javascript const express = require('express'); const { createInstance } = require('polotno-node'); const app = express(); const instance = await createInstance({ key: 'your-key' }); app.post('/api/export-image', async (req, res) => { try { const { json } = req.body; const buffer = await instance.jsonToBlob(json); res.set('Content-Type', 'image/png'); res.set('Content-Length', buffer.length); res.send(buffer); } catch (error) { res.status(400).json({ error: error.message }); } }); ``` -------------------------------- ### PolotnoInstance.run Source: https://github.com/polotno-project/polotno-node/blob/master/_autodocs/api-reference/run.md Executes an asynchronous function within the Polotno page context, providing access to the store and other global browser objects. This is useful for advanced workflows requiring direct manipulation of the Polotno store. ```APIDOC ## PolotnoInstance.run ### Description Executes an asynchronous function within the Polotno page context, providing access to the store and other global browser objects. This is useful for advanced workflows requiring direct manipulation of the Polotno store. ### Signature ```typescript run