### Getting File Metadata with `and_then` Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Shows how to use `and_then` to chain fallible file system operations, such as getting metadata and then its modification time. Includes examples for success and expected 'not found' errors. ```Rust use std::{io::ErrorKind, path::Path}; // Note: on Windows "/" maps to "C:\\" let root_modified_time = Path::new("/").metadata().and_then(|md| md.modified()); assert!(root_modified_time.is_ok()); let should_fail = Path::new("/bad/path").metadata().and_then(|md| md.modified()); assert!(should_fail.is_err()); assert_eq!(should_fail.unwrap_err().kind(), ErrorKind::NotFound); ``` -------------------------------- ### FromIterator Example (Ok) Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html Demonstrates collecting an iterator of Results into a single Result, succeeding when all elements are Ok. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### Chrome Renderer Example Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/renderer/chrome.rs.html?search=std%3A%3Avec Demonstrates how to create a new Chrome renderer and render HTML content to PDF. Ensure you have the necessary dependencies and configurations set up. ```rust use carbonpdf::{ChromeRenderer, PdfConfig}; use carbonpdf::renderer::ResolvedInput; use carbonpdf::config::ChromeConfig; use crate::carbonpdf::PdfRenderer; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let config = ChromeConfig::default(); let renderer = ChromeRenderer::new(config).await?; let input = ResolvedInput::Html("

Test

".to_string()); let pdf_config = PdfConfig::default(); let pdf = renderer.render(input, pdf_config).await?; # Ok(()) # } ``` -------------------------------- ### Quick Start: Convert HTML to PDF Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/index.html?search= Demonstrates how to convert an HTML string to a PDF document using the PdfBuilder. Ensure the 'chrome' feature flag is enabled. ```rust use carbonpdf::{PdfBuilder, PageSize, Result}; #[tokio::main] async fn main() -> Result<()> { // Convert HTML string to PDF let pdf = PdfBuilder::new() .html("

Hello, PDF!

") .page_size(PageSize::A4) .margin_all(1.0) .build() .await?; std::fs::write("output.pdf", pdf)?; Ok(()) } ``` -------------------------------- ### Product of Results Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates multiplying numbers from a vector of strings using the `product` method on an iterator of Results. It shows success and failure cases. ```rust let nums = vec!["5", "10", "1", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert_eq!(total, Ok(100)); let nums = vec!["5", "10", "one", "2"]; let total: Result = nums.iter().map(|w| w.parse::()).product(); assert!(total.is_err()); ``` -------------------------------- ### PdfBuilder::chrome_path Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html?search=u32+-%3E+bool Provides the explicit path to the Chrome binary, useful for custom installations. ```APIDOC ## PdfBuilder::chrome_path ### Description Sets the path to the Chrome binary. ### Method `chrome_path>(self, path: S) -> Self` ### Parameters - `path` (string): The file system path to the Chrome executable. ``` -------------------------------- ### unwrap_or_else Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates using unwrap_or_else with a closure to provide a default value when the Result is an Err. ```rust assert_eq!(Ok(2).unwrap_or_else(count), 2); assert_eq!(Err("foo").unwrap_or_else(count), 3); ``` -------------------------------- ### Get Basic PDF Information Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/utils.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves basic information from PDF bytes, including the PDF version and an estimated page count. Returns `None` if the input does not appear to be a valid PDF (e.g., does not start with '%PDF-'). ```rust /// Get PDF metadata (basic validation). /// /// Returns (version, page_count_estimate) or None if invalid. pub fn get_pdf_info(pdf: &[u8]) -> Option<(String, usize)> { if !pdf.starts_with(b"%PDF-") { return None; } let version = String::from_utf8_lossy(&pdf[5..8]).to_string(); let content = String::from_utf8_lossy(pdf); let page_count = content.matches("/Type /Page").count(); Some((version, page_count)) } ``` -------------------------------- ### IntoIterator Example: Ok Variant Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates converting an Ok Result into an iterator that yields the contained value. ```rust let x: Result = Ok(5); let v: Vec = x.into_iter().collect(); assert_eq!(v, [5]); ``` -------------------------------- ### FromIterator Example: Collection with Underflow Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Shows how collecting an iterator of Results stops and returns the first Err encountered, in this case due to underflow. ```rust let v = vec![1, 2, 0]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Err("Underflow!")); ``` -------------------------------- ### FromIterator Example: Successful Collection Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates collecting an iterator of Results into a single Result containing a collection of Ok values. If any element is an Err, it is returned immediately. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_add(1).ok_or("Overflow!") ).collect(); assert_eq!(res, Ok(vec![2, 3])); ``` -------------------------------- ### Example Usage of encode_base64 Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/utils/fn.encode_base64.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates how to use the encode_base64 function to convert PDF bytes into a base64 encoded string, suitable for embedding in JSON. Requires importing PdfBuilder and utils. ```rust use carbonpdf::{PdfBuilder, utils}; let pdf = PdfBuilder::new() .html("

