Module prelude

Module prelude 

Source
Expand description

Convenient imports for common usage patterns.

This module re-exports the most commonly used types from html2pdf-api, allowing you to quickly get started with a single import.

§Quick Start

use html2pdf_api::prelude::*;

This single line gives you access to all the core types needed to create and use a browser pool for PDF generation.

§What’s Included

§Core Types (Always Available)

TypeDescription
BrowserPoolMain pool for managing browser instances
BrowserPoolBuilderBuilder for creating configured pools
BrowserPoolConfigConfiguration settings for the pool
BrowserPoolConfigBuilderBuilder for creating configurations
BrowserPoolErrorError type for pool operations
ResultType alias for Result<T, BrowserPoolError>
BrowserHandleRAII handle for checked-out browsers
PoolStatsReal-time pool statistics
BrowserFactoryTrait for browser creation strategies
ChromeBrowserFactoryDefault Chrome/Chromium factory
HealthcheckTrait for browser health checking
SharedBrowserPoolType alias for Arc<Mutex<BrowserPool>>

§Standard Library Re-exports

For convenience, commonly needed types are re-exported:

TypeDescription
ArcThread-safe reference counting
MutexMutual exclusion lock

§Feature-Gated Exports

Additional exports are available with feature flags:

§env-config Feature

ExportDescription
init_browser_poolInitialize pool from environment variables
from_envLoad configuration from environment
chrome_path_from_envGet Chrome path from CHROME_PATH env var

§actix-integration Feature

ExportDescription
actix moduleActix-web handlers and helpers

§rocket-integration Feature

ExportDescription
rocket moduleRocket handlers and helpers

§axum-integration Feature

ExportDescription
axum moduleAxum handlers and router

§Any Integration Feature

When any integration feature is enabled, service types are also available:

TypeDescription
PdfFromUrlRequestRequest parameters for URL-to-PDF
PdfFromHtmlRequestRequest parameters for HTML-to-PDF
PdfResponseSuccessful PDF generation result
PdfServiceErrorService-level errors
ErrorResponseJSON error response format
PoolStatsResponsePool statistics response
HealthResponseHealth check response

§Usage Examples

§Basic Usage

Create a pool with manual configuration:

use html2pdf_api::prelude::*;
use std::time::Duration;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Build configuration
    let config = BrowserPoolConfigBuilder::new()
        .max_pool_size(5)
        .warmup_count(3)
        .browser_ttl(Duration::from_secs(3600))
        .build()?;

    // Create pool
    let pool = BrowserPool::builder()
        .config(config)
        .factory(Box::new(ChromeBrowserFactory::with_defaults()))
        .build()?;

    // Warmup for production readiness
    pool.warmup().await?;

    // Use a browser (automatically returned to pool when dropped)
    {
        let browser = pool.get()?;
        let tab = browser.new_tab()?;
        tab.navigate_to("https://example.com")?;
        tab.wait_until_navigated()?;
        let pdf = tab.print_to_pdf(None)?;
        std::fs::write("output.pdf", pdf)?;
    }

    // Graceful shutdown
    pool.shutdown();

    Ok(())
}

§Using Environment Configuration

With the env-config feature, initialization is simpler:

use html2pdf_api::prelude::*;

#[tokio::main]
async fn main() -> Result<(), Box<dyn std::error::Error>> {
    // Reads BROWSER_POOL_SIZE, BROWSER_TTL_SECONDS, etc.
    let pool = init_browser_pool().await?;

    // Pool is Arc<Mutex<BrowserPool>>, ready for sharing
    let guard = pool.lock().unwrap();
    let browser = guard.get()?;
    // ...

    Ok(())
}

§With Actix-web (Pre-built Routes)

The fastest way to set up a PDF API:

use actix_web::{App, HttpServer, web};
use html2pdf_api::prelude::*;
use html2pdf_api::integrations::actix::configure_routes;

