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)
| Type | Description |
|---|---|
BrowserPool | Main pool for managing browser instances |
BrowserPoolBuilder | Builder for creating configured pools |
BrowserPoolConfig | Configuration settings for the pool |
BrowserPoolConfigBuilder | Builder for creating configurations |
BrowserPoolError | Error type for pool operations |
Result | Type alias for Result<T, BrowserPoolError> |
BrowserHandle | RAII handle for checked-out browsers |
PoolStats | Real-time pool statistics |
BrowserFactory | Trait for browser creation strategies |
ChromeBrowserFactory | Default Chrome/Chromium factory |
Healthcheck | Trait for browser health checking |
SharedBrowserPool | Type alias for Arc<Mutex<BrowserPool>> |
§Standard Library Re-exports
For convenience, commonly needed types are re-exported:
§Feature-Gated Exports
Additional exports are available with feature flags:
§env-config Feature
| Export | Description |
|---|---|
init_browser_pool | Initialize pool from environment variables |
from_env | Load configuration from environment |
chrome_path_from_env | Get Chrome path from CHROME_PATH env var |
§actix-integration Feature
| Export | Description |
|---|---|
actix module | Actix-web handlers and helpers |
§rocket-integration Feature
| Export | Description |
|---|---|
rocket module | Rocket handlers and helpers |
§axum-integration Feature
| Export | Description |
|---|---|
axum module | Axum handlers and router |
§Any Integration Feature
When any integration feature is enabled, service types are also available:
| Type | Description |
|---|---|
PdfFromUrlRequest | Request parameters for URL-to-PDF |
PdfFromHtmlRequest | Request parameters for HTML-to-PDF |
PdfResponse | Successful PDF generation result |
PdfServiceError | Service-level errors |
ErrorResponse | JSON error response format |
PoolStatsResponse | Pool statistics response |
HealthResponse | Health 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
| Feature | Adds to Prelude |
|---|---|
| (none) | Core types only |
env-config | init_browser_pool, from_env, chrome_path_from_env |
actix-integration | actix module + service types |
rocket-integration | rocket module + service types |
axum-integration | axum module + service types |
test-utils | MockBrowserFactory (in factory::mock) |
§See Also
crate::pool- Browser pool implementation detailscrate::config- Configuration optionscrate::service- Core PDF generation servicecrate::integrations- Web framework integrations
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::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;