Chromiumly

repository·main·Indexed 41 days ago

https://github.com/cherfia/chromiumly

A lightweight TypeScript client for the Gotenberg HTTP API (version 6.0.0) used to convert various document formats to PDF. It supports both self-hosted Gotenberg instances and a managed hosted API, providing tools for PDF generation, manipulation, and conversion via LibreOffice, as well as screenshot capture and PDF/A or PDF/UA transformation.

Tokens
22K
Snippets
74
Records
80
Agent score
50%

What's inside Chromiumly

  1. Configure PDF watermarks and stamps

    main

    You can apply watermarks or stamps to PDFs using the watermark and stamp options. These use the same multipart field names as Gotenberg's PDF-engine. You can provide text, an image, or a PDF as the source. When using an image or PDF, you must provide the file property.

    Supported source values:

    • text: Use the expression property for the text content.
    • image: Use the expression property for the filename of the uploaded asset and provide the file (Buffer or Stream).
    • pdf: Use the expression property for the filename of the uploaded asset and provide the file (Buffer or Stream).

    Common properties:

    • pages: Page ranges (e.g., "1-3"). Omit for all pages.
    • options: Engine-specific JSON configuration (e.g., for pdfcpu).
    type PdfEngineWatermark = {
        source?: 'text' | 'image' | 'pdf';
        expression?: string; // Text, or filename of the uploaded asset when source is image or pdf
        pages?: string; // Page ranges (e.g. "1-3"); omit for all pages
        options?: Record<string, unknown>; // Serialized as JSON (engine-specific)
        file?: PathLikeOrReadStream | Buffer; // Required when source is image or pdf
    };
    
    type PdfEngineStamp = {
        source?: 'text' | 'image' | 'pdf';
        expression?: string;
        pages?: string;
        options?: Record<string, unknown>;
        file?: PathLikeOrReadStream | Buffer;
    };
  2. Configure PDF permissions

    main

    You can restrict PDF capabilities such as printing, copying, or modifying the document by providing a PdfEnginePermissions object.

    Note on Enforcement:

    • QPDF: Honors each permission individually.
    • pdfcpu: Restricts all permissions if any single permission is denied.
    • PDFtk: Does not support owner-only encryption or permission restrictions.
    • Warning: Restrictions are advisory; PDF viewers may honor them, but they are not cryptographically enforced once the document is opened.
    type PdfEnginePermissions = {
        allowPrinting?: boolean; // Allow printing the document
        allowCopying?: boolean; // Allow copying content from the document
        allowModifying?: boolean; // Allow modifying the document
        allowAnnotating?: boolean; // Allow adding or modifying annotations
        allowFillingForms?: boolean; // Allow filling in form fields
        allowAssembling?: boolean; // Allow document assembly, e.g. inserting, deleting, or rotating pages
    };
    
    // Usage example
    const buffer = await UrlConverter.convert({
        url: 'https://www.example.com/',
        ownerPassword: 'my_owner_password',
        allowPrinting: false,
        allowCopying: false
    });
  3. Apply watermarks and stamps to PDFs

    main

    You can apply a watermark (placed behind content) or a stamp (placed on top of content) using the configured PDF engine.

    How to apply them:

    • Converters (UrlConverter, HtmlConverter, etc.): Pass watermark, stamp, or rotate in the options object.
    • LibreOffice: Use native fields (e.g., nativeWatermarkText) or the standard watermark/stamp options.
    • PDFEngines (merge, split): Pass optional watermark, stamp, or rotate.
    • Dedicated Routes: Use PDFEngines.watermark() or PDFEngines.stamp() for direct operations.

    For Image or PDF sources: Set source to 'image' or 'pdf', set expression to the filename of the uploaded asset, and pass the file in the file parameter.

  4. Use Basic Authentication with self-hosted Gotenberg

    main

    If your self-hosted Gotenberg instance (version 8.4.0+) requires basic authentication, provide the username and password in your configuration. This is useful when running Gotenberg with --api-enable-basic-auth enabled.

    # Using dotenv
    GOTENBERG_ENDPOINT=http://localhost:3000
    GOTENBERG_API_BASIC_AUTH_USERNAME=user
    GOTENBERG_API_BASIC_AUTH_PASSWORD=pass
    // Using config library
    {
        "gotenberg": {
            "endpoint": "http://localhost:3000",
            "api": {
                "basicAuth": {
                    "username": "user",
                    "password": "pass"
                }
            }
        }
    }
    import { Chromiumly } from 'chromiumly';
    
    Chromiumly.configure({
        endpoint: 'http://localhost:3000',
        username: 'user',
        password: 'pass'
    });
  5. Install the Chromiumly client

    main

    You can install the chromiumly package using npm or yarn. This client works with both self-hosted Gotenberg instances and the managed Chromiumly hosted API.

    npm install chromiumly
    # or
    yarn add chromiumly
  6. Configure Chromiumly for the hosted API

    main

    To use the managed Chromiumly service at https://api.chromiumly.dev, you do not need to provide a GOTENBERG_ENDPOINT. Instead, provide your API key obtained from https://chromiumly.dev.

    When using the hosted API, you can set the key via an environment variable or programmatically via Chromiumly.configure().

    CHROMIUMLY_API_KEY=your-api-key
    import { Chromiumly } from 'chromiumly';
    
    Chromiumly.configure({
        apiKey: 'your-api-key'
    });
  7. Embed files into generated PDFs

    main

    Chromium and LibreOffice routes allow you to embed files (like XML invoices or images) directly into the generated PDF using the embeds parameter. This is useful for standards like ZUGFeRD / Factur-X.

    Supported file types for embeds:

    • File paths (string)
    • Buffers
    • Read streams

    You can provide per-attachment metadata using embedsMetadata to ensure compliance with PDF/A-3 or Factur-X by specifying the mimeType and the /AFRelationship (e.g., Source, Data, Alternative, Supplement, or Unspecified).

    import { HtmlConverter } from 'chromiumly';
    
    const htmlConverter = new HtmlConverter();
    const buffer = await htmlConverter.convert({
        html: 'path/to/index.html',
        embeds: [
            'path/to/invoice.xml',
            'path/to/logo.png',
            Buffer.from('additional data')
        ],
        embedsMetadata: {
            'invoice.xml': { mimeType: 'text/xml', relationship: 'Data' }
        }
    });
  8. Configure Chromiumly for self-hosted Gotenberg

    main

    If you are running your own Gotenberg instance (e.g., via Docker), you must provide the endpoint URL. You can configure this using environment variables, a configuration file, or directly in your code.

    # Using dotenv
    GOTENBERG_ENDPOINT=http://localhost:3000
    // Using config library
    {
        "gotenberg": {
            "endpoint": "http://localhost:3000"
        }
    }
    import { Chromiumly } from 'chromiumly';
    
    Chromiumly.configure({ endpoint: 'http://localhost:3000' });
  9. Use the Templates class (Hosted API only)

    main

    The Templates class is a premium feature available only on the Chromiumly hosted API (requires CHROMIUMLY_API_KEY). It is not available when pointing to a self-hosted Gotenberg instance via GOTENBERG_ENDPOINT.

    It allows generating structured PDFs (like invoices) from JSON payloads.

    Available Template Types:

    • invoice_saas: SaaS-style invoice.
    • invoice_freelancer: Freelancer invoice.
    • invoice_classic: Classic invoice (requires companyLogo).
    • invoice_minimal: Minimal invoice.
    • invoice_modern: Modern invoice.

    Validation: You can pass { validate: true } as a second argument to generate() to perform runtime validation of your data against the expected schema for the chosen template type.

    import { Templates } from 'chromiumly';
    
    const templates = new Templates();
    const buffer = await templates.generate({
        type: 'invoice_saas',
        data: {
            invoiceNumber: 'INV-319',
            createdDate: '2026-03-19',
            dueDate: '2026-04-02',
            companyLogo: 'https://cdn.acmecloud.com/assets/logo-mark.png',
            sender: {
                name: 'Acme Cloud LLC',
                addressLine1: '450 Madison Ave',
                addressLine2: 'New York, NY 10022'
            },
            receiver: {
                name: 'Northwind Health Inc.',
                addressLine1: '221 Harbor Blvd',
                addressLine2: 'San Diego, CA 92101'
            },
            items: [
                {
                    description: 'Platform Subscription (Annual)',
                    qty: 1,
                    unitPrice: '1500.00',
                    amount: '1500.00'
                }
            ],
            currency: 'USD',
            subTotal: '1800.00',
            taxRate: 8.25,
            taxAmount: '148.50',
            total: '1948.50',
            footerNote: 'Payment due in 14 days.'
        }
    }, { validate: true });
  10. Configure PDF Page Properties

    main

    The convert() method accepts a properties object of type PageProperties to customize the visual layout of the generated PDF.

    Supported Units: Dimensions for size and margins can be provided as numbers (inches) or strings with units (pt, px, in, mm, cm, pc).

    Key Properties:

    • singlePage: If true, prints the entire content on one single page (default false).
    • size: { width, height } defines paper dimensions.
    • margins: { top, bottom, left, right } defines page margins.
    • landscape: Set to true for landscape orientation.
    • scale: Number representing page rendering scale (default 1.0).
    • printBackground: Print background graphics (default false).
    • omitBackground: Enable transparency by hiding the default white background (default false).
    // Using numeric values (inches)
    properties: {
      size: { width: 8.5, height: 11 },
      margins: { top: 0.5, bottom: 0.5, left: 1, right: 1 }
    }
    
    // Using string values with units
    properties: {
      size: { width: "210mm", height: "297mm" }, // A4 size
      margins: { top: "1cm", bottom: "1cm", left: "2cm", right: "2cm" }
    }
    
    // Mixing numeric and string values
    properties: {
      size: { width: 8.5, height: "11in" },
      margins: { top: "10mm", bottom: 0.5, left: "72pt", right: 1 }
    }
  11. Convert URLs to PDF using UrlConverter

    main

    Use the UrlConverter class to transform a web URL into a PDF buffer. The convert method accepts a configuration object that allows you to control page sizing, media emulation (like dark mode), error handling for HTTP status codes or console exceptions, and PDF splitting/unifying logic. Once you have the buffer, you can use PDFEngines.generate to save it to a file.

    import { PDFEngines, UrlConverter } from 'chromiumly';
    
    async function run() {
        const urlConverter = new UrlConverter();
        const buffer = await urlConverter.convert({
            url: 'https://gotenberg.dev/',
            properties: {
                singlePage: true,
                size: {
                    width: 8.5,
                    height: 11
                }
            },
            emulatedMediaType: 'screen',
            emulatedMediaFeatures: [
                { name: 'prefers-color-scheme', value: 'dark' },
                { name: 'prefers-reduced-motion', value: 'reduce' }
            ],
            failOnHttpStatusCodes: [404],
            failOnConsoleExceptions: true,
            skipNetworkIdleEvent: false,
            skipNetworkAlmostIdleEvent: false,
            split: {
                mode: 'pages',
                span: '1-2',
                unify: true
            }
        });
    
        await PDFEngines.generate('gotenberg.pdf', buffer);
    }
    
    run();