### BTreeMap::new Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Creates a new, empty BTreeMap. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); // entries can now be inserted into the empty map map.insert(1, "a"); ``` -------------------------------- ### BTreeMap::iter Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Iterates over the entries of the map in sorted order. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::new(); map.insert(3, "c"); map.insert(2, "b"); map.insert(1, "a"); for (key, value) in map.iter() { println!("{key}: {value}"); } let (first_key, first_value) = map.iter().next().unwrap(); assert_eq!((*first_key, *first_value), (1, "a")); ``` -------------------------------- ### Initialize TextHole Source: https://docs.rs/printpdf/latest/printpdf/shape/struct.TextHole.html An example showing how to instantiate a TextHole with a specific rectangular region. ```rust let hole = TextHole { rect: Rect { x: Pt(100.0), y: Pt(200.0), width: Pt(50.0), height: Pt(50.0) } }; ``` -------------------------------- ### Using Pdf_BytesToDocumentSync in JavaScript Source: https://docs.rs/printpdf/latest/printpdf/wasm/api/fn.Pdf_BytesToDocumentSync.html Example showing how to prepare the input string and parse the result returned by Pdf_BytesToDocumentSync. ```javascript let input = JSON.stringify({ bytes: btoa(my_pdf_binary_string), options: {} }); let result = JSON.parse(Pdf_BytesToDocumentSync(input)); console.log(result.data.doc); // PdfDocument (same shape as Pdf_HtmlToDocumentSync) console.log(result.data.warnings); // [{ page, opId, severity, msg }] ``` -------------------------------- ### Pdf_DecodeImageSync usage example Source: https://docs.rs/printpdf/latest/printpdf/wasm/api/fn.Pdf_DecodeImageSync.html Example showing how to call Pdf_DecodeImageSync with a base64 encoded image and parse the resulting JSON response. ```javascript let r = JSON.parse(Pdf_DecodeImageSync(JSON.stringify({ bytes: pngB64 }))); // r == { status: 0, data: { image: { width, height, ... }, warnings: [] } } ``` -------------------------------- ### Creating LineDashPattern instances Source: https://docs.rs/printpdf/latest/printpdf/graphics/struct.LineDashPattern.html Examples of creating a dashed line pattern using a slice and creating a solid line pattern. ```rust let dashed = LineDashPattern::new(0.0, &[5.0, 3.0]); let solid = LineDashPattern::solid(); ``` -------------------------------- ### BTreeMap::lower_bound Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Demonstrates the nightly-only lower_bound API for BTreeMap cursors. ```rust #![feature(btree_cursors)] use std::collections::BTreeMap; use std::ops::Bound; let map = BTreeMap::from([ (1, "a"), (2, "b"), (3, "c"), (4, "d"), ]); let cursor = map.lower_bound(Bound::Included(&2)); assert_eq!(cursor.peek_prev(), Some((&1, &"a"))); assert_eq!(cursor.peek_next(), Some((&2, &"b"))); let cursor = map.lower_bound(Bound::Excluded(&2)); assert_eq!(cursor.peek_prev(), Some((&2, &"b"))); assert_eq!(cursor.peek_next(), Some((&3, &"c"))); let cursor = map.lower_bound(Bound::Unbounded); assert_eq!(cursor.peek_prev(), None); assert_eq!(cursor.peek_next(), Some((&1, &"a"))); ``` -------------------------------- ### Using Pdf_HtmlToDocumentSync Source: https://docs.rs/printpdf/latest/printpdf/wasm/api/fn.Pdf_HtmlToDocumentSync.html Example usage of Pdf_HtmlToDocumentSync showing how to pass a JSON-stringified input and parse the resulting JSON output. ```javascript let html = "

Hello!