Test

") .build() .await?; let base64 = utils::encode_base64(&pdf); println!("data:application/pdf;base64,{}", base64); ``` -------------------------------- ### Basic PDF Generation with PdfBuilder Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Demonstrates creating a PDF from HTML content, setting page size, margins, and background printing. The build() method is called asynchronously. ```rust use carbonpdf::{PdfBuilder, PageSize}; let pdf = PdfBuilder::new() .html("

Hello World

") .page_size(PageSize::A4) .margin_all(1.0) .print_background(true) .build() .await?; ``` -------------------------------- ### Unsafe unwrap_err_unchecked Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Shows how to get the contained Err value without checking if it's an Ok. Calling this on an Ok is undefined behavior. ```rust let x: Result = Err("emergency failure"); assert_eq!(unsafe { x.unwrap_err_unchecked() }, "emergency failure"); ``` -------------------------------- ### Unsafe unwrap_unchecked Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Shows how to get the contained Ok value without checking if it's an Err. Calling this on an Err is undefined behavior. ```rust let x: Result = Ok(2); assert_eq!(unsafe { x.unwrap_unchecked() }, 2); ``` -------------------------------- ### Get Basic PDF Information Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/utils.rs.html?search=std%3A%3Avec Retrieves basic information from a PDF byte slice, including the PDF version and an estimated page count. It performs a preliminary check to ensure the data starts with '%PDF-'. ```rust pub fn get_pdf_info(pdf: &[u8]) -> Option<(String, usize)> { if !pdf.starts_with(b"%PDF-") { return None; } let version = String::from_utf8_lossy(&pdf[5..8]).to_string(); let content = String::from_utf8_lossy(pdf); let page_count = content.matches("/Type /Page").count(); Some((version, page_count)) } ``` -------------------------------- ### PolicyExt Or Method Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/input/enum.InputSource.html?search= Creates a new Policy that returns Action::Follow if either self or other return Action::Follow. ```rust fn or(self, other: P) -> Or where T: Sized + Policy, P: Policy, ``` -------------------------------- ### Any Trait Implementation Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/input/enum.InputSource.html?search= Provides the `type_id` method to get the unique identifier of an object. ```APIDOC ## fn type_id(&self) -> TypeId ### Description Gets the `TypeId` of `self`. ### Method `type_id` ### Parameters None ### Response #### Success Response - **TypeId**: The unique identifier of the object. ``` -------------------------------- ### Initialize ChromeRenderer and Render PDF Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/renderer/chrome/struct.ChromeRenderer.html?search=u32+-%3E+bool Demonstrates how to create a new ChromeRenderer instance with default configuration and then use it to render HTML content into a PDF document. Requires Chrome DevTools Protocol compatibility. ```rust use carbonpdf::{ChromeRenderer, PdfConfig}; use carbonpdf::renderer::ResolvedInput; use carbonpdf::config::ChromeConfig; use crate::carbonpdf::PdfRenderer; let config = ChromeConfig::default(); let renderer = ChromeRenderer::new(config).await?; let input = ResolvedInput::Html("

Test

".to_string()); let pdf_config = PdfConfig::default(); let pdf = renderer.render(input, pdf_config).await?; ``` -------------------------------- ### build_with Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=std%3A%3Avec Build and generate the PDF using a provided custom renderer. ```APIDOC ## build_with ### Description Build and generate the PDF using a provided custom renderer that implements the `PdfRenderer` trait. ### Method ```rust pub async fn build_with( self, renderer: &R, ) -> Result> ``` ### Parameters * **renderer** (&R: PdfRenderer) - A reference to a type implementing the `PdfRenderer` trait. ``` -------------------------------- ### Basic HTML to PDF Generation Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use this snippet to create a PDF from simple HTML content. It demonstrates setting page size, margins, and print background options. ```rust use carbonpdf::{PdfBuilder, PageSize}; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let pdf = PdfBuilder::new() .html("

Hello World

