Expand description
Rocket framework integration.
This module provides helpers and pre-built handlers for using BrowserPool
with Rocket. You can choose between using the pre-built handlers for
quick setup, or writing custom handlers for full control.
§Quick Start
§Option 1: Pre-built Routes (Fastest Setup)
Use configure_routes to add all PDF endpoints with a single line:
ⓘ
use rocket::launch;
use html2pdf_api::prelude::*;
#[launch]
async fn rocket() -> _ {
let pool = init_browser_pool().await
.expect("Failed to initialize browser pool");
rocket::build()
.manage(pool)
.configure(html2pdf_api::integrations::rocket::configure_routes)
}This gives you the following endpoints:
| Method | Path | Description |
|---|---|---|
| GET | /pdf?url=... | Convert URL to PDF |
| POST | /pdf/html | Convert HTML to PDF |
| GET | /pool/stats | Pool statistics |
| GET | /health | Health check |
| GET | /ready | Readiness check |
§Option 2: Mix Pre-built and Custom Handlers
Use individual pre-built handlers alongside your own:
ⓘ
use rocket::{get, launch, routes};
use html2pdf_api::prelude::*;
use html2pdf_api::integrations::rocket::{pdf_from_url, health_check};
#[get("/custom")]
fn my_custom_handler() -> &'static str {
"Custom response"
}
#[launch]
async fn rocket() -> _ {
let pool = init_browser_pool().await
.expect("Failed to initialize browser pool");
rocket::build()
.manage(pool)
.mount("/", routes![
pdf_from_url,
health_check,
my_custom_handler
])
}§Option 3: Custom Handlers with Service Functions
For full control, use the service functions directly:
ⓘ
use rocket::{get, http::Status, serde::json::Json, State};
use html2pdf_api::prelude::*;
use html2pdf_api::service::{generate_pdf_from_url, PdfFromUrlRequest};
#[get("/my-pdf?<url>")]
async fn my_pdf_handler(
pool: &State<SharedBrowserPool>,
url: String,
) -> Result<Vec<u8>, Status> {
// Custom pre-processing: auth, rate limiting, logging, etc.
log::info!("Custom handler: {}", url);
let pool = pool.inner().clone();
let request = PdfFromUrlRequest {
url,
filename: Some("custom.pdf".to_string()),
..Default::default()
};
// Call service in blocking context
let result = tokio::task::spawn_blocking(move || {
generate_pdf_from_url(&pool, &request)
}).await;
match result {
Ok(Ok(pdf)) => {
// Custom post-processing
Ok(pdf.data)
}
Ok(Err(_)) => Err(Status::BadRequest),
Err(_) => Err(Status::InternalServerError),
}
}§Option 4: Full Manual Control (Original Approach)
For complete control over browser operations:
ⓘ
use rocket::{get, http::Status, State};
use html2pdf_api::prelude::*;
#[get("/manual-pdf")]
fn manual_pdf_handler(
pool: &State<SharedBrowserPool>,
) -> Result<Vec<u8>, Status> {
let pool_guard = pool.lock()
.map_err(|_| Status::InternalServerError)?;
let browser = pool_guard.get()
.map_err(|_| Status::ServiceUnavailable)?;
let tab = browser.new_tab()
.map_err(|_| Status::InternalServerError)?;
tab.navigate_to("https://example.com")
.map_err(|_| Status::BadGateway)?;
tab.wait_until_navigated()
.map_err(|_| Status::BadGateway)?;
let pdf_data = tab.print_to_pdf(None)
.map_err(|_| Status::InternalServerError)?;
Ok(pdf_data)
}§Setup
Add to your Cargo.toml:
[dependencies]
html2pdf-api = { version = "0.2", features = ["rocket-integration"] }
rocket = { version = "0.5", features = ["json"] }§Graceful Shutdown
For proper cleanup, use Rocket’s shutdown fairing:
ⓘ
use rocket::{fairing::{Fairing, Info, Kind}, launch, Orbit, Rocket};
use html2pdf_api::prelude::*;
use std::sync::Arc;
struct ShutdownFairing {
pool: SharedBrowserPool,
}
#[rocket::async_trait]
impl Fairing for ShutdownFairing {
fn info(&self) -> Info {
Info {
name: "Browser Pool Shutdown",
kind: Kind::Shutdown,
}
}
async fn on_shutdown(&self, _rocket: &Rocket<Orbit>) {
if let Ok(mut pool) = self.pool.lock() {
pool.shutdown();
}
}
}
#[launch]
async fn rocket() -> _ {
let pool = init_browser_pool().await
.expect("Failed to initialize browser pool");
let shutdown_pool = pool.clone();
rocket::build()
.manage(pool)
.attach(ShutdownFairing { pool: shutdown_pool })
.configure(html2pdf_api::integrations::rocket::configure_routes)
}§API Reference
§Pre-built Handlers
| Handler | Method | Default Path | Description |
|---|---|---|---|
pdf_from_url | GET | /pdf | Convert URL to PDF |
pdf_from_html | POST | /pdf/html | Convert HTML to PDF |
pool_stats | GET | /pool/stats | Pool statistics |
health_check | GET | /health | Health check (always 200) |
readiness_check | GET | /ready | Readiness check (checks pool) |
§Type Aliases
| Type | Description |
|---|---|
SharedPool | Arc<Mutex<BrowserPool>> - for service functions |
BrowserPoolState | &State<SharedBrowserPool> - for handler parameters |
§Helper Functions
| Function | Description |
|---|---|
configure_routes | Configure all pre-built routes |
routes() | Get all routes for manual mounting |
create_pool_data | Wrap SharedBrowserPool for Rocket managed state |
create_pool_data_from_arc | Wrap Arc<Mutex<BrowserPool>> for managed state |
§Extension Traits
| Trait | Description |
|---|---|
BrowserPoolRocketExt | Adds into_rocket_data() to BrowserPool |
Structs§
- Error
Responder - Error response wrapper for Rocket.
- PdfFrom
UrlQuery - Query parameters for PDF from URL endpoint.
- PdfResponder
- PDF response wrapper for Rocket.
Traits§
- Browser
Pool Rocket Ext - Extension trait for
BrowserPoolwith Rocket helpers.
Functions§
- configure_
routes - Configure all PDF routes.
- create_
pool_ data - Create Rocket managed state from an existing shared pool.
- create_
pool_ data_ from_ arc - Create Rocket managed state from an
Arcreference. - health_
check - Health check endpoint.
- pdf_
from_ html - Generate PDF from HTML content.
- pdf_
from_ url - Generate PDF from a URL.
- pool_
stats - Get browser pool statistics.
- readiness_
check - Readiness check endpoint.
- routes
- Get all routes for manual mounting.
Type Aliases§
- Browser
Pool State - Type alias for Rocket
Statewrapper around the shared pool. - Handler
Result - Result type for Rocket handlers.
- Shared
Pool - Type alias for shared browser pool.