### Install Project Dependencies
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Fetch project dependencies using Mix.
```elixir
mix deps.get
```
--------------------------------
### Full ChromicPDF Configuration Example
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Configure ChromicPDF with session pool settings, security options, Chrome arguments, and error handling. This example shows a comprehensive set of options.
```elixir
# Full configuration example
{ChromicPDF, [
# Session pool configuration
session_pool: [
size: 5, # Number of concurrent Chrome sessions
timeout: 15_000, # Operation timeout in milliseconds
checkout_timeout: 5_000, # Queue wait timeout
max_uses: 1000, # Restart sessions after N operations
init_timeout: 10_000 # Session initialization timeout
],
# Ghostscript pool for PDF/A conversion
ghostscript_pool: [size: 3],
# Security options
offline: true, # Prevent external URL access
disable_scripts: true, # Disable JavaScript in templates
ignore_certificate_errors: false, # SSL verification (dev only!)
# Chrome options (local instances only)
no_sandbox: false, # Required in some Docker setups
chrome_executable: "/usr/bin/chromium",
chrome_args: "--font-render-hinting=none",
discard_stderr: true,
# Error handling
unhandled_runtime_exceptions: :log, # :ignore | :log | :raise
console_api_calls: :ignore, # :ignore | :log | :raise
# On-demand mode (dev/test)
on_demand: false
]}
```
--------------------------------
### Generate PDF with Callback for Output
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use a callback function with `print_to_pdf/2` to process the generated PDF file, for example, to copy it to a permanent location.
```elixir
# Use callback function with temporary file
{:ok, :uploaded} = ChromicPDF.print_to_pdf(
{:html, "
Report
"},
output: fn path ->
File.cp!(path, "/permanent/location/report.pdf")
:uploaded
end
)
```
--------------------------------
### Start ChromicPDF in Application Supervision Tree
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
ChromicPDF must be started as part of your application's supervision tree. It can be started with default options or with custom configuration.
```elixir
defmodule MyApp.Application do
use Application
def start(_type, _args) do
children = [
# Basic start
ChromicPDF,
# Or with configuration options
{ChromicPDF, chromic_pdf_opts()}
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
defp chromic_pdf_opts do
[
session_pool: [size: 5, timeout: 10_000],
offline: false,
disable_scripts: false,
no_sandbox: false # Set to true in Docker containers
]
end
end
```
--------------------------------
### Start ChromicPDF in Application Supervision Tree
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Inject ChromicPDF into your application's supervision tree in `lib/my_app/application.ex`.
```elixir
def MyApp.Application do
def start(_type, _args) do
children = [
# other apps...
ChromicPDF
]
Supervisor.start_link(children, strategy: :one_for_one, name: MyApp.Supervisor)
end
end
```
--------------------------------
### Attaching Telemetry Handler
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Attach a telemetry handler to monitor the :stop event for the :print_to_pdf function. This example logs the duration and metadata.
```elixir
# Available telemetry events:
# [:chromic_pdf, :print_to_pdf, :start | :stop | :exception]
# [:chromic_pdf, :capture_screenshot, :start | :stop | :exception]
# [:chromic_pdf, :convert_to_pdfa, :start | :stop | :exception]
# [:chromic_pdf, :join_pdfs, :start | :stop | :exception]
# Attach telemetry handler
:telemetry.attach(
"chromic-pdf-handler",
[:chromic_pdf, :print_to_pdf, :stop],
fn _event, measurements, metadata, _config ->
IO.puts("PDF generated in #{measurements.duration / 1_000_000}ms")
IO.inspect(metadata, label: "Metadata")
end,
nil
)
```
--------------------------------
### Warm Up ChromicPDF
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Initialize Chrome caches by running a one-off Chrome process. This is particularly useful in CI environments to mitigate slow Chrome startup times.
```elixir
# In test_helper.exs
{:ok, _} = ChromicPDF.warm_up()
ExUnit.start()
# Or with options
{:ok, stderr} = ChromicPDF.warm_up(discard_stderr: false)
IO.puts("Chrome stderr: #{stderr}")
# Alternative: use mix task in CI
# $ mix chromic_pdf.warm_up
# $ mix test
```
--------------------------------
### Run Project Tests
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Execute the project's test suite using Mix.
```elixir
mix test
```
--------------------------------
### Generate PDF from Local File
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generate a PDF from a local HTML file using `print_to_pdf/2` with the `{:url, "file://..."}` input.
```elixir
# Print from local file
{:ok, blob} = ChromicPDF.print_to_pdf({:url, "file:///path/to/document.html"})
```
--------------------------------
### Print Local HTML to PDF/A with Callback
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Convert a local HTML file to PDF/A and process the generated PDF using a callback function.
```elixir
ChromicPDF.print_to_pdfa({:url, "file:///example.html"}, output: fn pdf ->
# Send pdf via mail, upload to S3, ...
end)
```
--------------------------------
### Generate PDF/A with Callback for Post-processing
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use a callback function with `print_to_pdfa/2` to handle the generated PDF/A file, such as uploading it to cloud storage.
```elixir
# With callback for post-processing
{:ok, :archived} = ChromicPDF.print_to_pdfa(
{:url, "file:///reports/quarterly.html"},
output: fn path ->
# Upload to S3 or other storage
MyApp.S3.upload(path, "archives/quarterly-2024.pdf")
:archived
end
)
```
--------------------------------
### Generate PDF/A from URL
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use `print_to_pdfa/2` to generate a PDF/A document from a URL. The default version is PDF/A-3b. The output can be a Base64 blob or saved to a file.
```elixir
# Generate PDF/A-3b (default) and return Base64
{:ok, blob} = ChromicPDF.print_to_pdfa({:url, "https://example.net"})
```
--------------------------------
### Generating PDFs from Controller/Context
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generate a PDF invoice by defining a view module and calling ChromicPDF.print_to_pdf with a Plug.Conn forward.
```elixir
def generate_invoice_pdf(invoice) do
ChromicPDF.print_to_pdf(
{:plug,
url: "http://localhost:4000/makepdf",
forward: {MyAppWeb.PDFView, :render_invoice, [invoice]}
},
output: "/invoices/#{invoice.id}.pdf"
)
end
```
--------------------------------
### Generate PDF from In-Memory HTML
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generate a PDF directly from an HTML string using `print_to_pdf/2` with the `{:html, ...}` input.
```elixir
# Print from in-memory HTML content
{:ok, blob} = ChromicPDF.print_to_pdf({:html, "Hello World!
Generated PDF
"})
```
--------------------------------
### Print External URL to Local PDF
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Generate a PDF from an external URL and save it to the local filesystem.
```elixir
# Prints a local HTML file to PDF.
ChromicPDF.print_to_pdf({:url, "https://example.net"}, output: "example.pdf")
```
--------------------------------
### Generate PDF from HTML String with Template Options
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Use the Template API to specify content and page size (e.g., A4) for PDF generation.
```elixir
[content: "Hello Template
", size: :a4]
|> ChromicPDF.Template.source_and_options()
|> ChromicPDF.print_to_pdf()
```
--------------------------------
### Generate PDF/A from HTML with Specific Version
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generate a PDF/A document from in-memory HTML content, specifying the PDF/A version (e.g., '2' for PDF/A-2b) using the `pdfa_version` option.
```elixir
# Generate PDF/A-2b version
{:ok, blob} = ChromicPDF.print_to_pdfa(
{:html, "Archived Document
"},
pdfa_version: "2"
)
```
--------------------------------
### Generate PDF with Custom Print Options
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Customize PDF generation using the `print_to_pdf` option, including margins, header, and footer HTML templates.
```elixir
# With custom printToPDF options (margins, headers, footers)
ChromicPDF.print_to_pdf(
{:url, "https://example.net"},
print_to_pdf: %{
marginTop: 1.0,
marginBottom: 1.0,
marginLeft: 0.5,
marginRight: 0.5,
displayHeaderFooter: true,
headerTemplate: """
Company Report
""",
footerTemplate: """
Page of
"""
},
output: "report.pdf"
)
```
--------------------------------
### Generate PDF from URL
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use `print_to_pdf/2` to generate a PDF from a URL. The output can be a Base64-encoded blob or saved directly to a file.
```elixir
# Print from URL and return Base64-encoded PDF
{:ok, base64_blob} = ChromicPDF.print_to_pdf({:url, "https://example.net"})
```
```elixir
# Save directly to file
:ok = ChromicPDF.print_to_pdf({:url, "https://example.net"}, output: "/tmp/output.pdf")
```
--------------------------------
### Generate PDF/A with Metadata and Save to File
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Save a PDF/A document to a file with custom metadata like title, author, and dates. The `pdfa_version` can be set to '3' for PDF/A-3b.
```elixir
# Save PDF/A directly to file with metadata
:ok = ChromicPDF.print_to_pdfa(
{:html, "Legal Document
Important content here.
"},
output: "/archive/document.pdf",
pdfa_version: "3",
info: %{
title: "Legal Agreement",
author: "John Doe",
subject: "Contract",
keywords: "legal, contract, agreement",
creator: "MyApp PDF Generator",
creation_date: DateTime.utc_now(),
mod_date: DateTime.utc_now()
}
)
```
--------------------------------
### convert_to_pdfa/2 - Convert Existing PDF to PDF/A
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Converts an existing PDF file to PDF/A format. Supports specifying the PDF/A version, output file, custom metadata, and custom PostScript.
```APIDOC
## POST /convert_to_pdfa
### Description
Converts an existing PDF file to PDF/A format. Useful when you already have a PDF that needs archival conversion.
### Method
POST
### Endpoint
/convert_to_pdfa
### Parameters
#### Query Parameters
- **input_path** (string) - Required - The path to the existing PDF file.
- **output_path** (string) - Optional - The path to save the converted PDF/A file. If not provided, the result is returned as a blob.
- **pdfa_version** (string) - Optional - Specifies the PDF/A version (e.g., "2", "3"). Defaults to "3".
- **pdfa_level** (string) - Optional - Specifies the PDF/A level (e.g., "b", "u", "a"). Defaults to "b".
- **info** (map) - Optional - A map containing metadata for the PDF/A file (e.g., title, author, creation_date).
- **pdfa_def_ext** (string) - Optional - Custom PostScript to add to the conversion.
### Request Example
```json
{
"input_path": "/path/to/existing.pdf",
"output_path": "/path/to/archive.pdf",
"pdfa_version": "3",
"pdfa_level": "b",
"info": {
"title": "Archived Document",
"author": "System",
"creation_date": "2023-10-27T10:00:00Z"
},
"pdfa_def_ext": "[/Title (Custom Title) /DOCINFO pdfmark"
}
```
### Response
#### Success Response (200)
- **blob** (binary) - The converted PDF/A file as a binary blob if output_path is not specified.
- **message** (string) - A success message if output_path is specified.
```
--------------------------------
### Custom ChromicPDF Supervisor Module
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Create a custom module that uses ChromicPDF.Supervisor for better encapsulation or to manage multiple instances with different configurations.
```elixir
defmodule MyApp.PDFGenerator do
use ChromicPDF.Supervisor
end
# In application.ex
children = [
{MyApp.PDFGenerator, session_pool: [size: 3]}
]
# Usage
MyApp.PDFGenerator.print_to_pdf({:html, "Hello
"})
MyApp.PDFGenerator.print_to_pdfa({:url, "https://example.net"})
MyApp.PDFGenerator.capture_screenshot({:html, "Screenshot
"})
```
--------------------------------
### Named Session Pools Configuration
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Configure named session pools for different sets of options, allowing you to switch between configurations like 'secure' or 'default'.
```elixir
# Named session pools for different configurations
{ChromicPDF, [
session_pool: %{
secure: [disable_scripts: true, offline: true],
default: [disable_scripts: false]
}
]}
```
--------------------------------
### PDF View Module
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Define a view module to render HTML content for PDF generation. You can return HTML directly or use conn to send a response.
```elixir
defmodule MyAppWeb.PDFView do
def render_invoice(conn, invoice) do
# Return HTML content directly
"""
Invoice ##{invoice.number}
Amount: $#{invoice.amount}
"""
# Or use conn to send response with Plug.Conn.send_resp/3
end
end
```
--------------------------------
### ChromicPDF.print_to_pdf/2
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generates a PDF document from a URL, local file, or raw HTML content.
```APIDOC
## ChromicPDF.print_to_pdf/2
### Description
Converts HTML content, a URL, or a local file into a PDF document. Supports custom print options, cookie injection, and JavaScript evaluation.
### Parameters
- **input** (tuple) - Required - The source of the content: {:url, String} or {:html, String}.
- **options** (keyword list) - Optional - Configuration for output, print settings, cookies, and evaluation.
### Request Example
ChromicPDF.print_to_pdf({:html, "Hello
"}, output: "report.pdf")
### Response
#### Success Response (200)
- **result** (binary/atom) - Returns {:ok, blob} if no output path is provided, or :ok if saved to a file.
```
--------------------------------
### Convert PDF to PDF/A
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Converts an existing PDF file to PDF/A format. Supports specifying the PDF/A version, custom metadata, and PostScript definitions.
```elixir
# Convert existing PDF to PDF/A-3b and return Base64
{:ok, blob} = ChromicPDF.convert_to_pdfa("/path/to/existing.pdf")
```
```elixir
# Convert and save to new file
:ok = ChromicPDF.convert_to_pdfa(
"/path/to/source.pdf",
output: "/path/to/archive.pdf"
)
```
```elixir
# Convert with PDF/A-2b and custom metadata
:ok = ChromicPDF.convert_to_pdfa(
"/uploads/document.pdf",
pdfa_version: "2",
output: "/archive/document-a2b.pdf",
info: %{
title: "Converted Document",
author: "System",
creation_date: DateTime.utc_now()
}
)
```
```elixir
# Add custom PostScript to conversion
ChromicPDF.convert_to_pdfa(
"input.pdf",
pdfa_def_ext: "[/Title (Custom Title) /DOCINFO pdfmark",
output: "output.pdf"
)
```
--------------------------------
### capture_screenshot/2 - Take Screenshots
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Captures screenshots of web pages as PNG or JPEG images. Supports various input sources and customization options.
```APIDOC
## POST /capture_screenshot
### Description
Captures screenshots of web pages as PNG or JPEG images. Supports the same input sources as PDF generation.
### Method
POST
### Endpoint
/capture_screenshot
### Parameters
#### Query Parameters
- **input_source** (object) - Required - The source to capture. Can be `{:url, "url_string"}`, `{:html, "html_string"}`, or `{:file, "path_to_file"}`.
- **output_path** (string) - Optional - The path to save the screenshot file. If not provided, the result is returned as a Base64-encoded string.
- **format** (string) - Optional - The image format ('png' or 'jpeg'). Defaults to 'png'.
- **quality** (integer) - Optional - The quality of the JPEG image (0-100). Only applicable for JPEG format.
- **full_page** (boolean) - Optional - Captures the entire scrollable page. Requires Chrome 91+.
- **evaluate** (map) - Optional - A map containing JavaScript to execute before capturing the screenshot. Example: `%{expression: "document.body.style.backgroundColor = 'lightblue';"}`.
### Request Example
```json
{
"input_source": {"url": "https://example.net"},
"output_path": "/screenshots/page.png",
"format": "png",
"full_page": true,
"evaluate": {"expression": "document.querySelector('h1').style.color = 'red';"}
}
```
### Response
#### Success Response (200)
- **blob** (binary) - The screenshot image as a binary blob if output_path is not specified.
- **message** (string) - A success message if output_path is specified.
```
--------------------------------
### Load dynamic content for PDF generation
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/test/integration/fixtures/test_dynamic.html
Use this function to populate dynamic elements and trigger the ready-to-print attribute for ChromicPDF.
```javascript
function loadDynamicContent() { // Call any JS libraries/frameworks to set the dynamic content. const dynamic_element = document.getElementById('dynamic'); dynamic_element.innerText = "Dynamic content from Javascript"; // When ready, set the attribute: const element = document.getElementById('print-ready'); element.setAttribute('ready-to-print', ''); } setTimeout(() => loadDynamicContent(), 500);
```
--------------------------------
### ChromicPDF.print_to_pdfa/2
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Generates a PDF/A compliant document for long-term archival using Ghostscript.
```APIDOC
## ChromicPDF.print_to_pdfa/2
### Description
Converts HTML content to a PDF/A-2b or PDF/A-3b compliant document. Allows for metadata injection and post-processing callbacks.
### Parameters
- **input** (tuple) - Required - The source of the content: {:url, String} or {:html, String}.
- **options** (keyword list) - Optional - Configuration for output, PDF/A version, and document metadata.
### Request Example
ChromicPDF.print_to_pdfa({:html, "Archive
"}, pdfa_version: "3", output: "archive.pdf")
### Response
#### Success Response (200)
- **result** (binary/atom) - Returns {:ok, blob} if no output path is provided, or :ok if saved to a file.
```
--------------------------------
### Phoenix Router Integration
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Integrate ChromicPDF into your Phoenix application by forwarding requests to the ChromicPDF.Plug.
```elixir
defmodule MyAppWeb.Router do
use MyAppWeb, :router
forward "/makepdf", ChromicPDF.Plug
end
```
--------------------------------
### Generate PDF Waiting for Dynamic Content
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use the `wait_for` option to pause PDF generation until specific content or attributes are present on the page, useful for Single Page Applications (SPAs).
```elixir
# Wait for dynamic content to load
ChromicPDF.print_to_pdf(
{:url, "https://spa-app.example.net"},
wait_for: %{selector: "#content", attribute: "data-loaded"},
output: "spa-content.pdf"
)
```
--------------------------------
### Remote Chrome Connection Configuration
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Configure ChromicPDF to connect to a remote Chrome instance via WebSocket. Ensure the `websockex` dependency is included.
```elixir
# Remote Chrome connection (requires websockex dependency)
{ChromicPDF, [
chrome_address: {"chrome-host.example.net", 9222}
]}
```
--------------------------------
### Concatenate Multiple HTML Sources into One PDF
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Combine multiple HTML sources into a single PDF document using Ghostscript.
```elixir
ChromicPDF.print_to_pdf([{:html, "page 1"}, {:html, "page 2"}], output: "joined.pdf")
```
--------------------------------
### Using a Specific Session Pool
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Specify which session pool to use for a particular operation by passing the `session_pool` option to the function call.
```elixir
ChromicPDF.print_to_pdf({:html, content}, session_pool: :secure)
```
--------------------------------
### Generate PDF with Cookies
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Include cookies when generating a PDF from a URL to access authenticated pages. The `set_cookie` option accepts a map of cookie attributes.
```elixir
# With cookies for authenticated pages
ChromicPDF.print_to_pdf(
{:url, "http://localhost:4000/dashboard"},
set_cookie: %{name: "session", value: "abc123", domain: "localhost"},
output: "dashboard.pdf"
)
```
--------------------------------
### Capture Web Page Screenshot
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Captures screenshots of web pages or HTML content as PNG or JPEG. Supports custom options like format, quality, full page capture, and JavaScript execution.
```elixir
# Capture screenshot and return Base64-encoded PNG
{:ok, base64_png} = ChromicPDF.capture_screenshot({:url, "https://example.net"})
```
```elixir
# Capture from HTML content
{:ok, blob} = ChromicPDF.capture_screenshot({:html, "Hello!
"})
```
```elixir
# Save screenshot to file
:ok = ChromicPDF.capture_screenshot(
{:url, "https://example.net"},
output: "/screenshots/page.png"
)
```
```elixir
# Capture as JPEG with custom options
{:ok, blob} = ChromicPDF.capture_screenshot(
{:url, "https://example.net"},
capture_screenshot: %{format: "jpeg", quality: 80}
)
```
```elixir
# Full page screenshot (Chrome 91+)
{:ok, blob} = ChromicPDF.capture_screenshot(
{:url, "https://long-page.example.net"},
full_page: true,
output: "full-page.png"
)
```
```elixir
# Screenshot with JavaScript execution
{:ok, blob} = ChromicPDF.capture_screenshot(
{:url, "https://app.example.net"},
evaluate: %{expression: "document.body.style.backgroundColor = 'lightblue';"},
output: "styled-screenshot.png"
)
```
--------------------------------
### Configure Chrome Version
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/CHANGELOG.md
Sets the specific Chrome version in the application configuration, required for remote Chrome users to ensure compatibility with recent browser updates.
```elixir
config :chromic_pdf, chrome_version: "Google Chrome 120.0.6099.71"
```
--------------------------------
### ChromicPDF.Plug - Request Forwarding for Phoenix
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Enables request forwarding from an internal endpoint to the print_to_pdf caller, useful for Phoenix applications.
```APIDOC
## POST /chromic_pdf/print (Phoenix Plug)
### Description
This endpoint acts as a Plug for Phoenix applications, forwarding requests to the `ChromicPDF.print_to_pdf` function.
### Method
POST
### Endpoint
/chromic_pdf/print
### Parameters
#### Request Body
- **source** (object or array) - Required - The PDF source(s). Can be a single source (`{:url, "url_string"}`, `{:html, "html_string"}`, `{:file, "path_to_file"}`) or an array of sources.
- **options** (map) - Optional - Additional options for `print_to_pdf`, such as `output`, `pdfa_version`, etc.
### Request Example
```json
{
"source": {"url": "https://example.net"},
"options": {"output": "phoenix_generated.pdf"}
}
```
### Response
#### Success Response (200)
- **message** (string) - A success message indicating the PDF was generated and saved.
```
--------------------------------
### Generate PDF after JavaScript Execution
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Execute JavaScript code before printing using the `evaluate` option to modify the DOM or prepare content dynamically.
```elixir
# Execute JavaScript before printing
ChromicPDF.print_to_pdf(
{:url, "https://example.net"},
evaluate: %{expression: "document.querySelector('h1').innerHTML = 'Modified Title';"},
output: "modified.pdf"
)
```
--------------------------------
### Dynamic Process Names Configuration
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Configure ChromicPDF to use a dynamic process name, allowing for better management and potential multiple instances. You can then use `put_dynamic_name` to set the name for subsequent calls.
```elixir
# Dynamic process names
{ChromicPDF, name: MyApp.PDFGenerator}
# Then use:
ChromicPDF.put_dynamic_name(MyApp.PDFGenerator)
ChromicPDF.print_to_pdf({:html, "Hello
"})
```
--------------------------------
### Generating PDFs with Anonymous Function
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Use an anonymous function within the {:plug, forward: ...} option to dynamically generate HTML content based on the request.
```elixir
ChromicPDF.print_to_pdf(
{:plug,
url: "http://localhost:4000/makepdf",
forward: fn conn ->
"Dynamic content based on request
"
end
}
)
```
--------------------------------
### ChromicPDF.Template - Page Layout Helpers
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Provides helper functions for controlling page dimensions, headers, footers, and styling in generated PDFs. Supports predefined paper sizes and custom dimensions.
```elixir
# Basic template usage - generates source and options for print_to_pdf
[
content: "Document Title
Document content goes here.
",
size: :a4,
header: "Company Name
",
footer: "Page
",
header_height: "20mm",
footer_height: "15mm"
]
|> ChromicPDF.Template.source_and_options()
|> ChromicPDF.print_to_pdf(output: "document.pdf")
```
```elixir
# Landscape orientation
[
content: "Landscape Report
",
size: :a4,
landscape: true
]
|> ChromicPDF.Template.source_and_options()
|> ChromicPDF.print_to_pdf()
```
```elixir
# Custom paper size (width x height in inches)
[
content: "Custom Size
",
size: {6.0, 9.0}
]
|> ChromicPDF.Template.source_and_options()
|> ChromicPDF.print_to_pdf()
```
```elixir
# Use options/1 separately when you have your own content source
opts = ChromicPDF.Template.options(
header: "Header Text
",
footer: "Footer Text
",
header_height: "25mm",
footer_height: "20mm",
header_font_size: "12pt",
footer_font_size: "10pt"
)
ChromicPDF.print_to_pdf({:url, "https://example.net"}, opts ++ [output: "styled.pdf"])
```
```elixir
# Get page styles for custom templates
styles = ChromicPDF.Template.page_styles(
size: :a4,
header_height: "20mm",
footer_height: "15mm"
)
html = ChromicPDF.Template.html_concat(styles, "My Content
")
ChromicPDF.print_to_pdf({:html, html})
```
--------------------------------
### Passing Custom Telemetry Metadata
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Pass custom metadata to telemetry events by using the `telemetry_metadata` option. This is useful for tracking specific job details.
```elixir
ChromicPDF.print_to_pdf(
{:html, "Invoice
"},
telemetry_metadata: %{template: "invoice", customer_id: 123},
output: "invoice.pdf"
)
```
--------------------------------
### Concatenate Multiple PDF Sources
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Combines multiple PDF sources into a single document. Sources can be HTML or use different template configurations.
```elixir
# Join multiple HTML sources into one PDF
ChromicPDF.print_to_pdf(
[
{:html, "Cover Page
"},
{:html, "Chapter 1
Content...
"},
{:html, "Chapter 2
More content...
"}
],
output: "book.pdf"
)
```
```elixir
# Mix different template configurations
ChromicPDF.print_to_pdf(
[
ChromicPDF.Template.source_and_options(
content: "Title Page
",
size: :a4
),
ChromicPDF.Template.source_and_options(
content: "Main content with header
",
size: :a4,
header: "Document Header
",
header_height: "20mm"
),
{:html, "Appendix
No header section
"}
],
output: "mixed-document.pdf"
)
```
```elixir
# Create PDF/A from multiple sources
ChromicPDF.print_to_pdfa(
[{:html, "Page 1"}, {:html, "Page 2"}],
pdfa_version: "3",
output: "archive.pdf"
)
```
--------------------------------
### Add ChromicPDF to Elixir Dependencies
Source: https://github.com/bitcrowd/chromic_pdf/blob/main/README.md
Add ChromicPDF to your project's runtime dependencies in `mix.exs`.
```elixir
def deps do
[
{:chromic_pdf, "~> 1.17"}
]
end
```
--------------------------------
### ChromicPDF.Template - Page Layout Helpers
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Provides helper functions for controlling page dimensions, headers, footers, and styling in generated PDFs.
```APIDOC
## POST /print_to_pdf (with template options)
### Description
Generates a PDF using template helpers for page layout, including headers, footers, and custom paper sizes.
### Method
POST
### Endpoint
/print_to_pdf
### Parameters
#### Request Body
- **content** (string) - Required - The HTML content for the PDF body.
- **size** (string or tuple) - Optional - The paper size. Can be a predefined size (e.g., ':a4', ':us_letter') or a custom size tuple `{width_inches, height_inches}`.
- **landscape** (boolean) - Optional - Set to true for landscape orientation.
- **header** (string) - Optional - HTML content for the header.
- **footer** (string) - Optional - HTML content for the footer.
- **header_height** (string) - Optional - Height of the header (e.g., "20mm").
- **footer_height** (string) - Optional - Height of the footer (e.g., "15mm").
- **header_font_size** (string) - Optional - Font size for the header.
- **footer_font_size** (string) - Optional - Font size for the footer.
- **output_path** (string) - Optional - The path to save the generated PDF. If not provided, the result is returned as a blob.
### Request Example
```json
{
"content": "Document Title
Document content goes here.
",
"size": ":a4",
"header": "Company Name
",
"footer": "Page
",
"header_height": "20mm",
"footer_height": "15mm",
"output_path": "document.pdf"
}
```
### Response
#### Success Response (200)
- **blob** (binary) - The generated PDF file as a binary blob if output_path is not specified.
- **message** (string) - A success message if output_path is specified.
```
--------------------------------
### Concatenating Multiple Sources
Source: https://context7.com/bitcrowd/chromic_pdf/llms.txt
Combines multiple PDF sources (HTML, existing PDFs) into a single document.
```APIDOC
## POST /print_to_pdf (multiple sources)
### Description
Combines multiple PDF sources into a single document. Each source can have different layouts and configurations.
### Method
POST
### Endpoint
/print_to_pdf
### Parameters
#### Request Body
- **sources** (array) - Required - An array of sources to combine. Each element can be:
- `{:html, "html_string"}`
- `{:url, "url_string"}`
- `{:file, "path_to_file"}`
- A map representing template options (see ChromicPDF.Template documentation).
- **output_path** (string) - Optional - The path to save the combined PDF. If not provided, the result is returned as a blob.
### Request Example
```json
{
"sources": [
{"html": "Cover Page
"},
{
"content": "Chapter 1
Content...
",
"size": ":a4",
"header": "Document Header
",
"header_height": "20mm"
},
{"url": "https://example.com/appendix"}
],
"output_path": "book.pdf"
}
```
### Response
#### Success Response (200)
- **blob** (binary) - The combined PDF file as a binary blob if output_path is not specified.
- **message** (string) - A success message if output_path is specified.
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.