") .page_size(PageSize::A4) .margin_all(1.0) .print_background(true) .build() .await?; # Ok(()) # } ``` -------------------------------- ### Get TypeId of Self Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/config/enum.Orientation.html?search=std%3A%3Avec Retrieves the `TypeId` of the current instance. This is useful for runtime type identification. ```rust fn type_id(&self) -> TypeId ``` -------------------------------- ### build_with Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=u32+-%3E+bool Build and generate the PDF using a provided custom PDF renderer. ```APIDOC ## build_with ### Description Build and generate the PDF using a provided custom PDF renderer. ### Method Async builder method ### Parameters * **renderer** (&R: PdfRenderer) - A reference to a type implementing the PdfRenderer trait. ``` -------------------------------- ### IntoIterator Example: Err Variant Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates converting an Err Result into an iterator that yields no values. ```rust let x: Result = Err("nothing!"); let v: Vec = x.into_iter().collect(); assert_eq!(v, []); ``` -------------------------------- ### ChromeRenderer::new Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/renderer/chrome/struct.ChromeRenderer.html Creates a new Chrome renderer instance with the specified configuration. This is the entry point for initializing the renderer. ```APIDOC ## `new` - ChromeRenderer::new ### Description Create a new Chrome renderer with the given configuration. ### Method `pub async fn new(config: ChromeConfig) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust use carbonpdf::ChromeRenderer; use carbonpdf::config::ChromeConfig; let config = ChromeConfig::default(); let renderer = ChromeRenderer::new(config).await?; ``` ### Response #### Success Response (Result) - `Self`: A new instance of `ChromeRenderer`. #### Response Example ```rust // Successful creation of ChromeRenderer let renderer = ChromeRenderer::new(ChromeConfig::default()).await?; ``` ### Error Handling - Returns `Result` which can contain an error if the renderer fails to initialize. ``` -------------------------------- ### Unsafe unwrap_err_unchecked on Ok Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Illustrates the undefined behavior that occurs when calling unwrap_err_unchecked on an Ok variant. ```rust let x: Result = Ok(2); unsafe { x.unwrap_err_unchecked() }; // Undefined behavior! ``` -------------------------------- ### Initialize ChromeRenderer with Custom Configuration Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/renderer/chrome.rs.html?search=u32+-%3E+bool Shows how to initialize the ChromeRenderer with a custom ChromeConfig, including specifying the binary path, headless mode, no-sandbox flag, and extra arguments. ```rust let profile_dir = TempDir::new() .map_err(|e| Error::ChromeProcess(format!("Failed to create temp profile: {}", e)))?; let mut builder = BrowserConfig::builder() .user_data_dir(profile_dir.path()); // Set Chrome binary path if provided if let Some(path) = config.binary_path { builder = builder.chrome_executable(path); } // Configure headless mode if config.headless { builder = builder.with_head(); } // Add sandbox flag if requested if config.no_sandbox { builder = builder.arg("--no-sandbox"); } // Add extra arguments for arg in config.extra_args { builder = builder.arg(arg); } let browser_config = builder.build() .map_err(|e| Error::ChromeProcess(format!("Failed to build config: {}", e)))?; // Launch browser with timeout let (browser, handler) = timeout( Duration::from_secs(config.connection_timeout), Browser::launch(browser_config) ) .await .map_err(|_| Error::Timeout(config.connection_timeout))? .map_err(|e| Error::ChromeProcess(format!("Failed to launch Chrome: {}", e)))?; let handler_task = tokio::spawn(async move { let mut handler = handler; while let Some(event) = handler.next().await { if let Err(e) = event { tracing::error!("Chrome handler error: {}", e); break; } } }); Ok(Self { browser: Arc::new(browser), _handler_task: handler_task, _profile_dir: profile_dir, }) ``` -------------------------------- ### Unsafe unwrap_unchecked on Err Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Illustrates the undefined behavior that occurs when calling unwrap_unchecked on an Err variant. ```rust let x: Result = Err("emergency failure"); unsafe { x.unwrap_unchecked() }; // Undefined behavior! ``` -------------------------------- ### PolicyExt And Method Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/input/enum.InputSource.html?search= Creates a new Policy that returns Action::Follow only if self and other return Action::Follow. ```rust fn and(self, other: P) -> And where T: Sized + Policy, P: Policy, ``` -------------------------------- ### chrome_path Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=u32+-%3E+bool Set the path to the Chrome binary. ```APIDOC ## chrome_path ### Description Set the path to the Chrome binary to be used for rendering. ### Method Builder method ### Parameters * **path** (S: Into) - The file system path to the Chrome executable. ``` -------------------------------- ### chrome_path Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=std%3A%3Avec Set the path to the Chrome binary. ```APIDOC ## chrome_path ### Description Set the path to the Chrome binary to be used for rendering. ### Method ```rust pub fn chrome_path>(mut self, path: S) -> Self ``` ### Parameters * **path** (S: Into) - The file system path to the Chrome executable. ``` -------------------------------- ### Get Page Dimensions in Inches Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/config/enum.PageSize.html Retrieves the width and height of a PageSize variant in inches. Useful for calculations or display. ```rust pub fn dimensions_inches(&self) -> (f64, f64) ``` -------------------------------- ### Termination for Result Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Provides a way to get the representation of a Result value as a status code, which is returned to the operating system. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Method fn ### Parameters None ``` -------------------------------- ### PdfBuilder::build_with Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html Builds and generates the PDF document asynchronously using a custom provided renderer. ```APIDOC ## PdfBuilder::build_with ### Description Build and generate the PDF using a custom renderer. ### Method Asynchronous builder method ### Signature `pub async fn build_with(self, renderer: &R) -> Result>` ### Parameters * **renderer** (&R) - Required - A reference to a type implementing the `PdfRenderer` trait. ### Returns A `Result` containing a `Vec` (the PDF file content) on success, or an error on failure. ``` -------------------------------- ### Termination for Result Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html Provides a way to get the representation of a Result value as an exit code, which is then returned to the operating system. ```APIDOC ## fn report(self) -> ExitCode ### Description Is called to get the representation of the value as status code. This status code is returned to the operating system. ### Method `report` ### Parameters None ### Response - **ExitCode**: The exit code representation of the Result. ``` -------------------------------- ### Collecting Results with checked_sub (no underflow) Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search= Shows collecting an iterator of Results, handling potential underflow with checked_sub. This example succeeds. ```rust let v = vec![1, 2]; let res: Result, &'static str> = v.iter().map(|x: &u32| x.checked_sub(1).ok_or("Underflow!") ).collect(); assert_eq!(res, Ok(vec![0, 1])); ``` -------------------------------- ### ChromeRenderer::new Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/renderer/chrome/struct.ChromeRenderer.html?search=u32+-%3E+bool Creates a new instance of the ChromeRenderer. This method initializes the renderer with the provided configuration, enabling it to convert HTML to PDF. ```APIDOC ## pub async fn new(config: ChromeConfig) -> Result ### Description Create a new Chrome renderer with the given configuration. ### Method `async fn new` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body * **config** (ChromeConfig) - Required - The configuration for the Chrome renderer. ``` -------------------------------- ### InputSource Constructor Methods Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/input.rs.html?search=std%3A%3Avec Provides convenient methods to create instances of InputSource for HTML strings, file paths, and URLs. These methods abstract away the direct enum variant instantiation. ```rust impl InputSource { /// Create an HTML string input source. pub fn html>(content: S) -> Self { Self::Html(content.into()) } /// Create a file input source. pub fn file>(path: P) -> Self { Self::File(path.into()) } /// Create a URL input source. pub fn url>(url: S) -> Self { Self::Url(url.into()) } } ``` -------------------------------- ### ChromeRenderer::new Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/renderer/chrome.rs.html Creates a new Chrome renderer instance. This method initializes Headless Chrome with the provided configuration, including options for the Chrome binary path, headless mode, sandbox settings, and extra arguments. It returns a Result containing the initialized ChromeRenderer or an Error if initialization fails. ```APIDOC ## ChromeRenderer::new ### Description Creates a new Chrome renderer instance. This method initializes Headless Chrome with the provided configuration, including options for the Chrome binary path, headless mode, sandbox settings, and extra arguments. It returns a Result containing the initialized ChromeRenderer or an Error if initialization fails. ### Method `pub async fn new(config: ChromeConfig) -> Result` ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```rust,no_run use carbonpdf::{ChromeRenderer, PdfConfig}; use carbonpdf::renderer::ResolvedInput; use carbonpdf::config::ChromeConfig; use crate::carbonpdf::PdfRenderer; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let config = ChromeConfig::default(); let renderer = ChromeRenderer::new(config).await?; let input = ResolvedInput::Html("