#[actix_web::main]
async fn main() -> std::io::Result<()> {
    let pool = init_browser_pool().await
        .expect("Failed to initialize pool");

    HttpServer::new(move || {
        App::new()
            .app_data(web::Data::new(pool.clone()))
            .configure(configure_routes) // Adds /pdf, /pdf/html, /health, etc.
    })
    .bind("127.0.0.1:8080")?
    .run()
    .await
}

§With Actix-web (Custom Handler)

For more control, use service functions directly:

use actix_web::{web, HttpResponse, Responder};
use html2pdf_api::prelude::*;
use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};

async fn my_pdf_handler(
    pool: web::Data<SharedBrowserPool>,
    query: web::Query<PdfFromUrlRequest>,
) -> impl Responder {
    let pool = pool.into_inner();
    let request = query.into_inner();

    let result = web::block(move || {
        generate_pdf_from_url(&pool, &request)
    }).await;

    match result {
        Ok(Ok(pdf)) => HttpResponse::Ok()
            .content_type("application/pdf")
            .body(pdf.data),
        Ok(Err(e)) => HttpResponse::BadRequest().body(e.to_string()),
        Err(e) => HttpResponse::InternalServerError().body(e.to_string()),
    }
}

§Checking Pool Statistics

Monitor pool health in your application:

use html2pdf_api::prelude::*;

fn log_pool_status(pool: &SharedBrowserPool) {
    if let Ok(guard) = pool.lock() {
        let stats = guard.stats();
        println!("Pool Status:");
        println!("  Available: {}", stats.available);
        println!("  Active: {}", stats.active);
        println!("  Total: {}", stats.total);
         
        // Check capacity
        if stats.available == 0 {
            println!("  ⚠️ Warning: No idle browsers available");
        }
    }
}

§Error Handling

Handle pool errors appropriately:

use html2pdf_api::prelude::*;

fn generate_pdf(pool: &SharedBrowserPool, url: &str) -> Result<Vec<u8>> {
    let guard = pool.lock()
        .map_err(|_| BrowserPoolError::PoolLock)?;

    let browser = guard.get()?;  // Returns BrowserPoolError
    let tab = browser.new_tab()
        .map_err(|e| BrowserPoolError::BrowserCreation(e.to_string()))?;

    tab.navigate_to(url)
        .map_err(|e| BrowserPoolError::BrowserCreation(e.to_string()))?;
    tab.wait_until_navigated()
        .map_err(|e| BrowserPoolError::BrowserCreation(e.to_string()))?;

    let pdf = tab.print_to_pdf(None)
        .map_err(|e| BrowserPoolError::BrowserCreation(e.to_string()))?;

    Ok(pdf)
}

§Feature Flag Reference

FeatureAdds to Prelude
(none)Core types only
env-configinit_browser_pool, from_env, chrome_path_from_env
actix-integrationactix module + service types
rocket-integrationrocket module + service types
axum-integrationaxum module + service types
test-utilsMockBrowserFactory (in factory::mock)

§See Also

Re-exports§

pub use crate::pool::BrowserPool;
pub use crate::pool::BrowserPoolBuilder;
pub use crate::config::BrowserPoolConfig;
pub use crate::config::BrowserPoolConfigBuilder;
pub use crate::error::BrowserPoolError;
pub use crate::error::Result;
pub use crate::handle::BrowserHandle;
pub use crate::stats::PoolStats;
pub use crate::factory::BrowserFactory;
pub use crate::factory::ChromeBrowserFactory;
pub use crate::traits::Healthcheck;
pub use crate::SharedBrowserPool;
pub use crate::pool::init_browser_pool;
pub use crate::config::env::from_env;
pub use crate::config::env::chrome_path_from_env;
pub use crate::service::PdfFromUrlRequest;
pub use crate::service::PdfFromHtmlRequest;
pub use crate::service::PdfResponse;
pub use crate::service::PdfServiceError;
pub use crate::service::ErrorResponse;
pub use crate::service::PoolStatsResponse;
pub use crate::service::HealthResponse;

Modules§

actix
Actix-web integration module.
axum
Axum integration module.
rocket
Rocket integration module.

Structs§

Arc
Thread-safe reference counting pointer.
Mutex
Mutual exclusion primitive.