"; let input = JSON.stringify({ html: html, fonts: {}, images: {} }); let result = JSON.parse(Pdf_HtmlToDocumentSync(input)); console.log(result); // { // status: 0, // 1 = bad input, 2 = conversion failed, 3 = output unserializable // data: { // doc: { // metadata: { info, xmp? }, // resources: { fonts, xobjects, extgstates, shadings, layers }, // bookmarks: {}, // pages: [{ mediaBox, trimBox, cropBox, ops }] // }, // warnings: [{ page, opId, severity, msg }] // } // on status != 0, `data` is the error string instead // } ``` -------------------------------- ### BTreeMap::entry example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Gets the given key’s corresponding entry in the map for in-place manipulation. ```rust use std::collections::BTreeMap; let mut count: BTreeMap<&str, usize> = BTreeMap::new(); // count the number of occurrences of letters in the vec for x in ["a", "b", "a", "c", "a", "b"] { count.entry(x).and_modify(|curr| *curr += 1).or_insert(1); } assert_eq!(count["a"], 3); assert_eq!(count["b"], 2); assert_eq!(count["c"], 1); ``` -------------------------------- ### init_doc_and_resources function Source: https://docs.rs/printpdf/latest/src/printpdf/serialize.rs.html Initializes a new lopdf document and populates the global XObject dictionary from the provided PdfDocument. ```rust pub fn init_doc_and_resources( pdf: &PdfDocument, opts: &PdfSaveOptions, ) -> (lopdf::Document, lopdf::Dictionary) { let mut doc = lopdf::Document::with_version("1.3"); doc.reference_table.cross_reference_type = lopdf::xref::XrefType::CrossReferenceTable; let mut global_xobject_dict = LoDictionary::new(); for (k, v) in pdf.resources.xobjects.map.iter() { global_xobject_dict.set( k.0.clone(), crate::xobject::add_xobject_to_document(v, &mut doc, opts.image_optimization.as_ref()), ); } (doc, global_xobject_dict) } ``` -------------------------------- ### LoadedFonts::get_by_hash Source: https://docs.rs/printpdf/latest/printpdf/text_shaping/struct.LoadedFonts.html Gets a font by its hash. ```APIDOC ## LoadedFonts::get_by_hash ### Description Gets a font by its hash. ### Method get_by_hash ### Signature pub fn get_by_hash(&self, hash: u64) -> Option<&T> ### Parameters - hash (u64) - Required - The hash of the font. ### Returns - Option<&T> - The font if found, otherwise None. ``` -------------------------------- ### LoadedFonts::get Source: https://docs.rs/printpdf/latest/printpdf/text_shaping/struct.LoadedFonts.html Gets a font by its FontId. ```APIDOC ## LoadedFonts::get ### Description Gets a font by its FontId. ### Method get ### Signature pub fn get(&self, font_id: &FontId) -> Option<&T> ### Parameters - font_id (&FontId) - Required - The FontId to look up. ### Returns - Option<&T> - The font if found, otherwise None. ``` -------------------------------- ### Shape text and convert to PDF operations Source: https://docs.rs/printpdf/latest/printpdf/shape/index.html Demonstrates the process of loading a font, configuring text shaping options, shaping the text, and converting the resulting layout into PDF operations. ```rust use printpdf::*; // Load a font let font_bytes = std::fs::read("my_font.ttf")?; let font = ParsedFont::from_bytes(&font_bytes, 0)?; // Shape text let options = TextShapingOptions::new(Pt(12.0)) .with_max_width(Pt(200.0)) .with_align(TextAlign::Left); let layout = shape_text("Hello, World!", &font, &options)?; // Convert to PDF operations let ops = layout_to_ops(&layout, page_height, &font_id, Color::black()); ``` -------------------------------- ### Create Image Stream with SMask Source: https://docs.rs/printpdf/latest/src/printpdf/image_types.rs.html Configures an image dictionary with width, height, and color space, then creates an SMask stream for transparency. ```rust ("Width", Integer(im.width as i64)), ("Height", Integer(im.height as i64)), ("BitsPerComponent", Integer(8)), ("ColorSpace", Name("DeviceGray".into())), ("Filter", Name("FlateDecode".into())), ]); let smask_id = doc.add_object(lopdf::Stream::new(smask_dict, flate(&alpha))); dict.set("SMask", Reference(smask_id)); } lopdf::Stream::new(dict, flate(&color)).with_compression(false) } ``` -------------------------------- ### num_glyphs Source: https://docs.rs/printpdf/latest/printpdf/font/struct.ParsedFont.html Gets the number of glyphs in this font. ```APIDOC ## num_glyphs ### Description Gets the number of glyphs in this font. ### Method pub fn num_glyphs(&self) -> u16 ### Returns - u16 - The number of glyphs. ``` -------------------------------- ### get_font_metrics Source: https://docs.rs/printpdf/latest/printpdf/font/struct.AzulParsedFont.html Gets layout-specific font metrics. ```APIDOC ## get_font_metrics ### Description Get layout-specific font metrics. ### Method pub fn get_font_metrics(&self) -> LayoutFontMetrics ### Parameters None ### Returns - **LayoutFontMetrics** - The layout font metrics. ``` -------------------------------- ### Initial PDF Parsing Logic Source: https://docs.rs/printpdf/latest/src/printpdf/deserialize.rs.html Initializes the PDF document loading process by extracting the catalog and pages tree from the trailer. ```rust fn parse_pdf_from_bytes_start( bytes: &[u8], _opts: &PdfParseOptions, warnings: &mut Vec, ) -> Result { // Load the PDF document using lopdf. let doc = LopdfDocument::load_mem(bytes).map_err(|e| format!("Failed to load PDF: {}", e))?; let mut objs_to_search_for_resources = Vec::new(); // Get the catalog from the trailer. let root_obj = doc .trailer .get(b"Root") .map_err(|_| "Missing Root in trailer".to_string())?; objs_to_search_for_resources.push((root_obj.clone(), None)); let root_ref = match root_obj { Object::Reference(r) => *r, _ => return Err("Invalid Root reference".to_string()), }; let catalog_obj = doc .get_object(root_ref) .map_err(|e| format!("Failed to get catalog: {}", e))?; objs_to_search_for_resources.push((catalog_obj.clone(), None)); let catalog = catalog_obj .as_dict() .map_err(|e| format!("Catalog is not a dictionary: {}", e))?; // Check if catalog has a Resources dictionary and include it if let Ok(resources) = catalog.get(b"Resources") { objs_to_search_for_resources.push((resources.clone(), None)); } // Get the Pages tree from the catalog. let pages_obj = catalog .get(b"Pages") .map_err(|e| format!("Missing Pages key in catalog: {}", e))?; objs_to_search_for_resources.push((pages_obj.clone(), None)); // The Pages entry should be an indirect reference, but tolerate an inline // dictionary too (seen in the wild). let pages_dict = match pages_obj { Object::Reference(r) => doc .get_object(*r) .map_err(|e| format!("Failed to get Pages object: {}", e))? ``` -------------------------------- ### LoadedFonts::len Source: https://docs.rs/printpdf/latest/printpdf/text_shaping/struct.LoadedFonts.html Gets the number of loaded fonts. ```APIDOC ## LoadedFonts::len ### Description Gets the number of loaded fonts. ### Method len ### Signature pub fn len(&self) -> usize ### Parameters None ### Returns - usize - The number of loaded fonts. ``` -------------------------------- ### LoadedFonts::get_font_id_by_hash Source: https://docs.rs/printpdf/latest/printpdf/text_shaping/struct.LoadedFonts.html Gets the FontId for a given hash. ```APIDOC ## LoadedFonts::get_font_id_by_hash ### Description Gets the FontId for a given hash. ### Method get_font_id_by_hash ### Signature pub fn get_font_id_by_hash(&self, hash: u64) -> Option<&FontId> ### Parameters - hash (u64) - Required - The hash of the font. ### Returns - Option<&FontId> - The FontId if found, otherwise None. ``` -------------------------------- ### get_key_value Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Returns the key-value pair corresponding to the supplied key. This is useful for key types where non-identical keys can be considered equal, for getting the &K stored key value from a borrowed &Q lookup key, or for getting a reference to a key with the same lifetime as the collection. ```APIDOC ## get_key_value ### Description Returns the key-value pair corresponding to the supplied key. This is useful for key types where non-identical keys can be considered equal, for getting the &K stored key value from a borrowed &Q lookup key, or for getting a reference to a key with the same lifetime as the collection. ### Method pub fn get_key_value(&self, k: &Q) -> Option<(&K, &V)> ### Parameters - **k** (&Q) - Required - The key to look up. Q must satisfy K: Borrow + Ord and Q: Ord + ?Sized. ### Return Value - Option<(&K, &V)> - Some tuple of references to the key and value if the key exists, otherwise None. ### Example ```rust use std::cmp::Ordering; use std::collections::BTreeMap; #[derive(Clone, Copy, Debug)] struct S { id: u32, name: &'static str, // ignored by equality and ordering operations } impl PartialEq for S { fn eq(&self, other: &S) -> bool { self.id == other.id } } impl Eq for S {} impl PartialOrd for S { fn partial_cmp(&self, other: &S) -> Option { self.id.partial_cmp(&other.id) } } impl Ord for S { fn cmp(&self, other: &S) -> Ordering { self.id.cmp(&other.id) } } let j_a = S { id: 1, name: "Jessica" }; let j_b = S { id: 1, name: "Jess" }; let p = S { id: 2, name: "Paul" }; assert_eq!(j_a, j_b); let mut map = BTreeMap::new(); map.insert(j_a, "Paris"); assert_eq!(map.get_key_value(&j_a), Some((&j_a, &"Paris"))); assert_eq!(map.get_key_value(&j_b), Some((&j_a, &"Paris"))); // the notable case assert_eq!(map.get_key_value(&p), None); ``` ``` -------------------------------- ### BTreeMap::is_empty Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Checks if the map contains no elements. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert!(a.is_empty()); a.insert(1, "a"); assert!(!a.is_empty()); ``` -------------------------------- ### RawImage Creation and Async Decoding Source: https://docs.rs/printpdf/latest/src/printpdf/image.rs.html Methods for creating an empty RawImage and the signature for async image decoding. ```rust impl RawImage { /// Creates an empty `RawImage` pub fn empty(width: usize, height: usize, format: crate::RawImageFormat) -> Self { Self { width, height, data_format: format, pixels: RawImageData::empty(format), tag: Vec::new(), } } /// Same as decode_from_bytes, but uses async for browser-native image decoding pub async fn decode_from_bytes_async( bytes: &[u8], warnings: &mut Vec, ) -> Result { // Try browser-native decoding first for better format support. // p1/p2 excluded (like src/date.rs): wasi is target_family = "wasm" too, and // compiling the browser path there puts `window`/canvas imports into a binary // no wasi runtime can instantiate. The portable fallback below covers it. #[cfg(all( feature = "js-sys", target_arch = "wasm32", not(any(target_env = "p1", target_env = "p2")) ))] { ``` -------------------------------- ### BTreeMap::len Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Returns the number of elements in the map. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); assert_eq!(a.len(), 0); a.insert(1, "a"); assert_eq!(a.len(), 1); ``` -------------------------------- ### init_doc_and_resources Source: https://docs.rs/printpdf/latest/printpdf/serialize/fn.init_doc_and_resources.html Initializes a PDF document and its resources for serialization. This function is part of the printpdf crate's serialization module and is used internally to prepare the document structure. ```APIDOC ## Function init_doc_and_resources ### Description Initializes a PDF document and its resources for serialization. This function is part of the printpdf crate's serialization module and is used internally to prepare the document structure. ### Signature ```rust pub fn init_doc_and_resources( pdf: &PdfDocument, opts: &PdfSaveOptions, ) -> (Document, Dictionary) ``` ### Parameters - **pdf** (&PdfDocument) - Required - A reference to the PDF document to initialize. - **opts** (&PdfSaveOptions) - Required - A reference to the PDF save options. ### Returns - **(Document, Dictionary)** - A tuple containing the initialized Document and Dictionary. ``` -------------------------------- ### BTreeMap::iter_mut Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Iterates over the entries of the map mutably. ```rust use std::collections::BTreeMap; let mut map = BTreeMap::from([ ("a", 1), ("b", 2), ("c", 3), ]); // add 10 to the value if the key isn't "a" for (key, value) in map.iter_mut() { if key != &"a" { *value += 10; } } ``` -------------------------------- ### Create a BTreeMap with new_in Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Demonstrates creating a new empty BTreeMap using a specific allocator. ```rust use std::collections::BTreeMap; use std::alloc::Global; let map: BTreeMap = BTreeMap::new_in(Global); ``` -------------------------------- ### html_to_document and html_to_document_async functions Source: https://docs.rs/printpdf/latest/src/printpdf/wasm/structs.rs.html Functions to convert HTML to a PDF document, requiring the 'html' feature flag. ```rust #[cfg(feature = "html")] pub fn html_to_document(input: HtmlToDocumentInput) -> Result { let mut warnings = Vec::new(); // Fonts registered via `Pdf_RegisterFonts` participate in every render. let fonts = fonts_with_registered(&input.fonts); let pdf = PdfDocument::from_html( &input.html, &input.images, &fonts, &input.options, &mut warnings, )?; Ok(HtmlToDocumentOutput { doc: pdf, warnings }) } #[cfg(not(feature = "html"))] const ERR: &str = "Pdf_HtmlToDocument failed: feature --html not enabled for printpdf crate"; #[cfg(not(feature = "html"))] pub fn html_to_document(_input: HtmlToDocumentInput) -> Result { Err(ERR.to_string()) } #[cfg(feature = "html")] pub async fn html_to_document_async( input: HtmlToDocumentInput, ) -> Result { let mut warnings = Vec::new(); // Fonts registered via `Pdf_RegisterFonts` participate in every render. let fonts = fonts_with_registered(&input.fonts); let pdf = PdfDocument::from_html( &input.html, &input.images, &fonts, &input.options, &mut warnings, )?; Ok(HtmlToDocumentOutput { doc: pdf, warnings }) } #[cfg(not(feature = "html"))] pub async fn html_to_document_async( _input: HtmlToDocumentInput, ) -> Result { Err(ERR.to_string()) } ``` -------------------------------- ### SpotColor::new Source: https://docs.rs/printpdf/latest/printpdf/color/struct.SpotColor.html Creates a new SpotColor instance with the given CMYK components. Note that values must be in the range 0.0 to 1.0, not 0 to 255. ```APIDOC ## SpotColor::new ### Description Creates a new SpotColor instance with the given CMYK components. The values must be in the range 0.0 to 1.0, not 0 to 255. ### Method pub fn new(c: f32, m: f32, y: f32, k: f32) -> Self ### Parameters - **c** (f32) - Required - Cyan component - **m** (f32) - Required - Magenta component - **y** (f32) - Required - Yellow component - **k** (f32) - Required - Black component ### Return Value Returns a new SpotColor instance. ### Example ```rust let color = SpotColor::new(0.1, 0.2, 0.3, 0.4); ``` ``` -------------------------------- ### BTreeMap::values_mut Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Retrieves a mutable iterator over the values of the map. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, String::from("hello")); a.insert(2, String::from("goodbye")); for value in a.values_mut() { value.push_str("!"); } let values: Vec = a.values().cloned().collect(); assert_eq!(values, [String::from("hello!"), String::from("goodbye!")]); ``` -------------------------------- ### CurTransMat Implementation Methods Source: https://docs.rs/printpdf/latest/src/printpdf/matrix.rs.html Provides methods for converting the matrix to a CSS value string and performing matrix multiplication. ```rust 37impl PartialEq for CurTransMat { 38 fn eq(&self, other: &Self) -> bool { 39 self.as_array() == other.as_array() 40 } 41} 42 43impl CurTransMat { 44 pub fn as_css_val(&self) -> String { 45 let m = self.as_array(); 46 format!( 47 "matrix({} {} {} {} {} {})", 48 m[0], m[1], m[2], m[3], m[4], m[5] 49 ) 50 } 51 52 pub fn combine_matrix(a: [f32; 6], b: [f32; 6]) -> [f32; 6] { 53 let a = [ 54 [a[0], a[1], 0.0, 0.0], 55 [a[2], a[3], 0.0, 0.0], 56 [0.0, 0.0, 1.0, 0.0], 57 [a[4], a[5], 0.0, 1.0], 58 ]; 59 60 let b = [ 61 [b[0], b[1], 0.0, 0.0], 62 [b[2], b[3], 0.0, 0.0], 63 [0.0, 0.0, 1.0, 0.0], 64 [b[4], b[5], 0.0, 1.0], 65 ]; 66 67 let result = [ 68 [ 69 mul_add( 70 a[0][0], 71 b[0][0], 72 mul_add( 73 a[0][1], 74 b[1][0], 75 mul_add(a[0][2], b[2][0], a[0][3] * b[3][0]), 76 ), 77 ), 78 mul_add( 79 a[0][0], 80 b[0][1], 81 mul_add( 82 a[0][1], 83 b[1][1], 84 mul_add(a[0][2], b[2][1], a[0][3] * b[3][1]), 85 ), 86 ), 87 mul_add( 88 a[0][0], 89 b[0][2], 90 mul_add( 91 a[0][1], 92 b[1][2], 93 mul_add(a[0][2], b[2][2], a[0][3] * b[3][2]), 94 ), 95 ), 96 mul_add( 97 a[0][0], 98 b[0][3], 99 mul_add( 100 a[0][1], 101 b[1][3], 102 mul_add(a[0][2], b[2][3], a[0][3] * b[3][3]), 103 ), 104 ), 105 ], 106 [ 107 mul_add( 108 a[1][0], 109 b[0][0], 110 mul_add( 111 a[1][1], 112 b[1][0], 113 mul_add(a[1][2], b[2][0], a[1][3] * b[3][0]), 114 ), 115 ), 116 mul_add( 117 a[1][0], 118 b[0][1], 119 mul_add( 120 a[1][1], 121 b[1][1], 122 mul_add(a[1][2], b[2][1], a[1][3] * b[3][1]), 123 ), 124 ), 125 mul_add( 126 a[1][0], 127 b[0][2], 128 mul_add( 129 a[1][1], 130 b[1][2], 131 mul_add(a[1][2], b[2][2], a[1][3] * b[3][2]), 132 ), 133 ), 134 mul_add( 135 a[1][0], 136 b[0][3], 137 mul_add( 138 a[1][1], 139 b[1][3], 140 mul_add(a[1][2], b[2][3], a[1][3] * b[3][3]), 141 ), 142 ), ``` -------------------------------- ### get_space_width Source: https://docs.rs/printpdf/latest/printpdf/font/struct.ParsedFont.html Gets the width of the space character in unscaled font units. ```APIDOC ## get_space_width ### Description Get the width of the space character (unscaled font units). ### Method get_space_width ### Signature pub fn get_space_width(&self) -> Option ### Returns - **Option** - The width of the space character, or None if not available. ``` -------------------------------- ### ColorU::new Source: https://docs.rs/printpdf/latest/printpdf/text_shaping/struct.ColorU.html Alias for rgba - kept for internal compatibility, not exposed in FFI. ```APIDOC ## ColorU::new ### Description Alias for `rgba` - kept for internal compatibility, not exposed in FFI. ### Method pub const fn new(r: u8, g: u8, b: u8, a: u8) -> ColorU ### Parameters - **r** (u8) - Required - Red channel value (0-255) - **g** (u8) - Required - Green channel value (0-255) - **b** (u8) - Required - Blue channel value (0-255) - **a** (u8) - Required - Alpha channel value (0-255) ### Returns - **ColorU** - A new ColorU instance with the specified RGBA values. ``` -------------------------------- ### ShadingId::new Source: https://docs.rs/printpdf/latest/printpdf/shading/struct.ShadingId.html Creates a new ShadingId instance. This is the primary constructor for the struct. ```APIDOC ## ShadingId::new ### Description Creates a new ShadingId instance. ### Method new ### Signature pub fn new() -> Self ### Parameters None ### Returns - **Self** - A new ShadingId instance. ### Example ```rust let id = ShadingId::new(); ``` ``` -------------------------------- ### get_glyph_width_internal Source: https://docs.rs/printpdf/latest/printpdf/font/struct.ParsedFont.html Gets the width of a glyph in font units (internal, unscaled). ```APIDOC ## get_glyph_width_internal ### Description Get the width of a glyph in font units (internal, unscaled). ### Method get_glyph_width_internal ### Signature pub fn get_glyph_width_internal(&self, glyph_index: u16) -> Option ### Parameters - **glyph_index** (u16) - Required - The glyph index. ### Returns - **Option** - The glyph width in font units, or None if not available. ``` -------------------------------- ### get_space_width Source: https://docs.rs/printpdf/latest/printpdf/font/struct.AzulParsedFont.html Gets the width of the space character in unscaled font units. ```APIDOC ## get_space_width ### Description Get the width of the space character (unscaled font units). ### Method pub const fn get_space_width(&self) -> Option ### Parameters None ### Returns - **Option** - The space character width, or None if not available. ``` -------------------------------- ### TextItem From implementations Source: https://docs.rs/printpdf/latest/src/printpdf/text.rs.html Conversion implementations that allow creating TextItem variants from String, &str, f32, f64, i32, i64, and u8 values. ```APIDOC ## TextItem From implementations ### Description Provides `From` conversions to create `TextItem` variants from various primitive types. `String` and `&str` produce `TextItem::Text`, while numeric types produce `TextItem::Offset` (converted to f32). ### Implementations - `impl From for TextItem` - Creates `TextItem::Text(s)`. - `impl From<&str> for TextItem` - Creates `TextItem::Text(s.to_string())`. - `impl From for TextItem` - Creates `TextItem::Offset(n)`. - `impl From for TextItem` - Creates `TextItem::Offset(n as f32)`. - `impl From for TextItem` - Creates `TextItem::Offset(n as f32)`. - `impl From for TextItem` - Creates `TextItem::Offset(n as f32)`. - `impl From for TextItem` - Creates `TextItem::Offset(n as f32)`. ### Example ```rust let text = TextItem::from("hello"); let offset = TextItem::from(1.5f32); ``` ``` -------------------------------- ### get_glyph_width_internal Source: https://docs.rs/printpdf/latest/printpdf/font/struct.AzulParsedFont.html Gets the width of a glyph in font units (internal, unscaled). ```APIDOC ## get_glyph_width_internal ### Description Get the width of a glyph in font units (internal, unscaled). ### Method pub fn get_glyph_width_internal(&self, glyph_index: u16) -> Option ### Parameters - **glyph_index** (u16) - Required - The glyph index. ### Returns - **Option** - The glyph width in font units, or None if not available. ``` -------------------------------- ### PathBuilder::build method Source: https://docs.rs/printpdf/latest/src/printpdf/deserialize.rs.html Constructs a PdfPath from the current builder state, including subpaths and paint modes. ```rust #[cfg(test)] pub fn is_empty(&self) -> bool { self.current_subpath.is_empty() && self.subpaths.is_empty() } pub fn build(&self, paint_mode: PaintMode, winding_order: WindingOrder) -> PdfPath { let mut all_subpaths = self.subpaths.clone(); if !self.current_subpath.is_empty() { all_subpaths.push(self.current_subpath.clone()); } let subpaths = all_subpaths .into_iter() .map(|ops| { let is_closed = ops.iter().any(|op| matches!(op, PathOperation::ClosePath)); PdfSubPath { operations: ops, is_closed, } }) .collect(); PdfPath { subpaths, paint_mode, winding_order, } } } ``` -------------------------------- ### ImageOptimizationOptions and default values Source: https://docs.rs/printpdf/latest/src/printpdf/image_types.rs.html Defines the configuration for image optimization in PDF, including quality, size limits, and compression settings. Includes default implementations for these options. ```rust 1// Image-related types that are always available, regardless of the 'images' feature 2use serde_derive::{Deserialize, Serialize}; 3 4/// Options for optimizing images in PDF 5#[derive(Debug, Clone, Serialize, PartialOrd, PartialEq, Deserialize)] 6#[serde(rename_all = "camelCase")] 7pub struct ImageOptimizationOptions { 8 /// Quality level for lossy compression (0.0-1.0) 9 #[serde(default = "default_quality", skip_serializing_if = "Option::is_none")] 10 pub quality: Option, 11 /// Maximum image size (e.g. "300kb") 12 #[serde( 13 default = "default_max_img_size", 14 skip_serializing_if = "Option::is_none" 15 )] 16 pub max_image_size: Option, 17 /// Whether to apply dithering to greyscale images 18 #[serde( 19 default = "default_dither_greyscale", 20 skip_serializing_if = "Option::is_none" 21 )] 22 pub dither_greyscale: Option, 23 /// Automatically convert the image to greyscale (only done if auto_optimize = true) 24 #[serde( 25 default = "default_convert_to_greyscale", 26 skip_serializing_if = "Option::is_none" 27 )] 28 pub convert_to_greyscale: Option, 29 /// Auto-optimize images (remove alpha if not needed, detect greyscale) 30 #[serde( 31 default = "default_auto_optimize", 32 skip_serializing_if = "Option::is_none" 33 )] 34 pub auto_optimize: Option, 35 /// Preferred compression format 36 #[serde(default = "default_format", skip_serializing_if = "Option::is_none")] 37 pub format: Option, 38} 39 40const fn default_quality() -> Option { 41 Some(0.85) 42} 43 44fn default_max_img_size() -> Option { 45 Some("2MB".to_string()) 46} 47 48const fn default_convert_to_greyscale() -> Option { 49 Some(false) 50} 51 52const fn default_dither_greyscale() -> Option { 53 None 54} 55 56const fn default_auto_optimize() -> Option { 57 Some(true) 58} 59 60const fn default_format() -> Option { 61 Some(ImageCompression::Auto) 62} 63 64impl Default for ImageOptimizationOptions { 65 fn default() -> Self { 66 ImageOptimizationOptions { 67 quality: default_quality(), 68 convert_to_greyscale: default_convert_to_greyscale(), 69 max_image_size: default_max_img_size(), 70 dither_greyscale: default_dither_greyscale(), 71 auto_optimize: default_auto_optimize(), 72 format: default_format(), 73 } 74 } 75} ``` -------------------------------- ### BTreeMap::range example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Constructs a double-ended iterator over a sub-range of elements in the map. ```rust use std::collections::BTreeMap; use std::ops::Bound::Included; let mut map = BTreeMap::new(); map.insert(3, "a"); map.insert(5, "b"); map.insert(8, "c"); for (&key, &value) in map.range((Included(&4), Included(&8))) { println!("{key}: {value}"); } assert_eq!(Some((&5, &"b")), map.range(4..).next()); ``` -------------------------------- ### BlendMode::screen() Source: https://docs.rs/printpdf/latest/src/printpdf/graphics.rs.html Creates a BlendMode instance representing the Screen blend mode. ```APIDOC ## BlendMode::screen() ### Description Creates a BlendMode instance representing the Screen blend mode. ### Signature ```rust pub fn screen() -> BlendMode ``` ### Returns - **BlendMode** - A BlendMode value representing the Screen blend mode. ``` -------------------------------- ### BlendMode::soft_light() Source: https://docs.rs/printpdf/latest/src/printpdf/graphics.rs.html Creates a BlendMode instance representing the SoftLight blend mode. ```APIDOC ## BlendMode::soft_light() ### Description Creates a BlendMode instance representing the SoftLight blend mode. ### Signature ```rust pub fn soft_light() -> BlendMode ``` ### Returns - **BlendMode** - A BlendMode value representing the SoftLight blend mode. ``` -------------------------------- ### BlendMode Constructors Source: https://docs.rs/printpdf/latest/printpdf/graphics/enum.BlendMode.html Static methods to create BlendMode instances for each supported blend mode. ```APIDOC ## BlendMode Constructors ### Description These static methods return a BlendMode instance for the corresponding blend mode. ### Methods - **normal()** -> BlendMode - Creates a normal blend mode. - **multiply()** -> BlendMode - Creates a multiply blend mode. - **screen()** -> BlendMode - Creates a screen blend mode. - **overlay()** -> BlendMode - Creates an overlay blend mode. - **darken()** -> BlendMode - Creates a darken blend mode. - **lighten()** -> BlendMode - Creates a lighten blend mode. - **color_dodge()** -> BlendMode - Creates a color dodge blend mode. - **color_burn()** -> BlendMode - Creates a color burn blend mode. - **hard_light()** -> BlendMode - Creates a hard light blend mode. - **soft_light()** -> BlendMode - Creates a soft light blend mode. - **difference()** -> BlendMode - Creates a difference blend mode. - **exclusion()** -> BlendMode - Creates an exclusion blend mode. - **hue()** -> BlendMode - Creates a hue blend mode. - **saturation()** -> BlendMode - Creates a saturation blend mode. - **color()** -> BlendMode - Creates a color blend mode. - **luminosity()** -> BlendMode - Creates a luminosity blend mode. ``` -------------------------------- ### BTreeMap::values Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Retrieves an iterator over the values of the map in order by key. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(1, "hello"); a.insert(2, "goodbye"); let values: Vec<&str> = a.values().cloned().collect(); assert_eq!(values, ["hello", "goodbye"]); ``` -------------------------------- ### BlendMode::overlay() Source: https://docs.rs/printpdf/latest/src/printpdf/graphics.rs.html Creates a BlendMode instance representing the Overlay blend mode. ```APIDOC ## BlendMode::overlay() ### Description Creates a BlendMode instance representing the Overlay blend mode. ### Signature ```rust pub fn overlay() -> BlendMode ``` ### Returns - **BlendMode** - A BlendMode value representing the Overlay blend mode. ``` -------------------------------- ### BTreeMap::keys Example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Retrieves an iterator over the keys of the map in sorted order. ```rust use std::collections::BTreeMap; let mut a = BTreeMap::new(); a.insert(2, "b"); a.insert(1, "a"); let keys: Vec<_> = a.keys().cloned().collect(); assert_eq!(keys, [1, 2]); ``` -------------------------------- ### BTreeMap::range_mut example Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Constructs a mutable double-ended iterator over a sub-range of elements in the map. ```rust use std::collections::BTreeMap; let mut map: BTreeMap<&str, i32> = [("Alice", 0), ("Bob", 0), ("Carol", 0), ("Cheryl", 0)].into(); for (_, balance) in map.range_mut("B".."Cheryl") { *balance += 100; } for (name, balance) in &map { println!("{name} => {balance}"); } ``` -------------------------------- ### PdfToSvgOptions::web() Source: https://docs.rs/printpdf/latest/printpdf/struct.PdfToSvgOptions.html Constructs a new PdfToSvgOptions instance with default settings optimized for web rendering. This is the primary way to create options for SVG conversion. ```APIDOC ## PdfToSvgOptions::web() ### Description Creates a new PdfToSvgOptions instance with default settings. This is the recommended way to obtain options for SVG rendering, particularly in web contexts. ### Method Associated function (constructor) ### Signature pub fn web() -> Self ### Parameters None ### Returns - **PdfToSvgOptions** - A new instance with default configuration. ### Example ```rust let options = PdfToSvgOptions::web(); ``` ``` -------------------------------- ### OutputImageFormat Source: https://docs.rs/printpdf/latest/src/printpdf/image_types.rs.html Enum representing output image formats with a method to get the MIME type. ```APIDOC ## OutputImageFormat ### Description Enum representing output image formats. Provides a method to retrieve the MIME type for each format. ### Variants - **Png** - PNG (lossless) - **Jpeg** - JPEG (lossy) - **Webp** - WebP (lossy or lossless) - **Avif** - AVIF (lossy or lossless) - **Gif** - GIF (lossless, limited colors) - **Bmp** - BMP (lossless, uncompressed) - **Tiff** - TIFF (lossless or lossy) - **Tga** - TGA (lossless) - **Pnm** - PNM (lossless) ### Methods #### mime_type Returns the MIME type string for the format. - **Returns** (&'static str) - The MIME type string. Example mappings: - Png -> "image/png" - Jpeg -> "image/jpeg" - Webp -> "image/webp" - Avif -> "image/avif" - Gif -> "image/gif" - Bmp -> "image/bmp" - Tiff -> "image/tiff" - Tga -> "image/x-tga" - Pnm -> "image/x-portable-anymap" ``` -------------------------------- ### Unit Implementation Application Source: https://docs.rs/printpdf/latest/src/printpdf/units.rs.html Applying arithmetic macros to Mm, Pt, and Px types. ```rust impl_add_self!(Mm); impl_add_self!(Pt); impl_add_self!(Px); impl_add_assign_self!(Mm); impl_add_assign_self!(Pt); impl_add_assign_self!(Px); impl_sub_assign_self!(Mm); impl_sub_assign_self!(Pt); impl_sub_assign_self!(Px); impl_sub_self!(Mm); impl_sub_self!(Pt); impl_sub_self!(Px); impl_mul_f32!(Mm); impl_mul_f32!(Pt); impl_mul_assign_f32!(Mm); impl_mul_assign_f32!(Pt); impl_div!(Mm); impl_div!(Pt); impl_div_assign_f32!(Mm); impl_div_assign_f32!(Pt); ``` -------------------------------- ### Registering fonts with Pdf_RegisterFontsSync Source: https://docs.rs/printpdf/latest/printpdf/wasm/api/fn.Pdf_RegisterFontsSync.html Example of calling Pdf_RegisterFontsSync with a JSON-encoded object containing font data. ```javascript let r = JSON.parse(Pdf_RegisterFontsSync(JSON.stringify({ fonts: { "Helvetica.ttf": HELVETICA_B64 }, }))); // r == { status: 0, data: { registered: 1, total: 1 } } ``` -------------------------------- ### BlendMode::hard_light() Source: https://docs.rs/printpdf/latest/src/printpdf/graphics.rs.html Creates a BlendMode instance representing the HardLight blend mode. ```APIDOC ## BlendMode::hard_light() ### Description Creates a BlendMode instance representing the HardLight blend mode. ### Signature ```rust pub fn hard_light() -> BlendMode ``` ### Returns - **BlendMode** - A BlendMode value representing the HardLight blend mode. ``` -------------------------------- ### BTreeMap::new_in Source: https://docs.rs/printpdf/latest/printpdf/html/bridge/type.ResolvedImages.html Makes a new empty BTreeMap with a reasonable choice for B. This is a nightly-only experimental API. ```APIDOC ## BTreeMap::new_in ### Description Makes a new empty BTreeMap with a reasonable choice for B. This is a nightly-only experimental API. ### Signature pub const fn new_in(alloc: A) -> BTreeMap ### Parameters - alloc (A) - Required - The allocator to use. ### Examples ```rust use std::collections::BTreeMap; use std::alloc::Global; let map: BTreeMap = BTreeMap::new_in(Global); ``` ``` -------------------------------- ### PathBuilder::close_path Source: https://docs.rs/printpdf/latest/printpdf/deserialize/struct.PathBuilder.html Closes the current path by adding a line segment back to the starting point. ```APIDOC ## PathBuilder::close_path ### Description Closes the current path by adding a line segment back to the starting point. ### Method pub fn close_path(&mut self) ### Parameters None. ### Returns No return value. ``` -------------------------------- ### DateTime Implementation and Epoch Source: https://docs.rs/printpdf/latest/src/printpdf/date.rs.html Methods for creating new DateTime instances and the epoch constant. ```rust impl DateTime { pub fn new_in_offset(date: Date, time: Time, offset: Offset) -> Self { Self { date, time, offset } } pub const fn epoch() -> Self { Self { date: Date { year: 1970, month: 1, day: 1, }, time: Time { hour: 0, minute: 0, second: 0, millisecond: 0, }, offset: Offset { hours: 0, minutes: 0, seconds: 0, milliseconds: 0, }, } } ```