### Install Gotenberg PHP Client and Guzzle Adapter
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Install the Gotenberg PHP client library and a compatible HTTP client adapter like Guzzle using Composer.
```bash
composer require gotenberg/gotenberg-php
composer require php-http/guzzle7-adapter
```
--------------------------------
### Install Guzzle7 Adapter
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
If you are unsure which HTTP client adapter to use, the php-http/guzzle7-adapter is recommended. Install it with Composer.
```bash
composer require php-http/guzzle7-adapter
```
--------------------------------
### Initialize Gotenberg Modules
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Instantiate the main Gotenberg client for different modules like Chromium, LibreOffice, or PDF engines. This is the starting point for building any request.
```php
use Gotenberg\Gotenberg;
Gotenberg::chromium($apiUrl);
Gotenberg::libreOffice($apiUrl);
Gotenberg::pdfEngines($apiUrl);
```
--------------------------------
### Install Gotenberg PHP Client
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Install the Gotenberg PHP client using Composer. This package requires PSR-7 and PSR-18 compatible HTTP clients.
```bash
composer require gotenberg/gotenberg-php
```
--------------------------------
### Install Dependencies and Run Linters
Source: https://github.com/gotenberg/gotenberg-php/blob/main/CLAUDE.md
Install project dependencies using Composer and run linting and testing commands. The `lint:fix` command automatically corrects coding standard violations.
```bash
composer install
composer run lint:fix # Auto-fix coding standard violations
composer run lint # phpcs + phpstan at max level (zero errors permitted)
composer run tests # PHPUnit with coverage
composer run all # lint:fix + lint + tests
```
--------------------------------
### Download from URL with Custom Headers for Authentication
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
This example shows how to download a file from a URL while including custom HTTP headers, such as authentication tokens. This is essential for accessing protected resources. The downloaded and processed file is saved to the output directory.
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Download with custom headers (for authentication)
$request = Gotenberg::libreOffice($apiUrl)
->downloadFrom([
new DownloadFrom(
'https://api.example.com/files/document.docx',
['Authorization' => 'Bearer token123', 'X-API-Key' => 'secret']
)
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Send Request and Get PSR-7 Response
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Build a request and send it to the Gotenberg API using a PSR-7 compatible HTTP client. This method returns the API's response object for further handling.
```php
use Gotenberg\Gotenberg;
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://my.url');
$response = $client->sendRequest($request);
```
--------------------------------
### Get Stream Properties with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Retrieve the filename and the underlying PSR-7 stream object from a Gotenberg Stream instance.
```php
use Gotenberg\Stream;
// Get stream properties
$stream = Stream::path('/path/to/document.docx');
$filename = $stream->getFilename(); // Returns: document.docx
$psr7Stream = $stream->getStream(); // Returns: StreamInterface
```
--------------------------------
### LibreOffice Module - Basic Conversion
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Demonstrates how to convert single or multiple Office documents to PDF using the Gotenberg PHP client. Multiple documents are converted into a ZIP archive.
```APIDOC
## POST /convert/office
### Description
Converts Office documents (Word, Excel, PowerPoint, etc.) to PDF. If multiple documents are provided, they are merged into a ZIP archive.
### Method
POST
### Endpoint
/convert/office
### Parameters
#### Query Parameters
- **webhook-url** (string) - Optional - URL to send a notification when the conversion is complete.
- ** விளைவு ** (string) - Optional - The name of the output file.
#### Request Body
- **payload** (multipart/form-data) - Contains the Office documents to convert.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Convert a single document
$request = Gotenberg::libreOffice($apiUrl)
->convert(Stream::path('/path/to/document.docx'));
$filename = Gotenberg::save($request, '/output');
// Convert multiple documents (returns ZIP archive)
$request = Gotenberg::libreOffice($apiUrl)
->convert(
Stream::path('/path/to/report.docx'),
Stream::path('/path/to/spreadsheet.xlsx'),
Stream::path('/path/to/presentation.pptx')
);
$filename = Gotenberg::save($request, '/output');
// Output: archive.zip
```
### Response
#### Success Response (200)
- **file** (binary) - The converted PDF file or a ZIP archive of PDF files.
```
--------------------------------
### Convert Office Document to PDF with LibreOffice
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Use this to convert a single Office document (e.g., DOCX, XLSX, PPTX) to PDF. Ensure the API URL is correctly set and the file path is valid.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Convert a single document
$request = Gotenberg::libreOffice($apiUrl)
->convert(Stream::path('/path/to/document.docx'));
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Convert Document to PDF using LibreOffice with a File Path
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Convert a document from a local file path to PDF using the LibreOffice module. Ensure the `Stream::path()` method is used to correctly reference the file.
```php
use Gotenberg\DownloadFrom;
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
Gotenberg::libreOffice($apiUrl)
->convert(Stream::path($pathToDocument));
```
--------------------------------
### Convert Markdown to PDF with Wrapper Template
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Converts Markdown content to PDF using an HTML wrapper template. The `{{ toHTML "document.md" }}` placeholder in the wrapper injects the rendered Markdown.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$wrapperHtml = <<
{{ toHTML "document.md" }}
HTML;
$markdown = <<pdf()
->assets(Stream::string('style.css', $css))
->markdown(
Stream::string('index.html', $wrapperHtml),
Stream::string('document.md', $markdown)
);
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Download Document for Conversion using LibreOffice
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Instruct Gotenberg to download a document from a specified URL for conversion using the LibreOffice module. Custom headers can be included in the download request.
```php
use Gotenberg\DownloadFrom;
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
Gotenberg::libreOffice($apiUrl)
->downloadFrom([
new DownloadFrom('https://url.to.document.docx', ['MyHeader' => 'MyValue'])
])
->convert();
```
--------------------------------
### Advanced LibreOffice PDF Conversion Options
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Demonstrates advanced LibreOffice conversion settings including password protection, page layout, image compression, watermarks, and PDF viewer preferences.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Advanced LibreOffice conversion with all options
$request = Gotenberg::libreOffice($apiUrl)
->password('document-password') // Password-protected source
->landscape()
->nativePageRanges('1-5')
->exportFormFields(false) // Flatten form fields
->exportBookmarks()
->exportBookmarksToPdfDestination()
->exportNotes()
->skipEmptyPages()
->losslessImageCompression()
->quality(90) // Image quality
->reduceImageResolution()
->maxImageResolution(300) // DPI
->nativeWatermarkText('CONFIDENTIAL')
->nativeWatermarkFontHeight(48)
->nativeWatermarkRotateAngle(45)
->nativeWatermarkColor(0xFF0000) // Red
->initialView('outline') // PDF viewer opens with outline
->magnification('fitPage')
->pageLayout('continuous')
->centerWindow()
->displayPDFDocumentTitle()
->pdfa('PDF/A-2b')
->pdfua()
->flatten()
->encrypt('user-password', 'owner-password')
->convert(Stream::path('/path/to/document.docx'));
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Convert URL to PDF
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Convert a target URL to a PDF file and save it to a specified directory using the Gotenberg PHP client. Ensure the Gotenberg API URL is correctly configured.
```php
use Gotenberg\Gotenberg;
// Converts a target URL to PDF and saves it to a given directory.
$filename = Gotenberg::save(
Gotenberg::chromium($apiUrl)->pdf()->url('https://my.url'),
$pathToSavingDirectory
);
```
--------------------------------
### Convert URL to PDF using Chromium
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Build a request to convert a given URL into a PDF document using the Chromium module. The `singlePage()` method is optional and can be used to ensure the output is a single page.
```php
use Gotenberg\Gotenberg;
Gotenberg::chromium($apiUrl)
->pdf()
->singlePage()
->url('https://my.url'));
```
--------------------------------
### Convert Document to PDF using LibreOffice with a Stream
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Convert a document to PDF using the LibreOffice module by providing the document content directly as a stream. This is useful when the document content is already in memory.
```php
use Gotenberg\DownloadFrom;
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
Gotenberg::libreOffice($apiUrl)
->convert(new Stream('document.docx', $stream));
```
--------------------------------
### Convert URL to PDF with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Use the Gotenberg::chromium() factory to create a request for converting a URL to PDF. Ensure the Gotenberg API is accessible at the specified URL.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\Exceptions\GotenbergApiErrored;
$apiUrl = 'http://localhost:3000';
// Convert a URL to PDF
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://example.com');
// Convert HTML to PDF with custom settings
$request = Gotenberg::chromium($apiUrl)
->pdf()
->paperSize('8.27in', '11.7in') // A4 size
->margins('1in', '1in', '0.5in', '0.5in')
->printBackground()
->landscape()
->html(Stream::string('index.html', '
Hello World
'));
// Save the PDF to a directory
try {
$filename = Gotenberg::save($request, '/path/to/output');
echo "Saved: $filename"; // Output: Saved: 95cd9945-484f-4f89-8bdb-23dbdd0bdea9.pdf
} catch (GotenbergApiErrored $e) {
echo "Error: " . $e->getMessage();
}
```
--------------------------------
### Send Request with Explicit HTTP Client
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Send a request using the `Gotenberg::send` helper while explicitly providing the HTTP client instance. This allows for custom client configurations.
```php
use Gotenberg\Gotenberg;
$response = Gotenberg::send($request, $client);
```
--------------------------------
### Split PDF by Intervals with PdfEngines
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Splits a PDF document into multiple smaller PDFs based on a specified interval (e.g., every 5 pages). The output is a ZIP archive containing the split PDFs.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\SplitMode;
$apiUrl = 'http://localhost:3000';
// Split PDF by intervals (every N pages)
$request = Gotenberg::pdfEngines($apiUrl)
->split(
SplitMode::intervals(5), // Split every 5 pages
Stream::path('/path/to/document.pdf')
);
$filename = Gotenberg::save($request, '/output');
// Output: archive.zip containing multiple PDFs
```
--------------------------------
### Create Stream from String Content with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Creates a file stream from a string, useful for generating files like HTML or CSS on the fly. Requires a filename and the string content.
```php
use Gotenberg\Stream;
// From string content
$htmlStream = Stream::string('index.html', 'Hello');
$cssStream = Stream::string('styles.css', 'body { font-family: Arial; }');
```
--------------------------------
### LibreOffice Module - Merging and Advanced Options
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Shows how to merge multiple Office documents into a single PDF with advanced customization options like page ranges, PDF/A compliance, metadata, and viewer settings.
```APIDOC
## POST /convert/office
### Description
Merges multiple Office documents into a single PDF with advanced customization options. Supports PDF/A compliance, metadata, watermarks, and viewer settings.
### Method
POST
### Endpoint
/convert/office
### Parameters
#### Query Parameters
- **webhook-url** (string) - Optional - URL to send a notification when the conversion is complete.
- ** விளைவு ** (string) - Optional - The name of the output file.
#### Request Body
- **payload** (multipart/form-data) - Contains the Office documents to convert.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Merge multiple documents into single PDF
$request = Gotenberg::libreOffice($apiUrl)
->merge()
->landscape()
->nativePageRanges('1-10')
->pdfa('PDF/A-1a')
->metadata([
'Author' => 'John Doe',
'Title' => 'Merged Document',
'Subject' => 'Annual Report 2024'
])
->convert(
Stream::path('/path/to/cover.docx'),
Stream::path('/path/to/content.docx'),
Stream::path('/path/to/appendix.xlsx')
);
$filename = Gotenberg::save($request, '/output');
// Advanced LibreOffice conversion with all options
$request = Gotenberg::libreOffice($apiUrl)
->password('document-password') // Password-protected source
->landscape()
->nativePageRanges('1-5')
->exportFormFields(false) // Flatten form fields
->exportBookmarks()
->exportBookmarksToPdfDestination()
->exportNotes()
->skipEmptyPages()
->losslessImageCompression()
->quality(90) // Image quality
->reduceImageResolution()
->maxImageResolution(300) // DPI
->nativeWatermarkText('CONFIDENTIAL')
->nativeWatermarkFontHeight(48)
->nativeWatermarkRotateAngle(45)
->nativeWatermarkColor(0xFF0000) // Red
->initialView('outline') // PDF viewer opens with outline
->magnification('fitPage')
->pageLayout('continuous')
->centerWindow()
->displayPDFDocumentTitle()
->pdfa('PDF/A-2b')
->pdfua()
->flatten()
->encrypt('user-password', 'owner-password')
->convert(Stream::path('/path/to/document.docx'));
$filename = Gotenberg::save($request, '/output');
```
### Response
#### Success Response (200)
- **file** (binary) - The converted and customized PDF file.
```
--------------------------------
### Capture Screenshot with Clipping and JPEG Compression
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Captures a screenshot from a URL, applying clipping to viewport dimensions and saving as a JPEG with specified quality. `optimizeForSpeed()` can be used for faster processing.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Screenshot with clipping and JPEG compression
$request = Gotenberg::chromium($apiUrl)
->screenshot()
->width(1280)
->height(720)
->clip() // Clip to viewport dimensions
->jpeg()
->quality(85) // JPEG quality (0-100)
->optimizeForSpeed()
->url('https://example.com');
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Merge Multiple Files from URLs with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
This snippet demonstrates merging multiple documents fetched from different URLs. Each URL is specified using the DownloadFrom class. The merged document is then converted and saved to the output directory.
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Multiple files from URLs
$request = Gotenberg::libreOffice($apiUrl)
->merge()
->downloadFrom([
new DownloadFrom('https://example.com/cover.docx'),
new DownloadFrom('https://example.com/content.docx'),
new DownloadFrom('https://example.com/appendix.xlsx')
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### DownloadFrom - Remote File Downloads
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Instructs Gotenberg to download files from URLs instead of uploading them directly, useful for large files or when files are already hosted remotely.
```APIDOC
## DownloadFrom - Remote File Downloads
### Description
Instructs Gotenberg to download files from URLs instead of uploading them directly. Useful for large files or when files are already hosted remotely.
### Download and Convert from URL
#### Method
POST
#### Endpoint
(Specific endpoint depends on the conversion type, e.g., /convert or /libreoffice)
#### Parameters
##### Request Body
- **downloadFrom** (array) - Required - An array of DownloadFrom objects specifying the URLs to download files from.
- **convert** (boolean) - Optional - If true, performs a conversion after downloading.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Convert document from URL
$request = Gotenberg::libreOffice($apiUrl)
->downloadFrom([
new DownloadFrom('https://example.com/document.docx')
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
### Download with Custom Headers
#### Method
POST
#### Endpoint
(Specific endpoint depends on the conversion type)
#### Parameters
##### Request Body
- **downloadFrom** (array) - Required - An array of DownloadFrom objects, each potentially including custom headers.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Download with custom headers (for authentication)
$request = Gotenberg::libreOffice($apiUrl)
->downloadFrom([
new DownloadFrom(
'https://api.example.com/files/document.docx',
['Authorization' => 'Bearer token123', 'X-API-Key' => 'secret']
)
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
### Download Multiple Files from URLs
#### Method
POST
#### Endpoint
(Specific endpoint depends on the operation, e.g., /merge or /convert)
#### Parameters
##### Request Body
- **downloadFrom** (array) - Required - An array of DownloadFrom objects for multiple files.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Multiple files from URLs
$request = Gotenberg::libreOffice($apiUrl)
->merge()
->downloadFrom([
new DownloadFrom('https://example.com/cover.docx'),
new DownloadFrom('https://example.com/content.docx'),
new DownloadFrom('https://example.com/appendix.xlsx')
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
### DownloadFrom Class
#### Description
Represents a remote file to be downloaded by Gotenberg.
#### Constructor
`__construct(string $url, ?array $headers = null)`
#### Parameters
- **url** (string) - Required - The URL of the file to download.
- **headers** (array, optional) - An associative array of HTTP headers to include in the download request.
```
--------------------------------
### Write PDF Metadata with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
This snippet demonstrates how to write metadata to a PDF document. Provide a key-value array of metadata and the path to the PDF file. The result is saved to the specified output directory.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Write PDF metadata
$request = Gotenberg::pdfEngines($apiUrl)
->writeMetadata(
[
'Author' => 'John Doe',
'Title' => 'Annual Report',
'Subject' => 'Financial Summary',
'Keywords' => ['finance', 'annual', 'report'],
'Creator' => 'My Application'
],
Stream::path('/path/to/document.pdf')
);
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Advanced URL to PDF Conversion with Chromium Module
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Perform advanced URL to PDF conversions using the Chromium module, configuring options like paper size, margins, headers, footers, and PDF/A compliance. Ensure the API URL is correctly set.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\Modules\ChromiumCookie;
$apiUrl = 'http://localhost:3000';
// Basic URL to PDF conversion
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://example.com');
$response = Gotenberg::send($request);
// Advanced URL conversion with all options
$request = Gotenberg::chromium($apiUrl)
->pdf()
->singlePage() // Print all content on one page
->paperSize('8.5in', '11in') // Letter size
->margins('0.5in', '0.5in', '0.5in', '0.5in')
->printBackground() // Include background graphics
->landscape() // Landscape orientation
->scale(0.9) // 90% scale
->nativePageRanges('1-5, 8') // Specific pages
->waitDelay('2s') // Wait 2 seconds before conversion
->waitForExpression("window.loaded === true")
->emulateScreenMediaType() // Use screen CSS media type
->userAgent('CustomUserAgent/1.0')
->extraHttpHeaders(['Authorization' => 'Bearer token123'])
->cookies([
new ChromiumCookie('session', 'abc123', 'example.com', '/')
])
->failOnHttpStatusCodes([400, 401, 403, 404, 500])
->failOnConsoleExceptions()
->pdfa('PDF/A-2b') // PDF/A compliance
->pdfua() // PDF/UA accessibility
->outputFilename('my-document')
->url('https://example.com');
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Convert HTML to PDF with Assets
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Converts an HTML string to PDF, supporting external assets like CSS and images referenced within the HTML. Ensure assets are provided via `Stream::string` or `Stream::path`.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Simple HTML to PDF
$html = <<
Invoice #12345
Item
Price
Product A
$100.00
HTML;
$css = 'body { font-family: Arial, sans-serif; } h1 { color: #333; }';
$request = Gotenberg::chromium($apiUrl)
->pdf()
->assets(
Stream::string('style.css', $css),
Stream::path('/path/to/logo.png')
)
->html(Stream::string('index.html', $html));
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Capture Screenshot from HTML with Transparent Background
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Takes a screenshot of provided HTML content, saving it as a WebP image with a transparent background. The `omitBackground()` option is used for transparency.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Screenshot from HTML
$request = Gotenberg::chromium($apiUrl)
->screenshot()
->width(800)
->height(600)
->webp()
->omitBackground() // Transparent background
->html(Stream::string('index.html', '
Hello
'));
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Capture Screenshot from URL
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Takes a screenshot of a given URL. Specify dimensions, image format (PNG, JPEG, WebP), and quality settings as needed.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Screenshot from URL
$request = Gotenberg::chromium($apiUrl)
->screenshot()
->width(1920)
->height(1080)
->png()
->url('https://example.com');
$filename = Gotenberg::save($request, '/output');
// Output: screenshot.png
```
--------------------------------
### Send Request using Gotenberg::send Helper
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Utilize the `Gotenberg::send` helper function for PSR-18 compatible clients to send a request and receive a response. This helper automatically throws an exception for non-2xx responses.
```php
use Gotenberg\Gotenberg;
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://my.url');
try {
$response = Gotenberg::send($request);
return $response;
} catch (GotenbergApiErrored $e) {
// $e->getResponse();
}
```
--------------------------------
### Create Stream from Custom PSR-7 Stream with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Allows creating a file stream using an existing PSR-7 stream object. This provides flexibility when working with other libraries that produce PSR-7 streams.
```php
use Gotenberg\Stream;
use GuzzleHttp\Psr7\Utils;
// From custom PSR-7 stream
$customStream = new Stream('filename.txt', Utils::streamFor('content'));
```
--------------------------------
### Convert Document from URL with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Instructs Gotenberg to download a document from a URL and then convert it. This is useful for processing documents hosted remotely. The converted file is saved to the output directory.
```php
use Gotenberg\Gotenberg;
use Gotenberg\DownloadFrom;
$apiUrl = 'http://localhost:3000';
// Convert document from URL
$request = Gotenberg::libreOffice($apiUrl)
->downloadFrom([
new DownloadFrom('https://example.com/document.docx')
])
->convert();
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Create PDF from HTML with CSS Asset using Chromium
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Generate a PDF from HTML content, including external CSS assets, using the Chromium module. The `Stream::string()` method is used to embed the CSS and HTML content directly.
```php
use Gotenberg\DownloadFrom;
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
Gotenberg::chromium($apiUrl)
->pdf()
->assets(Stream::string('style.css', 'body{font-family: Arial, Helvetica, sans-serif;}'))
->html(Stream::string('index.html', '
Hello, world!
'));
```
--------------------------------
### Convert HTML to PDF with Header and Footer
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Generates a PDF from HTML content, including custom headers and footers. Margins can be specified to control spacing around the content.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// HTML with header and footer
$header = '
'));
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Run Composer Commands in Docker
Source: https://github.com/gotenberg/gotenberg-php/blob/main/CLAUDE.md
Execute all Composer commands within a Docker container to ensure a consistent development environment. This command mounts the current directory and runs all defined Composer scripts.
```bash
docker run --rm -it \
-e PHP_EXTENSION_XDEBUG=1 \
-v $(PWD):/usr/src/app/ \
thecodingmachine/php:8.1-v4-cli \
bash -c "composer run all"
```
--------------------------------
### Read PDF Metadata with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Use this to retrieve metadata from one or more PDF files. Ensure the API URL is correctly set and the PDF files exist at the specified paths.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Read PDF metadata
$request = Gotenberg::pdfEngines($apiUrl)
->readMetadata(
Stream::path('/path/to/document1.pdf'),
Stream::path('/path/to/document2.pdf')
);
$response = Gotenberg::send($request);
$metadata = json_decode($response->getBody()->getContents(), true);
// Output: {"document1.pdf": {"Author": "...", "Title": "..."}, "document2.pdf": {...}}
```
--------------------------------
### Convert Office Documents to PDF
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Convert Office documents (e.g., DOCX, XLSX) to PDF using the Gotenberg PHP client's LibreOffice module. This method sends the documents to the Gotenberg API.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
// Converts Office documents to PDF.
$response = Gotenberg::send(
Gotenberg::libreOffice($apiUrl)
->convert(
Stream::path($pathToDocx),
Stream::path($pathToXlsx)
)
);
```
--------------------------------
### Save Resulting File using Gotenberg::save Helper
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Use the `Gotenberg::save` helper function with a PSR-18 compatible client to send a request and save the resulting file to a specified directory. The function returns the filename of the saved file.
```php
use Gotenberg\Gotenberg;
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://my.url');
$filename = Gotenberg::save($request, '/path/to/saving/directory');
```
--------------------------------
### Save Resulting File with Explicit HTTP Client
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Save the resulting file from a Gotenberg request by explicitly providing the HTTP client to the `Gotenberg::save` function. This offers flexibility in client management.
```php
use Gotenberg\Gotenberg;
$response = Gotenberg::save($request, $pathToSavingDirectory, $client);
```
--------------------------------
### Create Stream from File Path with Gotenberg PHP
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Generates a file stream for Gotenberg requests using a local file path. You can optionally provide a custom filename for the stream.
```php
use Gotenberg\Stream;
// From file path (lazy-loaded)
$stream = Stream::path('/path/to/document.docx');
$stream = Stream::path('/path/to/document.docx', 'custom-name.docx');
```
--------------------------------
### Split PDF by Specific Pages with PdfEngines
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Splits a PDF document based on a list of specific page ranges or individual pages. The 'unify' option can merge the selected pages into a single output PDF.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\SplitMode;
$apiUrl = 'http://localhost:3000';
// Split PDF by specific pages
$request = Gotenberg::pdfEngines($apiUrl)
->split(
SplitMode::pages('1-3, 5, 7-10', unify: true), // Unify into single PDF
Stream::path('/path/to/document.pdf')
);
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Gotenberg::chromium() - Chromium Module Factory
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Factory method to create a Chromium module instance for PDF conversions and screenshots. It allows chaining various options for customization.
```APIDOC
## Gotenberg::chromium() - Chromium Module Factory
### Description
Creates a Chromium module instance for HTML, URL, and Markdown to PDF conversions or screenshots. The Chromium module uses headless Chrome/Chromium for rendering.
### Method
Factory method
### Endpoint
N/A (Client-side library)
### Parameters
None directly on the factory method, but subsequent chained methods accept parameters.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\Exceptions\GotenbergApiErrored;
$apiUrl = 'http://localhost:3000';
// Convert a URL to PDF
$request = Gotenberg::chromium($apiUrl)
->pdf()
->url('https://example.com');
// Convert HTML to PDF with custom settings
$request = Gotenberg::chromium($apiUrl)
->pdf()
->paperSize('8.27in', '11.7in') // A4 size
->margins('1in', '1in', '0.5in', '0.5in')
->printBackground()
->landscape()
->html(Stream::string('index.html', '
Hello World
'));
// Save the PDF to a directory
try {
$filename = Gotenberg::save($request, '/path/to/output');
echo "Saved: $filename"; // Output: Saved: 95cd9945-484f-4f89-8bdb-23dbdd0bdea9.pdf
} catch (GotenbergApiErrored $e) {
echo "Error: " . $e->getMessage();
}
```
### Response
N/A (This is a factory method for building requests)
```
--------------------------------
### Embed Files and Metadata in PDFs
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Embed additional files like XML invoices into PDFs during creation or into existing PDFs. Use Stream::path for file paths and EmbedMetadata for file details.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
use Gotenberg\EmbedMetadata;
$apiUrl = 'http://localhost:3000';
// Embed files during PDF creation
$request = Gotenberg::chromium($apiUrl)
->pdf()
->embeds(
Stream::path('/path/to/factur-x.xml'),
Stream::path('/path/to/additional-data.json')
)
->embedsMetadata(
new EmbedMetadata(
'factur-x.xml',
'application/xml',
EmbedMetadata::RELATIONSHIP_DATA
),
new EmbedMetadata(
'additional-data.json',
'application/json',
EmbedMetadata::RELATIONSHIP_SUPPLEMENT
)
)
->html(Stream::string('index.html', 'Invoice'));
$filename = Gotenberg::save($request, '/output');
// Embed files into existing PDFs
$request = Gotenberg::pdfEngines($apiUrl)
->embed(
[Stream::path('/path/to/factur-x.xml')],
Stream::path('/path/to/invoice.pdf')
);
$filename = Gotenberg::save($request, '/output');
```
--------------------------------
### Override Output Filename
Source: https://github.com/gotenberg/gotenberg-php/blob/main/README.md
Specify a custom output filename for the resulting file using the `outputFilename()` method. Gotenberg will automatically append the correct file extension.
```php
use Gotenberg\Gotenberg;
$request = Gotenberg::chromium($apiUrl)
->pdf()
->outputFilename('my_file')
->url('https://my.url');
```
--------------------------------
### Convert Multiple Office Documents to ZIP Archive
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
This snippet converts multiple Office documents into a single ZIP archive, where each document is converted to PDF. Useful for batch processing.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
// Convert multiple documents (returns ZIP archive)
$request = Gotenberg::libreOffice($apiUrl)
->convert(
Stream::path('/path/to/report.docx'),
Stream::path('/path/to/spreadsheet.xlsx'),
Stream::path('/path/to/presentation.pptx')
);
$filename = Gotenberg::save($request, '/output');
// Output: archive.zip
```
--------------------------------
### PDF Engines Operations
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Perform various operations on PDF documents using the PdfEngines API, such as reading metadata, writing metadata, converting to PDF/A, flattening forms, and encrypting documents.
```APIDOC
## PDF Engines Operations
### Description
Perform various operations on PDF documents using the PdfEngines API, such as reading metadata, writing metadata, converting to PDF/A, flattening forms, and encrypting documents.
### Read PDF Metadata
#### Method
POST
#### Endpoint
/pdfengines
#### Parameters
##### Request Body
- **files** (array) - Required - One or more PDF files to read metadata from.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$request = Gotenberg::pdfEngines($apiUrl)
->readMetadata(
Stream::path('/path/to/document1.pdf'),
Stream::path('/path/to/document2.pdf')
);
$response = Gotenberg::send($request);
$metadata = json_decode($response->getBody()->getContents(), true);
```
### Response
#### Success Response (200)
- **metadata** (object) - An object where keys are filenames and values are objects containing the PDF metadata.
#### Response Example
```json
{
"document1.pdf": {"Author": "...", "Title": "..."},
"document2.pdf": {...}
}
```
### Write PDF Metadata
#### Method
POST
#### Endpoint
/pdfengines
#### Parameters
##### Request Body
- **metadata** (object) - Required - An object containing the metadata to write to the PDF.
- **file** (StreamInterface) - Required - The PDF file to write metadata to.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$request = Gotenberg::pdfEngines($apiUrl)
->writeMetadata(
[
'Author' => 'John Doe',
'Title' => 'Annual Report',
'Subject' => 'Financial Summary',
'Keywords' => ['finance', 'annual', 'report'],
'Creator' => 'My Application'
],
Stream::path('/path/to/document.pdf')
);
$filename = Gotenberg::save($request, '/output');
```
### Convert to PDF/A
#### Method
POST
#### Endpoint
/pdfengines
#### Parameters
##### Request Body
- **pdfa_version** (string) - Required - The PDF/A version to convert to (e.g., 'PDF/A-2b').
- **file** (StreamInterface) - Required - The PDF file to convert.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$request = Gotenberg::pdfEngines($apiUrl)
->convert('PDF/A-2b', Stream::path('/path/to/document.pdf'));
$filename = Gotenberg::save($request, '/output');
```
### Flatten PDF (Remove Form Fields)
#### Method
POST
#### Endpoint
/pdfengines
#### Parameters
##### Request Body
- **file** (StreamInterface) - Required - The PDF file with form fields to flatten.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$request = Gotenberg::pdfEngines($apiUrl)
->flatten(Stream::path('/path/to/form.pdf'));
$filename = Gotenberg::save($request, '/output');
```
### Encrypt PDF
#### Method
POST
#### Endpoint
/pdfengines
#### Parameters
##### Request Body
- **userPassword** (string) - Required - The password for general users.
- **ownerPassword** (string) - Required - The password for administrative users.
- **file** (StreamInterface) - Required - The PDF file to encrypt.
### Request Example
```php
use Gotenberg\Gotenberg;
use Gotenberg\Stream;
$apiUrl = 'http://localhost:3000';
$request = Gotenberg::pdfEngines($apiUrl)
->encrypt('user-password', 'owner-password', Stream::path('/path/to/document.pdf'));
$filename = Gotenberg::save($request, '/output');
```
```
--------------------------------
### Handle API Errors with Try-Catch Blocks
Source: https://context7.com/gotenberg/gotenberg-php/llms.txt
Use try-catch blocks to handle specific Gotenberg API exceptions. Retrieve correlation IDs from exceptions for debugging API errors.
```php
use Gotenberg\Gotenberg;
use Gotenberg\Exceptions\GotenbergApiErrored;
use Gotenberg\Exceptions\NoOutputFileInResponse;
use Gotenberg\Exceptions\NativeFunctionErrored;
$apiUrl = 'http://localhost:3000';
try {
$request = Gotenberg::chromium($apiUrl)
->pdf()
->correlationId('request-12345') // Custom correlation ID for logs
->failOnHttpStatusCodes([404, 500])
->failOnConsoleExceptions()
->url('https://example.com/page');
$filename = Gotenberg::save($request, '/output');
echo "Success: $filename";
} catch (GotenbergApiErrored $e) {
// API returned an error (4xx or 5xx)
$statusCode = $e->getResponse()->getStatusCode();
$correlationId = $e->getCorrelationId();
$body = $e->getResponse()->getBody()->getContents();
echo "API Error ($statusCode): $body";
echo "Correlation ID: $correlationId"; // Use this to find logs in Gotenberg
} catch (NoOutputFileInResponse $e) {
// Response didn't contain expected file
echo "No output file in response";
} catch (NativeFunctionErrored $e) {
// PHP native function failed (file operations, JSON encoding, etc.)
echo "Native function error: " . $e->getMessage();
}
```