Test

".to_string()); let pdf_config = PdfConfig::default(); let pdf = renderer.render(input, pdf_config).await?; # Ok(()) # } ``` ### Response #### Success Response - **Self** (ChromeRenderer) - A new instance of ChromeRenderer. #### Response Example None provided in source. ### Error Handling - **Error::ChromeProcess** - If there's an issue creating the temporary profile directory or launching Chrome. - **Error::Timeout** - If the connection to Chrome times out. ``` -------------------------------- ### Build PDF from HTML content Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html Use this snippet to generate a PDF directly from an HTML string. Configure page size, margins, and print background settings as needed. ```rust use carbonpdf::{PdfBuilder, PageSize}; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let pdf = PdfBuilder::new() .html("

Hello World

") .page_size(PageSize::A4) .margin_all(1.0) .print_background(true) .build() .await?; # Ok(()) # } ``` -------------------------------- ### FromIterator Example: Early Termination Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Illustrates that `collect()` on an iterator of Results terminates upon encountering the first Err, preventing further processing of iterator elements. ```rust let v = vec![3, 2, 1, 10]; let mut shared = 0; let res: Result, &'static str> = v.iter().map(|x: &u32| { shared += x; x.checked_sub(2).ok_or("Underflow!") }).collect(); assert_eq!(res, Err("Underflow!")); assert_eq!(shared, 6); ``` -------------------------------- ### PdfBuilder::build Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html?search=u32+-%3E+bool Initiates the PDF generation process using the configured settings and returns the PDF as a byte vector. ```APIDOC ## PdfBuilder::build ### Description Builds and generates the PDF using the configured settings and the default Chrome renderer. ### Method `build(self) -> Result>` ### Returns - `Result>`: A `Result` containing the PDF content as a byte vector on success, or an error on failure. ``` -------------------------------- ### Get PDF Info Function Signature Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/utils/fn.get_pdf_info.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Retrieves basic PDF metadata including version and an estimated page count. Returns None if the PDF is invalid. ```rust pub fn get_pdf_info(pdf: &[u8]) -> Option<(String, usize)> ``` -------------------------------- ### Default PDF Configuration Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/config.rs.html Provides the default settings for PDF generation. This is useful when you need a basic configuration without specifying every parameter. ```rust impl Default for PdfConfig { fn default() -> Self { Self { page_size: PageSize::A4, orientation: Orientation::Portrait, margins: Margins::default(), scale: 1.0, print_background: true, display_header_footer: false, header_template: None, footer_template: None, prefer_css_page_size: false, timeout_seconds: 30, } } } ``` -------------------------------- ### Create File Input Source Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/input/enum.InputSource.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Use this function to create an InputSource variant from a local file path. ```rust pub fn file>(path: P) -> Self ``` -------------------------------- ### Sum of Results Example Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Illustrates summing integers from a vector, with a condition to return an error if a negative element is encountered. This uses the `sum` method on an iterator of Results. ```rust let f = |&x: &i32| if x < 0 { Err("Negative element found") } else { Ok(x) }; let v = vec![1, 2]; ``` -------------------------------- ### PdfBuilder::build_with Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html?search=u32+-%3E+bool Generates the PDF using a provided custom renderer implementation. ```APIDOC ## PdfBuilder::build_with ### Description Builds and generates the PDF using a custom renderer. ### Method `build_with(self, renderer: &R) -> Result>` ### Parameters - `renderer` (&R): A reference to a type implementing the `PdfRenderer` trait. ``` -------------------------------- ### Build PDF with Custom Renderer Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Builds and generates the PDF using a provided custom `PdfRenderer`. Ensures input source is specified and configuration is valid before rendering. ```rust pub async fn build_with( self, renderer: &R, ) -> Result> { let input = self.input.ok_or_else(|| crate::Error::InvalidConfig("No input source specified".to_string()) )?; self.config.validate()?; let resolved = match input { InputSource::Url(url) => ResolvedInput::Url(url), other => ResolvedInput::Html(other.resolve().await?), }; renderer.render(resolved, self.config).await } ``` -------------------------------- ### Unwrap or default value Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `unwrap_or_default` to get the `Ok` value or a default value if it's an `Err`. This is useful for providing fallback values when an operation might fail. ```Rust let good_year_from_input = "1909"; let bad_year_from_input = "190blarg"; let good_year = good_year_from_input.parse().unwrap_or_default(); let bad_year = bad_year_from_input.parse().unwrap_or_default(); assert_eq!(1909, good_year); assert_eq!(0, bad_year); ``` -------------------------------- ### Policy AND Operation Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/config/enum.Orientation.html?search=std%3A%3Avec Creates a new `Policy` that returns `Action::Follow` only if both `self` and `other` policies return `Action::Follow`. Combines two policies with a logical AND. ```rust fn and(self, other: P) -> And where T: Sized + Policy, P: Policy ``` -------------------------------- ### Unwrap Err value Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `unwrap_err` to get the `Err` value. This method panics if the `Result` is an `Ok`. It's useful when you expect an error and want to assert its content. ```Rust let x: Result = Err("emergency failure"); assert_eq!(x.unwrap_err(), "emergency failure"); ``` -------------------------------- ### Setting Page Size and Margins Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Configure the page dimensions and margins for the PDF. Supports standard sizes and custom dimensions. ```rust use carbonpdf::{PdfBuilder, PageSize}; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let pdf = PdfBuilder::new() .page_size(PageSize::A4) // Set to A4 .custom_page_size(8.5, 11.0) // Set custom size in inches .margin_all(0.5) // Set all margins to 0.5 inches .margins(1.0, 0.5, 1.0, 0.5) // Set top, right, bottom, left margins .build() .await?; # Ok(()) # } ``` -------------------------------- ### InputSource Methods Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/input.rs.html?search=std%3A%3Avec Convenience methods for creating InputSource variants. These methods simplify the process of initializing input sources for HTML strings, files, URLs, and templates. ```APIDOC ## InputSource Methods ### `html>(content: S) -> Self` Creates an `InputSource::Html` variant from a given string. ### `file>(path: P) -> Self` Creates an `InputSource::File` variant from a path. ### `url>(url: S) -> Self` Creates an `InputSource::Url` variant from a URL string. ### `template(template: S, data: D) -> Result` (requires `templates` feature) Creates an `InputSource::Template` variant using an inline template string and serializable data. ### `template_file(path: P, data: D) -> Result` (requires `templates` feature) Creates an `InputSource::Template` variant using a template file path and serializable data. ``` -------------------------------- ### Unwrap Ok value Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `unwrap` to get the `Ok` value. This method panics if the `Result` is an `Err`. It's generally discouraged in favor of safer error handling. ```Rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` -------------------------------- ### chrome_path Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search= Sets the path to the Chrome binary executable. ```APIDOC ## chrome_path ### Description Sets the path to the Chrome binary executable. ### Method Builder method (Chained) ### Parameters * **path** (string) - Description: The file path to the Chrome binary. ### Return Type Self (The builder instance) ``` -------------------------------- ### Get references from Result using as_ref() Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `as_ref()` to convert a `&Result` into a `Result<&T, &E>`. This allows you to inspect the contents of a `Result` by reference without consuming it. ```rust let x: Result = Ok(2); assert_eq!(x.as_ref(), Ok(&2)); let x: Result = Err("Error"); assert_eq!(x.as_ref(), Err(&"Error")); ``` -------------------------------- ### Builder Configuration Methods Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html These methods allow you to configure various aspects of the PDF generation process before building the final PDF. They are chainable and return the builder instance for further configuration. ```APIDOC ## Builder Methods ### `scale(scale: f64) -> Self` Sets the scale factor for the PDF. The scale should be between 0.1 and 2.0. ### `print_background(enabled: bool) -> Self` Enables or disables the printing of background graphics in the PDF. ### `header>(template: S) -> Self` Sets an HTML template for the PDF header. This also enables the display of the header. ### `footer>(template: S) -> Self` Sets an HTML template for the PDF footer. This also enables the display of the footer. ### `timeout(seconds: u64) -> Self` Sets the generation timeout for the PDF in seconds. ### `chrome_path>(path: S) -> Self` Sets the path to the Chrome binary to be used for rendering. ### `no_sandbox() -> Self` Disables the Chrome sandbox, which can be useful in environments like Docker or CI. ### `chrome_args(args: I) -> Self` Adds custom arguments to be passed to the Chrome instance. `I` must be an iterator of items convertible to strings. ``` -------------------------------- ### Unwrap Ok value or panic Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html Use `unwrap()` to get the contained `Ok` value. This method will panic if the `Result` is an `Err`. It is generally discouraged in favor of safer error handling. ```rust let x: Result = Ok(2); assert_eq!(x.unwrap(), 2); ``` ```rust let x: Result = Err("emergency failure"); x.unwrap(); // panics with `emergency failure` ``` -------------------------------- ### PDF Generation from Template File Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Create a PDF by rendering a Handlebars template file with provided data. This also requires the 'templates' feature. ```rust use carbonpdf::PdfBuilder; use serde_json::json; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let data = json!({ "title": "My Document", "content": "Document content here" }); let pdf = PdfBuilder::new() .template_file("templates/custom.hbs", data)? .build() .await?; # Ok(()) # } ``` -------------------------------- ### Expect Err value with custom message Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `expect_err` to get the `Err` value, panicking with a custom message if the `Result` is an `Ok`. This is helpful for asserting expected error conditions during testing. ```Rust let x: Result = Ok(10); x.expect_err("Testing expect_err"); // panics with `Testing expect_err: 10` ``` -------------------------------- ### build Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=std%3A%3Avec Build and generate the PDF using the configured Chrome renderer. Requires the 'chrome' feature to be enabled. ```APIDOC ## build ### Description Build and generate the PDF using the configured Chrome renderer. This method requires the `chrome` feature to be enabled. ### Method ```rust #[cfg(feature = "chrome")] pub async fn build(self) -> Result> ``` ### Returns * `Result>` - A `Result` containing a vector of bytes representing the PDF on success, or an error on failure. ``` -------------------------------- ### Get Basic PDF Info Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/utils.rs.html?search= Extracts basic information from PDF bytes, including the PDF version and an estimated page count. Returns None if the bytes do not appear to be a valid PDF. ```rust pub fn get_pdf_info(pdf: &[u8]) -> Option<(String, usize)> { if !pdf.starts_with(b"%PDF-") { return None; } let version = String::from_utf8_lossy(&pdf[5..8]).to_string(); let content = String::from_utf8_lossy(pdf); let page_count = content.matches("/Type /Page").count(); Some((version, page_count)) } ``` -------------------------------- ### Get mutable references from Result using as_mut() Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Use `as_mut()` to convert a `&mut Result` into a `Result<&mut T, &mut E>`. This enables modifying the contained value of a `Result` in place. ```rust fn mutate(r: &mut Result) { match r.as_mut() { Ok(v) => *v = 42, Err(e) => *e = 0, } } let mut x: Result = Ok(2); mutate(&mut x); assert_eq!(x.unwrap(), 42); let mut x: Result = Err(13); mutate(&mut x); assert_eq!(x.unwrap_err(), 0); ``` -------------------------------- ### Summing Iterator with Result Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html Demonstrates using `iter().map().sum()` with a Result type. The first example shows a successful summation, while the second illustrates error propagation when a negative element is encountered. ```rust let v = vec![1, 2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); ``` ```rust let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### InputSource Helper Methods Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/input.rs.html Provides convenient methods to create InputSource variants for HTML strings, files, URLs, and templates. Template creation methods require serialization of data into JSON. ```rust impl InputSource { /// Create an HTML string input source. pub fn html>(content: S) -> Self { Self::Html(content.into()) } /// Create a file input source. pub fn file>(path: P) -> Self { Self::File(path.into()) } /// Create a URL input source. pub fn url>(url: S) -> Self { Self::Url(url.into()) } /// Create a template input source with inline template string. #[cfg(feature = "templates")] pub fn template(template: S, data: D) -> Result where S: Into, D: serde::Serialize, { let data = serde_json::to_value(data) .map_err(|e| Error::Template(format!("Failed to serialize data: {}", e)))?; Ok(Self::Template { source: TemplateSource::Inline(template.into()), data, }) } /// Create a template input source with template file. #[cfg(feature = "templates")] pub fn template_file(path: P, data: D) -> Result where P: Into, D: serde::Serialize, { let data = serde_json::to_value(data) .map_err(|e| Error::Template(format!("Failed to serialize data: {}", e)))?; Ok(Self::Template { source: TemplateSource::File(path.into()), data, }) } } ``` -------------------------------- ### PdfRenderer Trait Definition Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/renderer/mod.rs.html?search= Defines the `PdfRenderer` trait for PDF rendering backends. It includes methods for rendering HTML to PDF and getting the renderer's name. This trait is generic over different rendering implementations. ```rust use async_trait::async_trait; use crate::{config::PdfConfig, Result}; #[cfg(feature = "chrome")] pub mod chrome; /// Resolved input for rendering. #[derive(Debug, Clone)] pub enum ResolvedInput { /// Raw HTML string Html(String), /// URL to fetch and render Url(String), } /// Trait for PDF rendering backends. /// /// This abstraction allows multiple rendering implementations (Chrome, Playwright, etc.) #[async_trait] pub trait PdfRenderer: Send + Sync { /// Render HTML content to PDF. /// /// # Arguments /// /// * `input` - Source of HTML content (string, file, or URL) /// * `config` - PDF generation configuration /// /// # Returns /// /// PDF file as a byte vector async fn render(&self, input: ResolvedInput, config: PdfConfig) -> Result>; /// Get the renderer name (for logging/debugging). fn name(&self) -> &str; } ``` -------------------------------- ### Setting Page Size Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=std%3A%3Avec Configure the page size for the PDF using predefined PageSize variants. ```rust let pdf = PdfBuilder::new() .page_size(PageSize::A4) .build() .await?; ``` -------------------------------- ### PDF Generation Methods Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html Methods for building and generating the PDF. These methods consume the builder and return the generated PDF as a byte vector. ```APIDOC ## PDF Generation ### `build() -> Result>` Builds and generates the PDF using the configured Chrome renderer. This method requires the `chrome` feature to be enabled. **Returns**: A `Result` containing a `Vec` of the PDF data on success, or an error. ### `build_with(renderer: &R) -> Result>` Builds and generates the PDF using a provided custom `PdfRenderer`. This allows for flexibility in choosing the rendering engine. **Parameters**: * `renderer` (&R): A reference to an object implementing the `PdfRenderer` trait. **Returns**: A `Result` containing a `Vec` of the PDF data on success, or an error. ``` -------------------------------- ### Summing elements in a Result with error handling Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Demonstrates using `iter().map().sum()` with a Result type. The first example shows a successful sum, while the second shows how an error condition (negative element) is propagated. ```rust let res: Result = v.iter().map(f).sum(); assert_eq!(res, Ok(3)); ``` ```rust let v = vec![1, -2]; let res: Result = v.iter().map(f).sum(); assert_eq!(res, Err("Negative element found")); ``` -------------------------------- ### Encode PDF Bytes to Base64 Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/utils.rs.html?search=std%3A%3Avec Encodes PDF byte slices into a base64 string. This is useful for embedding PDF data within JSON responses or other text-based formats. The example demonstrates building a PDF from HTML and then encoding it. ```rust use carbonpdf::{PdfBuilder, utils}; # #[tokio::main] # async fn main() -> carbonpdf::Result<()> { let pdf = PdfBuilder::new() .html("

