### Rust Doc Example
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Example of a Rust function with documentation comments and a runnable example.
```rust
/// Converts HTML to PDF.
///
/// # Arguments
///
/// * `html` - The HTML content to convert
///
/// # Examples
///
/// ```rust,no_run
/// # use carbonpdf::PdfBuilder;
/// # #[tokio::main]
/// # async fn main() -> carbonpdf::Result<()> {
/// let pdf = PdfBuilder::new()
/// .html("
Test
")
/// .build()
/// .await?;
/// # Ok(())
/// # }
/// ```
pub fn html>(self, content: S) -> Self {
// ...
}
```
--------------------------------
### Install CarbonPDF CLI
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Installs the CarbonPDF CLI tool with the 'cli' feature enabled. Ensure you have Rust and Cargo installed.
```bash
cargo install carbonpdf --features cli
```
--------------------------------
### Handlebars Template Example with Custom Helpers
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Demonstrates using built-in Handlebars helpers like `format_currency` and `format_date` within a template.
```handlebars
Total: {{format_currency 1234.56 "$"}}
```
--------------------------------
### Install Chromium on Arch Linux
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Installs the chromium package on Arch Linux systems using pacman.
```bash
sudo pacman -S chromium
```
--------------------------------
### Install Chromium on Ubuntu/Debian
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Installs the chromium-browser package on Ubuntu or Debian systems.
```bash
sudo apt-get install chromium-browser
```
--------------------------------
### Install Google Chrome on macOS
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Installs Google Chrome on macOS using the Homebrew package manager.
```bash
brew install --cask google-chrome
```
--------------------------------
### Playwright Renderer Structure
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Example structure for implementing a new PDF rendering backend using the PlaywrightRenderer.
```rust
// src/renderer/playwright.rs
pub struct PlaywrightRenderer {
// ...
}
#[async_trait]
impl PdfRenderer for PlaywrightRenderer {
async fn render(&self, input: InputSource, config: PdfConfig) -> Result> {
// Implementation
}
fn name(&self) -> &str {
"PlaywrightRenderer"
}
}
```
--------------------------------
### Dockerfile for CarbonPDF Application
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
A Dockerfile setup for building a Rust application that uses CarbonPDF, including installing Chromium and copying the release binary.
```dockerfile
# Dockerfile
FROM rust:1.70 as builder
WORKDIR /app
COPY . .
RUN cargo build --release
FROM debian:bullseye-slim
RUN apt-get update && apt-get install -y \
chromium \
&& rm -rf /var/lib/apt/lists/*
COPY --from=builder /app/target/release/myapp /usr/local/bin/
CMD ["myapp"]
```
--------------------------------
### Configure PDF Builder for Docker Environment
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Example of configuring the `PdfBuilder` in Rust code, specifically highlighting the `no_sandbox()` and `chrome_args()` methods, which are often necessary when running in a Docker container.
```rust
// In your code
let pdf = PdfBuilder::new()
.html(content)
.no_sandbox() // Required in Docker
.chrome_args(["--disable-dev-shm-usage"])
.build()
.await?;
```
--------------------------------
### Generate and Open Documentation
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Generate Rust documentation and open it in a browser.
```bash
cargo doc --open
```
--------------------------------
### Convert HTML to PDF with Options using CLI
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Demonstrates advanced CLI options for PDF generation, including page size, orientation, margins, and scaling.
```bash
# With options
carbonpdf input.html -o output.pdf \
--page-size A4 \
--landscape \
--margin 1.0 \
--scale 0.9
```
--------------------------------
### Build Project
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Build the CarbonPDF project using Cargo.
```bash
cargo build
```
--------------------------------
### Clone Repository
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Clone your forked repository and navigate into the project directory.
```bash
git clone https://github.com/rockycRockyCottott/carbonpdf.git
cd carbonpdf
```
--------------------------------
### Run Tests
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Execute all tests for the project.
```bash
cargo test
```
--------------------------------
### Run Tests with Logging
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Execute tests and enable debug logging.
```bash
RUST_LOG=debug cargo test
```
--------------------------------
### Run Benchmarks
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Execute performance benchmarks using Criterion.
```bash
cargo bench
```
--------------------------------
### Basic HTML to PDF Conversion
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Converts an HTML string to a PDF document with specified page size and margins. Requires the tokio runtime.
```rust
use carbonpdf::{PdfBuilder, PageSize, Result};
#[tokio::main]
async fn main() -> Result<()> {
// Convert HTML string to PDF
let pdf = PdfBuilder::new()
.html("Hello, CarbonPDF!
Easy PDF generation.
")
.page_size(PageSize::A4)
.margin_all(1.0)
.build()
.await?;
std::fs::write("output.pdf", pdf)?;
Ok(())
}
```
--------------------------------
### Advanced PDF Configuration with Page Size, Orientation, and Margins
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Configure PDF generation with specific page sizes (A4), orientation (Landscape), margins, scaling, background printing, headers, footers, and timeouts.
```rust
use carbonpdf::{PdfBuilder, PageSize, Orientation};
let pdf = PdfBuilder::new()
.html(html_content)
.page_size(PageSize::A4)
.orientation(Orientation::Landscape)
.margins(0.5, 0.75, 0.5, 0.75) // top, right, bottom, left (inches)
.scale(0.9)
.print_background(true)
.header("Page
")
.footer("© 2024 Your Company
")
.timeout(60) // seconds
.build()
.await?;
```
--------------------------------
### Convert URL to PDF using CLI
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Converts a web page from a given URL to a PDF document using the CarbonPDF CLI.
```bash
# Convert from URL
carbonpdf https://example.com -o example.pdf
```
--------------------------------
### URL to PDF Conversion
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Converts a web page from a given URL to a PDF document. Requires the tokio runtime.
```rust
let pdf = PdfBuilder::new()
.url("https://example.com")
.build()
.await?;
```
--------------------------------
### File to PDF Conversion
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Converts an HTML file to a PDF document with a specified page size. Requires the tokio runtime.
```rust
let pdf = PdfBuilder::new()
.file("invoice.html")
.page_size(PageSize::Letter)
.build()
.await?;
```
--------------------------------
### Run Specific Test
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Execute a single, named test case.
```bash
cargo test test_html_string_to_pdf
```
--------------------------------
### Convert HTML to PDF using CLI
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Basic usage of the CarbonPDF CLI to convert an HTML file to a PDF document.
```bash
# Convert HTML file
carbonpdf input.html -o output.pdf
```
--------------------------------
### Create Feature Branch
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Create a new branch for your feature development.
```bash
git checkout -b feature/my-feature
```
--------------------------------
### Configure PDF Generation for Docker/CI Environments
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Use `no_sandbox()` and provide custom Chrome arguments like `--disable-dev-shm-usage` for running CarbonPDF in Docker or CI environments.
```rust
let pdf = PdfBuilder::new()
.html(content)
.no_sandbox() // Required in Docker
.chrome_args(["--disable-dev-shm-usage"])
.build()
.await?;
```
--------------------------------
### Run Integration Tests
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Execute only the integration tests.
```bash
cargo test --test integration_test
```
--------------------------------
### Check Code Quality
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Ensure code passes tests, clippy, and fmt checks.
```bash
cargo test
cargo clippy
cargo fmt -- --check
```
--------------------------------
### Reuse Renderer Instance in Backend Services
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Illustrates a best practice for backend services: reusing a `ChromeRenderer` instance across multiple requests to improve performance. Requires the `lazy_static` crate.
```rust
// Reuse renderer instance across requests
lazy_static! {
static ref RENDERER: ChromeRenderer = {
ChromeRenderer::new(ChromeConfig::default())
.await
.expect("Failed to initialize Chrome")
};
}
async fn generate_invoice(html: String) -> Result> {
RENDERER.render(
InputSource::html(html),
PdfConfig::default()
)
.await
}
```
--------------------------------
### Add CarbonPDF and Tokio to Cargo.toml
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Specifies the CarbonPDF and Tokio dependencies for a Rust project in Cargo.toml.
```toml
[dependencies]
carbonpdf = "0.1"
tokio = { version = "1", features = ["full"] }
```
--------------------------------
### Enable Templates Feature in Cargo.toml
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Add the 'templates' feature to your project's Cargo.toml file to enable Handlebars templating support.
```toml
[dependencies]
carbonpdf = { version = "0.2", features = ["templates"] }
```
--------------------------------
### Generate PDF from Handlebars Template and Data
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Use a Handlebars template string and JSON data to dynamically generate a PDF. Ensure the 'templates' feature is enabled.
```rust
use carbonpdf::{PdfBuilder, Result};
use serde_json::json;
#[tokio::main]
async fn main() -> Result<()> {
let template = r#"{{title}}
Hello {{name}}, your order #{{order_id}} is confirmed!
{{#each items}}
- {{this}}
{{/each}}
"#;
let data = json!({
"title": "Order Confirmation",
"name": "Sevani",
"order_id": "12345",
"items": ["Product A", "Product B", "Product C"]
});
let pdf = PdfBuilder::new()
.template(template, data)?
.build()
.await?;
std::fs::write("output.pdf", pdf)?;
Ok(())
}
```
--------------------------------
### Commit Changes
Source: https://github.com/rockycott/carbonpdf/blob/master/CONTRIBUTING.md
Commit your changes with a message following the Conventional Commits format.
```bash
git commit -m "feat: add custom font support"
```
--------------------------------
### Set Custom Page Size for PDF Generation
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Define a custom page size for the generated PDF by specifying width and height in inches.
```rust
let pdf = PdfBuilder::new()
.html(content)
.custom_page_size(8.5, 14.0) // width, height in inches
.build()
.await?;
```
--------------------------------
### Handle CarbonPDF Errors in Rust
Source: https://github.com/rockycott/carbonpdf/blob/master/README.md
Shows how to match and handle different error types returned by CarbonPDF operations in a Rust application.
```rust
use carbonpdf::Error;
match pdf_result {
Ok(pdf) => println!("Success!"),
Err(Error::ChromeProcess(msg)) => eprintln!("Chrome error: {}", msg),
Err(Error::Timeout(secs)) => eprintln!("Timed out after {}s", secs),
Err(Error::InvalidConfig(msg)) => eprintln!("Config error: {}", msg),
Err(e) => eprintln!("Error: {}", e),
}
```
--------------------------------
### Thread-Safe ChromeRenderer Usage
Source: https://github.com/rockycott/carbonpdf/blob/master/ARCHITECTURE.md
Demonstrates a safe pattern for using a lazily initialized ChromeRenderer across multiple threads or asynchronous tasks. Ensure the renderer is initialized once and then shared using thread-safe mechanisms like `lazy_static!`. This pattern is suitable for concurrent PDF generation requests.
```rust
lazy_static! {
static ref RENDERER: ChromeRenderer = /* ... */;
}
// Safe to call from multiple threads/tasks
tokio::spawn(async {
RENDERER.render(/* ... */).await
});
```
--------------------------------
### PdfRenderer Trait Definition
Source: https://github.com/rockycott/carbonpdf/blob/master/ARCHITECTURE.md
Defines the contract for PDF rendering implementations, allowing for different backend technologies. It includes an asynchronous render method and a name identifier.
```rust
pub trait PdfRenderer: Send + Sync {
async fn render(&self, input: InputSource, config: PdfConfig) -> Result>;
fn name(&self) -> &str;
}
```
--------------------------------
### CarbonPDF Error Enum
Source: https://github.com/rockycott/carbonpdf/blob/master/ARCHITECTURE.md
Defines the custom error types used within CarbonPDF, providing context for different failure scenarios like Chrome process issues, protocol errors, or configuration problems.
```rust
pub enum Error {
ChromeProcess(String), // Launch/crash
Protocol(String), // CDP communication
InvalidConfig(String), // User configuration
InputSource(String), // File/URL issues
Network(reqwest::Error), // HTTP errors
Timeout(u64), // Timeout exceeded
// ...
}
```
=== COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.