Test

") .build() .await?; let base64 = utils::encode_base64(&pdf); println!("data:application/pdf;base64,{}", base64); # Ok(()) # } ``` -------------------------------- ### Build PDF with Chrome Renderer Source: https://docs.rs/carbonpdf/0.2.0/src/carbonpdf/builder.rs.html?search=Option%3CT%3E%2C+%28T+-%3E+U%29+-%3E+Option%3CU%3E Builds and generates the PDF using the configured Chrome renderer. Requires the 'chrome' feature to be enabled. Ensures input source is specified and configuration is valid before rendering. ```rust pub async fn build(self) -> Result> { let input = self .input .ok_or_else(|| crate::Error::InvalidConfig("No input source specified".to_string()))?; self.config.validate()?; let resolved = match input { InputSource::Url(url) => ResolvedInput::Url(url), other => ResolvedInput::Html(other.resolve().await?), }; let renderer = ChromeRenderer::new(self.chrome_config).await?; renderer.render(resolved, self.config).await } ``` -------------------------------- ### Policy OR Operation Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/config/enum.Orientation.html?search=std%3A%3Avec Creates a new `Policy` that returns `Action::Follow` if either `self` or `other` policies return `Action::Follow`. Combines two policies with a logical OR. ```rust fn or(self, other: P) -> Or where T: Sized + Policy, P: Policy ``` -------------------------------- ### PdfBuilder::new Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/builder/struct.PdfBuilder.html?search=u32+-%3E+bool Creates a new PDF builder instance with default settings, serving as the entry point for PDF generation configuration. ```APIDOC ## PdfBuilder::new ### Description Creates a new PDF builder with default settings. ### Method `new()` ### Returns - `Self`: A new instance of `PdfBuilder`. ``` -------------------------------- ### into_ok Source: https://docs.rs/carbonpdf/0.2.0/carbonpdf/error/type.Result.html?search=u32+-%3E+bool Returns the contained `Ok` value, but never panics. This is an experimental API. ```APIDOC ## pub const fn into_ok(self) -> T ### Description Returns the contained `Ok` value, but never panics. Unlike `unwrap`, this method is known to never panic on the result types it is implemented for. Therefore, it can be used instead of `unwrap` as a maintainability safeguard that will fail to compile if the error type of the `Result` is later changed to an error that can actually occur. ### Examples ```rust fn only_good_news() -> Result { Ok("this is fine".into()) } let s: String = only_good_news().into_ok(); println!("{s}"); ``` ```