### Custom Text Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Example of creating a Text object with custom content, size, and position. ```APIDOC ## Custom Text ### Description Creates a `Text` object with custom content, expanded content, size, and position. ### Usage ```rust use crate::types::hierarchy::content::text::Identifier; use crate::types::primitives::rectangle::Position; let txt = Text::builder() .with_content("This is") .with_expanded_content(" a custom text content.") .with_size(14) .at(Position::from_mm(0.0, 0.0)) .build() .to_bytes(Identifier::from_static(b"CustomFnt")) .unwrap(); let output = String::from_utf8_lossy(&txt); // insta::assert_snapshot!(output, @r"...expected output..."); ``` ``` -------------------------------- ### Default Text Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Example of creating a default Text object with a specified position. ```APIDOC ## Default Text ### Description Creates a default `Text` object at a specific position. ### Usage ```rust use crate::types::hierarchy::content::text::Identifier; use crate::types::primitives::rectangle::Position; let txt = Text::builder() .at(Position::from_mm(0.0, 0.0)) .build() .to_bytes(Identifier::from_static(b"BiHDef")) .unwrap(); let output = String::from_utf8_lossy(&txt); // insta::assert_snapshot!(output, @r"...expected output..."); ``` ``` -------------------------------- ### Subscript Text Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Example of creating a Text object with subscript formatting. ```APIDOC ## Subscript Text ### Description Creates a `Text` object with subscript formatting, applying transformations to position and size. ### Usage ```rust use crate::types::hierarchy::content::text::Identifier; use crate::types::primitives::rectangle::Position; let subscript_text = Text::builder() .with_content("This is") .with_expanded_content(" a superscript text content.") .with_size(14) .at(Position::from_mm(0.0, 0.0)) .subscript() .build() .to_bytes(Identifier::from_static(b"CustomFnt")) .unwrap(); let output = String::from_utf8_lossy(&subscript_text); // insta::assert_snapshot!(output, @r"...expected output..."); ``` ``` -------------------------------- ### Superscript Text Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Example of creating a Text object with superscript formatting. ```APIDOC ## Superscript Text ### Description Creates a `Text` object with superscript formatting, applying transformations to position and size. ### Usage ```rust use crate::types::hierarchy::content::text::Identifier; use crate::types::primitives::rectangle::Position; let superscript_text = Text::builder() .with_content("This is") .with_expanded_content(" a superscript text content.") .with_size(14) .at(Position::from_mm(0.0, 0.0)) .superscript() .build() .to_bytes(Identifier::from_static(b"CustomFnt")) .unwrap(); let output = String::from_utf8_lossy(&superscript_text); // insta::assert_snapshot!(output, @r"...expected output..."); ``` ``` -------------------------------- ### Stream Object Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/stream.rs.html Demonstrates the basic usage of the Stream object, including creation and writing to a buffer. ```APIDOC ## Stream Object Example ### `basic_stream()` test function This test function demonstrates the creation of a `Stream` with specific bytes and then writing it to a `Vec` buffer. It asserts that the output matches the expected PDF stream format. ```rust #[test] fn basic_stream() { let bytes = String::from("This is the content of a stream."); let stream = Stream::with_bytes(bytes); let mut writer = Vec::default(); stream.write(&mut writer).unwrap(); let output = String::from_utf8_lossy(&writer); insta::assert_snapshot!(output, @r"<< /Length 32 >>\nstream\nThis is the content of a stream.\nendstream\n"); } ``` ``` -------------------------------- ### Initialize and Configure PDF Document Builder Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/builder.rs.html Use the `Builder` struct to start constructing a PDF document. It can be configured with a default page size using `with_page_size`. ```rust use crate::{ Document, IdManager, types::hierarchy::catalog::Catalog, types::hierarchy::page_tree::PageTree, types::hierarchy::primitives::rectangle::Rectangle, }; pub struct Builder { pub(crate) id_manager: IdManager, pub(crate) page_size: Option, } impl Builder { pub fn with_page_size(self, media_box: impl Into) -> Self { Self { page_size: Some(media_box.into()), ..self } } pub fn build(mut self) -> Document { let catalog_id = self.id_manager.create_id(); let mut root_page_tree = PageTree::new(self.id_manager.create_id(), None); if let Some(rect) = self.page_size { root_page_tree.set_page_size(rect); } let catalog = Catalog::new(catalog_id, root_page_tree); Document { catalog, id_manager: self.id_manager, pages: Vec::default(), fonts: Vec::default(), } } } ``` -------------------------------- ### Write PDF Trailer Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Writes the PDF trailer, including the size, root object reference, ID, startxref, and EOF marker. This is a comprehensive PDF generation example. ```rust #[test] fn write_trailer() { let mut writer = Vec::new(); let mut pdf_writer = PdfWriter::new(&mut writer); let mut id_manager = IdManager::new(); pdf_writer.write_header().unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); pdf_writer.write_crt().unwrap(); pdf_writer.write_trailer(id_manager.create_id()).unwrap(); pdf_writer.write_eof().unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!( output, @r" %PDF-2.0 1 0 obj FirstLine SecondLine endobj 2 0 obj FirstLine SecondLine endobj 3 0 obj FirstLine SecondLine endobj 4 0 obj FirstLine SecondLine endobj xref 0 4 0000000010 00000 n 0000000047 00000 n 0000000084 00000 n 0000000121 00000 n trailer << /Size 4 /Root 5 0 R /ID [ ] >> startxref 158 %%EOF " ); } ``` -------------------------------- ### Convert Unit from Millimeters Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/unit.rs.html Demonstrates creating a Unit from millimeters and asserting its approximate value in default user space units. Note the use of floor due to potential floating-point inaccuracies. ```rust let unit = Unit::from_mm(1.0); assert_eq!(unit.into_user_unit().floor(), 2.0); ``` -------------------------------- ### Convert Unit to Default User Space Unit Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/unit.rs.html Demonstrates converting a Unit created from inches into its equivalent value in default user space units (1/72th of an inch). ```rust let unit = Unit::from_inch(1.0); assert_eq!(unit.into_user_unit(), 72.0); ``` -------------------------------- ### Convert Unit from Centimeters Example Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/unit.rs.html Demonstrates creating a Unit from centimeters and asserting its approximate value in default user space units. Note the use of floor due to potential floating-point inaccuracies. ```rust let unit = Unit::from_cm(1.0); assert_eq!(unit.into_user_unit().floor(), 28.0); ``` -------------------------------- ### Test Identifier Starting with Solidus Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/identifier.rs.html Checks if an identifier starting with a '/' character correctly results in a `StartsWithSolidus` error during parsing. ```rust #[test] fn starts_with_solidus() { let ident_res = Identifier::from_str("/InvalidIdent"); assert!(matches!( ident_res, Err(ParseIdentifierErr::StartsWithSolidus) )); } ``` -------------------------------- ### Get Image Transform Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/image/struct.Image.html Retrieves the width, height, and position of an Image. ```rust pub fn transform(&self) -> ImageTransform ``` -------------------------------- ### Get Page Object Reference Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page.rs.html Returns a clone of the `ObjId` representing this `Page` object. ```rust pub fn obj_ref(&self) -> ObjId { self.id.clone() } ``` -------------------------------- ### Create and Write a Basic PDF Page Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page.rs.html Demonstrates the creation of a `Page` object, setting its mediabox, and writing it to a byte vector. This is useful for generating simple PDF structures. ```rust let mut id_manager = IdManager::new(); let mut page = Page::new( id_manager.create_id(), id_manager.create_id(), id_manager.create_id(), ); page.set_mediabox(Rectangle::from_units(0.0, 0.0, 100.0, 100.0)); let mut writer = Vec::new(); page.write(&mut writer, &mut id_manager).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!( output, @r"1 0 obj << /Type /Page /Parent 3 0 R /Resources << >> /MediaBox [0 0 100 100]>> endobj " ); ``` -------------------------------- ### Using write_fmt Macro Source: https://docs.rs/pdfgen/0.3.1/pdfgen/macro.write_fmt.html Demonstrates how to use the write_fmt macro to write formatted content into a PDF writer. It shows the typical usage pattern and the expected output and return value. ```rust let mut writer = Vec::new(); let count = crate::write_fmt!(&mut writer, "{}", 42).unwrap(); assert_eq!(writer, b"42"); assert_eq!(count, 2); ``` -------------------------------- ### Create and Write Image to PDF Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/image.rs.html Demonstrates loading an image from a file, scaling and positioning it, and then writing it to a byte vector for PDF generation. Ensure the image file exists at the specified path. ```rust let img_file = std::fs::File::open(dbg!(path)).unwrap(); let mut id_mngr = IdManager::new(); let img = Image::from_reader(img_file) .scaled(Position::from_mm(100., 100.)) .at(Position::from_mm(10.0, 42.0)) .build(); let mut writer = Vec::default(); // NOTE: same function defined on Image directly, so call using qualified syntax img.write(&mut writer, &id_mngr.create_id()).unwrap(); let output = String::from_utf8_lossy(&writer); insta::assert_snapshot!(output); ``` -------------------------------- ### Create and Write a Basic Stream Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/stream.rs.html Demonstrates creating a Stream with initial bytes and writing it to a buffer. The output includes the stream dictionary with the 'Length' field and the stream content enclosed by 'stream' and 'endstream' markers. ```rust use std::io::{Error, Write}; use pdfgen_macros::const_identifiers; use crate::types::{constants, hierarchy::primitives::identifier::Identifier}; /// A stream object, like a string object, is a sequence of bytes that may be of unlimited length. /// Streams should be used to represent objects with potentially large amounts of data, such as /// images and page descriptions. #[derive(Debug, PartialEq, Eq, PartialOrd, Ord)] pub(crate) struct Stream { // NOTE: Stream dictionaries have more entries such as filter, decode parameters etc. For now, // we only need the required dictionary entry 'Length', implicitly available in `Vec` // implementation. // TODO: Implement full support for stream dictionary. /// Bytes contained in this `Stream` object. inner: Vec, } impl Stream { const START_STREAM: &[u8] = b"stream"; const END_STREAM: &[u8] = b"endstream"; const_identifiers!(LENGTH); /// Creates a new empty `Stream`, containing no bytes and with length 0. pub fn new() -> Self { Self { inner: Vec::default(), } } /// Creates a new `Stream` with given bytes as the stream's bytes. pub fn with_bytes(bytes: impl Into>) -> Self { Self { inner: bytes.into(), } } /// Writes (aditional) bytes into this `Stream`, updating it's length. pub fn push_bytes(&mut self, bytes: &[u8]) { self.inner .write_all(bytes) .expect("Writing to Vec should never fail."); } /// Writes an [`Identifier`] into this `Stream`, updating it's length. pub fn write_identifier>(&mut self, identifier: &Identifier) { identifier .write(&mut self.inner) .expect("Writing to Vec should never fail."); } /// Write the stream object into the given implementor of [`Write`] trait, with dictionary /// containing only the required `Length` field. #[inline(always)] pub fn write(&self, writer: &mut dyn Write) -> Result { self.write_with_dict(writer, |_| Ok(0)) } /// Write the stream object into the given implementor of [`Write`] trait, with function that /// writes dictionary fields additional to the `Length` field. pub fn write_with_dict(&self, writer: &mut dyn Write, write_dict: F) -> Result where F: FnOnce(&mut dyn Write) -> Result, { let written = pdfgen_macros::write_chain! { // BEGIN_DICTIONARY: writer.write(b"<< "), // write the additional dictionary fields write_dict(writer), // write the length Self::LENGTH.write(writer), crate::write_fmt!(&mut *writer, "{}", self.inner.len()), writer.write(b" >>"), writer.write(constants::NL_MARKER), // END_DICTIONARY // stream writer.write(Self::START_STREAM), writer.write(constants::NL_MARKER), writer.write_all(&self.inner).map(|_| self.inner.len()), writer.write(constants::NL_MARKER), writer.write(Self::END_STREAM), }; Ok(written) } /// Returns `true` if no bytes were written to this [`Stream`]. pub fn is_empty(&self) -> bool { self.inner.is_empty() } } #[cfg(test)] mod tests { use super::Stream; #[test] fn basic_stream() { let bytes = String::from("This is the content of a stream."); let stream = Stream::with_bytes(bytes); let mut writer = Vec::default(); stream.write(&mut writer).unwrap(); let output = String::from_utf8_lossy(&writer); insta::assert_snapshot!(output, @r"\ << /Length 32 >> stream This is the content of a stream. endstream "); } } ``` -------------------------------- ### Create Sample Document for Tests Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Helper function to create a `Document` instance with a single page and a font, commonly used in tests. ```rust fn create_sample_doc() -> Document { let mut document = Document::default(); document.create_page().set_mediabox(Rectangle::A4); document.create_font("Type1".into(), "Helvetica".into()); document } ``` -------------------------------- ### Get TypeId for Any Trait Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/struct.ContentStream.html Implements the Any trait for generic types, providing a method to get the TypeId of the instance. This is part of blanket implementations. ```rust fn type_id(&self) -> TypeId> ``` -------------------------------- ### Write Complete PDF with Objects Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Demonstrates writing a PDF header, multiple objects, a cross-reference table, and the EOF marker. ```rust #[test] fn write_crt() { let mut writer = Vec::new(); let mut pdf_writer = PdfWriter::new(&mut writer); let mut id_manager = IdManager::new(); pdf_writer.write_header().unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); let dummy = Dummy(id_manager.create_id()); pdf_writer.write_object(&dummy).unwrap(); pdf_writer.write_crt().unwrap(); pdf_writer.write_eof().unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!( output, @r" %PDF-2.0 1 0 obj FirstLine SecondLine endobj 2 0 obj FirstLine SecondLine endobj 3 0 obj FirstLine SecondLine endobj 4 0 obj FirstLine SecondLine endobj xref 0 4 0000000010 00000 n 0000000047 00000 n 0000000084 00000 n 0000000121 00000 n %%EOF " ); } ``` -------------------------------- ### Get ContentStream Object Reference Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/content_stream.rs.html Returns a reference to the ContentStream's ObjId. ```rust pub(crate) fn obj_ref(&self) -> &ObjId { &self.id } ``` -------------------------------- ### Get Page Object Reference Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Retrieves the object identifier for this Page object. ```rust pub fn obj_ref(&self) -> ObjId ``` -------------------------------- ### Initialize Empty Page Tree Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page_tree.rs.html Demonstrates the creation of a new PageTree with an empty list of kids, suitable for a PDF with no pages initially. ```rust fn page_tree_empty() { let mut id_manager = IdManager::new(); let mut page_tree = PageTree::new(id_manager.create_id(), None); let mut writer = Vec::new(); page_tree.write_content(&mut writer).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!(output, @r"<< /Type /Pages /Kids [] /Count 0 >> "); } ``` -------------------------------- ### Get Referenced Identifier Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/identifier.rs.html Returns a new Identifier referencing the same data but with a static lifetime. ```rust pub fn as_ref(&self) -> Identifier<&[u8]> { Identifier { inner: self.inner.as_ref(), } } ``` -------------------------------- ### Get Content Stream Reference Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page.rs.html Provides read-only access to the page's `ContentStream`. ```rust pub(crate) fn content_stream(&self) -> &ContentStream { &self.contents } ``` -------------------------------- ### PdfWriter::new Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Creates a new PdfWriter instance, initializing the internal state. ```APIDOC ## new ### Description Creates a new [`PdfWriter`] instance. ### Method `pub fn new(inner: W) -> Self` ### Parameters * `inner` (W): A type that implements the `Write` trait. ``` -------------------------------- ### PageTree Object Reference Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page_tree.rs.html Provides a method to get the object reference (ID) of the PageTree. ```rust pub fn obj_ref(&self) -> ObjId { self.id.clone() } ``` -------------------------------- ### Get Current Page Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Returns an optional mutable reference to the last page added to the document. ```rust pub fn current_page(&mut self) -> Option<&mut Page> { self.pages.last_mut() } ``` -------------------------------- ### Document Builder Method Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Returns a new `Builder` instance, which is used for constructing a `Document` with specific configurations. ```rust pub fn builder() -> Builder { Builder { id_manager: IdManager::new(), page_size: None, } } ``` -------------------------------- ### Default Document Implementation Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Provides a default implementation for `Document`, initializing a new document with a basic catalog and ID manager. ```rust impl Default for Document { fn default() -> Self { let mut id_manager = IdManager::new(); let catalog_id = id_manager.create_id(); let page_tree_root_id = id_manager.create_id(); let root_page_tree = PageTree::new(page_tree_root_id, None); let catalog = Catalog::new(catalog_id, root_page_tree); Self { catalog, id_manager, pages: Vec::new(), fonts: Vec::new(), } } } ``` -------------------------------- ### Get Size of CrossReferenceTable Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/cross_reference_table/struct.CrossReferenceTable.html Returns the number of object offsets currently stored in the cross-reference table. ```rust pub fn len(&self) -> usize ``` -------------------------------- ### Unit Creation and Conversion Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/unit/struct.Unit.html Demonstrates creating Unit instances from different measurement units and converting them to the default user space unit. ```APIDOC ## Unit Struct Methods ### `from_mm(mm: f32) -> Self` Creates a new `Unit` from the specified number of millimeters. #### Example ```rust let unit = Unit::from_mm(1.0); assert_eq!(unit.into_user_unit().floor(), 2.0); ``` ### `from_cm(cm: f32) -> Self` Creates a new `Unit` from the specified number of centimeters. #### Example ```rust let unit = Unit::from_cm(1.0); assert_eq!(unit.into_user_unit().floor(), 28.0); ``` ### `from_inch(inch: f32) -> Self` Creates a new `Unit` from the specified number of inches. #### Example ```rust let unit = Unit::from_inch(1.0); assert_eq!(unit.into_user_unit(), 72.0); ``` ### `from_unit(unit: f32) -> Unit` Creates a new `Unit` from the specified number of default user space units. ### `into_user_unit(self) -> f32` Converts the `Unit` into default user space unit to be specified in a PDF document, regardless of how this `Unit` is currently internally represented. #### Example ```rust let unit = Unit::from_inch(1.0); assert_eq!(unit.into_user_unit(), 72.0); ``` ``` -------------------------------- ### Get Length of CrossReferenceTable Offsets Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/cross_reference_table.rs.html Returns the number of object offsets currently stored in the cross-reference table. ```rust pub fn len(&self) -> usize { self.offsets.len() } ``` -------------------------------- ### Initialize PdfWriter Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Creates a new PdfWriter instance with an inner writer. The initial byte offset is set to 1, accounting for the '%' character in the PDF header. ```rust pub fn new(inner: W) -> Self { PdfWriter { inner, // NOTE: The current byte is included in offset. current_offset: 1, cross_reference_table: CrossReferenceTable::default(), } } ``` -------------------------------- ### Get Color Space Identifier Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/color/mod.rs.html Returns the PDF `Identifier` for the current color space (DeviceRGB, DeviceGray, or DeviceCMYK). ```rust fn identifier(&self) -> Identifier<&'static [u8]> { match self { Color::Rgb { .. } => Identifier::from_static(b"DeviceRGB"), Color::Gray(_) => Identifier::from_static(b"DeviceGray"), Color::CMYK { .. } => Identifier::from_static(b"DeviceCMYK"), } } ``` -------------------------------- ### Builder::build Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/builder.rs.html Constructs and returns a configured PDF Document based on the builder's settings. ```APIDOC ## Builder::build ### Description Produce a configured PDF [`Document`]. ### Signature ```rust pub fn build(mut self) -> Document ``` ### Returns A `Document` object configured with the specified page size and other settings. ``` -------------------------------- ### Dereference Pointer Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Dereferences the given pointer to get an immutable reference. This is an unsafe operation and part of the `Pointable` trait implementation. ```rust unsafe fn deref<'a>(ptr: usize) -> &'a T ``` -------------------------------- ### Text Builder Method Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/text/struct.Text.html Creates a default initialized `TextBuilder` with default font and size. ```APIDOC ## `builder()` Creates a default initialized [`TexBuilder`], providing default values for font (Helvetica) and it’s size (12). ### Signature ```rust pub fn builder() -> TextBuilder ``` ``` -------------------------------- ### Get Minimum of Two PdfStrings Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/string/struct.PdfString.html Compares two PdfString instances and returns the minimum of the two. Requires the Self type to be Sized. ```rust fn min(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Create New Page Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Creates a new blank page associated with a parent page tree and a media box. ```rust pub fn new( id: ObjId, contents_id: ObjId, parent: ObjId, ) -> Self ``` -------------------------------- ### Get Maximum of Two PdfStrings Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/string/struct.PdfString.html Compares two PdfString instances and returns the maximum of the two. Requires the Self type to be Sized. ```rust fn max(self, other: Self) -> Self where Self: Sized, ``` -------------------------------- ### Mutably Dereference Pointer Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Mutably dereferences the given pointer to get a mutable reference. This is an unsafe operation and part of the `Pointable` trait implementation. ```rust unsafe fn deref_mut<'a>(ptr: usize) -> &'a mut T ``` -------------------------------- ### Get a mutable reference to the current page Source: https://docs.rs/pdfgen/0.3.1/pdfgen/struct.Document.html Returns a mutable reference to the current page in the document, if one exists. Useful for modifying the active page. ```rust pub fn current_page(&mut self) -> Option<&mut Page> ``` -------------------------------- ### Create a New PageTree Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page_tree/struct.PageTree.html Initializes a new PageTree instance. This is the basic constructor for creating a page tree node. ```rust pub fn new(obj_id: ObjId, parent: Option<&PageTree>) -> Self ``` -------------------------------- ### Page::new Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Creates a new blank page that belongs to a given parent and media box. ```APIDOC ## pub fn new( id: ObjId, contents_id: ObjId, parent: ObjId, ) -> Self Create a new blank page that belongs to the given parent and media box. ``` -------------------------------- ### Create a PdfString Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/string.rs.html Use `PdfString::from` to create a new PdfString with initial content. This is useful for initializing string objects that will be written to a PDF. ```rust pub fn from(content: impl Into) -> Self { Self { inner: content.into(), } } ``` -------------------------------- ### Get Image Transform Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/image.rs.html Returns the current transformation matrix (position and scale) of the image. Note: This method is marked with a TODO and might be exposed differently in the public API. ```rust pub fn transform(&self) -> ImageTransform { self.transform } ``` -------------------------------- ### Create a New Page Object Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page.rs.html Initializes a new `Page` object with a given ID, content stream ID, and parent page tree. Sets default resources and an optional media box. ```rust pub fn new( id: ObjId, contents_id: ObjId, parent: ObjId, ) -> Self { Self { id, parent, resources: Resources::default(), media_box: None, contents: ContentStream::new(contents_id), } } ``` -------------------------------- ### Parse Identifier from String Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/identifier/struct.Identifier.html Parses an Identifier from a string slice. It enforces rules such as not starting with '/', not containing null characters, and correctly encoding special characters like '#' and whitespace. ```rust let ident = Identifier::from_str("SomeName").unwrap(); let mut output = Vec::new(); ident.write(&mut output).unwrap(); assert_eq!(&output, b"/SomeName "); ``` ```rust let ident = Identifier::from_str("With Whitespace").unwrap(); let mut output = Vec::new(); ident.write(&mut output).unwrap(); assert_eq!(&output, b"/With#20Whitespace "); ``` ```rust let ident = Identifier::from_str(" Trimmed").unwrap(); let mut output = Vec::new(); ident.write(&mut output).unwrap(); assert_eq!(&output, b"/Trimmed "); ``` ```rust let ident = Identifier::from_str("/Invalid"); assert!(matches!(ident, Err(ParseIdentifierErr::StartsWithSolidus))); ``` ```rust let ident = Identifier::from_str("WithNull\0"); assert!(matches!(ident, Err(ParseIdentifierErr::ContainsNull))); ``` -------------------------------- ### Create Image from File Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/image.rs.html Initializes an ImageBuilder by reading image data from a file. It decodes the image and converts it to RGB format. Defaults to 100mm width/height and position 0,0. ```rust pub fn from_file(file: &std::fs::File) -> ImageBuilder { let mut bytes = Vec::new(); BufReader::new(file).read_to_end(&mut bytes).unwrap(); Self::from_bytes(bytes) } ``` -------------------------------- ### Catalog Test: simple_catalog Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/catalog.rs.html A test case demonstrating the creation and content writing of a simple Catalog. ```APIDOC ## Test: simple_catalog ### Description Tests the creation of a `Catalog` and verifies its content output using `insta::assert_snapshot!`. ``` -------------------------------- ### Write PDF Page Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Writes a page object into the PDF document. It adds the page's starting offset to the cross-reference table and updates the current byte offset based on the written content. It also handles offsets for any objects embedded within the page. ```rust pub(crate) fn write_page( &mut self, page: &Page, id_manager: &mut IdManager, ) -> Result<(), io::Error> { self.cross_reference_table.add_object(self.current_offset); let (bytes_written, offsets) = page.write(&mut self.inner, id_manager)?; for offset in offsets { self.cross_reference_table .add_object(self.current_offset + offset); } self.current_offset += bytes_written; Ok(()) } ``` -------------------------------- ### Test String Expansion and Writing Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/string.rs.html This test checks the `expand` functionality by creating a PdfString, appending more text, and then verifying that the combined content is written correctly in PDF string format. ```rust #[test] fn simple_string_expanded() { let mut pdf_string = PdfString::from("This is"); pdf_string.expand(" an expanded text."); let mut writer = Vec::default(); pdf_string.write_content(&mut writer).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!(output, @"(This is an expanded text.)"); } ``` -------------------------------- ### Create Image from File Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/image/struct.Image.html Creates a new Image from a file. The default dimensions and position are applied. ```rust pub fn from_file(file: &File) -> ImageBuilder ``` -------------------------------- ### Catalog Test: Simple Catalog Creation Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/catalog.rs.html Tests the creation and content writing of a simple Catalog. It verifies that the `write_content` method produces the expected PDF dictionary format for a catalog with a root page tree. ```rust #[test] fn simple_catalog() { let mut id_manager = IdManager::new(); let page_tree = PageTree::new(id_manager.create_id(), None); let catalog = Catalog::new(id_manager.create_id(), page_tree); let mut writer = Vec::default(); catalog.write_content(&mut writer).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!(output, @r" << /Type /Catalog /Pages 1 0 R >> "); } ``` -------------------------------- ### Write and Assert PDF Output Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Writes the generated PDF content to a buffer and asserts its snapshot against a predefined PDF structure. Ensure the `insta` crate is available for snapshot testing. ```rust document.write(&mut writer).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!(output, @r" %PDF-2.0 1 0 obj << /Type /Catalog /Pages 2 0 R >> endobj 2 0 obj << /Type /Pages /Kids [3 0 R] /Count 1 >> endobj 3 0 obj << /Type /Page /Parent 2 0 R /Resources << >> /MediaBox [0 0 592.441 839.0551]>> endobj 5 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj xref 0 4 0000000010 00000 n 0000000061 00000 n 0000000120 00000 n 0000000220 00000 n trailer << /Size 4 /Root 1 0 R /ID [ ] >> startxref 294 %%EOF "); ``` -------------------------------- ### PdfString Initialization Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/string/struct.PdfString.html Provides methods for initializing PdfString objects. ```APIDOC ## type Init The type for initializers. ## unsafe fn init(init: ::Init) -> usize Initializes a with the given initializer. ``` -------------------------------- ### CmykValue Creation and Conversion Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/color/cmyk_value.rs.html Demonstrates how to create and use `CmykValue` instances, including conversion from `u8` and `f32` types, and handling potential out-of-range errors. ```APIDOC ## CmykValue Newtype for ensuring correct values are used in CMYK color space. ### Methods #### `from_const() -> Self` Create a new [`CmykValue`] from a constant that is in range. Range is checked at compile time. - **Panics**: If `N` is greater than 100. #### `try_from(value: u8) -> Result>` Create a new [`CmykValue`] from an [`u8`], with valid range being `[0, 100]`. - **Error**: Returns `CmykValueErr::OutOfRange` if the value is greater than 100. #### `try_from(value: f32) -> Result>` Create a new [`CmykValue`] from an [`f32`], with valid range being `[0.0, 1.0]`. - **Error**: Returns `CmykValueErr::OutOfRange` if the value is outside the `[0.0, 1.0]` range. ### Conversions #### `From for u8` Converts a `CmykValue` instance into its underlying `u8` representation. ### Errors #### `CmykValueErr` Possible errors that might be returned when creating a new [`CmykValue`] instance. - `OutOfRange(T)`: Indicates that the provided value is out of the acceptable range. ``` -------------------------------- ### PageTree Constants and Constructors Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page_tree.rs.html Defines constants for PageTree fields and provides constructors for creating new PageTree instances. `new` initializes a basic PageTree, while `with_mediabox` allows setting an initial media box. ```rust const_identifiers! { PARENT, PAGES, MEDIA_BOX, KIDS, COUNT, } pub fn new(obj_id: ObjId, parent: Option<&PageTree>) -> Self { Self { id: obj_id, parent: parent.map(|parent| parent.obj_ref()), kids: Vec::default(), count: 0, default_mediabox: None, } } pub fn with_mediabox( obj_id: ObjId, parent: Option<&PageTree>, mediabox: impl Into, ) -> Self { let mut page_tree = Self::new(obj_id, parent); page_tree.default_mediabox = Some(mediabox.into()); page_tree } ``` -------------------------------- ### Catalog Implementation Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/catalog.rs.html Provides methods for creating, referencing, and accessing the root PageTree of a Catalog. It also defines constants for common PDF dictionary keys. ```rust impl Catalog { const_identifiers! { CATALOG, PAGES, } /// Create a new `Catalog` with the given [`ObjId`] and [`PageTree`]. pub(crate) fn new(obj_ref: ObjId, root_page_tree: PageTree) -> Self { Self { id: obj_ref, root_page_tree, } } /// Returns the [`ObjId`] allocated to this `Catalog`. pub(crate) fn obj_ref(&self) -> ObjId { self.id.clone() } /// Returns a reference to the root [`PageTree`] that this `Catalog` holds. pub(crate) fn page_tree(&self) -> &PageTree { &self.root_page_tree } /// Returns a mutable reference to the root [`PageTree`] that this `Catalog` holds. pub(crate) fn page_tree_mut(&mut self) -> &mut PageTree { &mut self.root_page_tree } } ``` -------------------------------- ### Test Font Object Creation and Writing Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/font.rs.html Tests the creation of a `Font` object and its serialization into PDF format. Verifies the output against a snapshot using `insta::assert_snapshot!`. ```rust #[cfg(test)] mod tests { use crate::{IdManager, types::hierarchy::primitives::font::Object}; use super::Font; #[test] pub fn font_object() { let mut id_manager = IdManager::new(); let font = Font::new(id_manager.create_id(), "Type1", "Helvetica"); let mut writer = Vec::default(); let _ = font.write_def(&mut writer); let _ = font.write_content(&mut writer); let _ = font.write_end(&mut writer); let output = String::from_utf8_lossy(&writer); insta::assert_snapshot!(output, @r"1 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica >> endobj "); } } ``` -------------------------------- ### Create a PageTree with Mediabox Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page_tree/struct.PageTree.html Creates a new PageTree instance and associates it with a mediabox, which defines the boundaries of the page. Useful for setting initial page dimensions. ```rust pub fn with_mediabox( obj_id: ObjId, parent: Option<&PageTree>, mediabox: impl Into, ) -> Self ``` -------------------------------- ### Setting Default Media Box Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/page_tree.rs.html Allows updating the default media box for the PageTree after its creation. ```rust pub(crate) fn set_page_size(&mut self, rect: Rectangle) { self.default_mediabox = Some(rect); } ``` -------------------------------- ### Create Text Builder Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/text/struct.Text.html Initializes a TextBuilder with default values for font (Helvetica) and size (12). Use this to construct Text objects. ```rust pub fn builder() -> TextBuilder ``` -------------------------------- ### PdfWriter::new Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/pdf_writer/struct.PdfWriter.html Creates a new `PdfWriter` instance, wrapping an existing `Write` implementor. ```APIDOC ## PdfWriter::new ### Description Creates a new `PdfWriter` instance. ### Signature `pub fn new(inner: W) -> Self` ### Parameters - **inner** (`W` where `W: Write`): The underlying writer to wrap. ``` -------------------------------- ### Text Builder Initialization Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Provides a static method to create a TextBuilder with default values for font (Helvetica) and size (12). ```APIDOC /// Creates a default initialized [`TexBuilder`], providing default values for font (Helvetica) and it's /// size (12). pub fn builder() -> TextBuilder { let txt = Self { content: PdfString::from(""), transform: TextTransform { position: Position::from_mm(0.0, 0.0), size: 12, }, color: Color::Rgb { red: 0, green: 0, blue: 0, }, }; TextBuilder { inner: txt, script: Script::Normal, } } ``` -------------------------------- ### Try Convert From Another Type Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/text/struct.TextBuilder.html Attempts to convert another type into a TextBuilder. This conversion might fail. ```rust impl TryFrom for T where U: Into, ``` -------------------------------- ### Create New ContentStream Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/struct.ContentStream.html Creates a new ContentStream instance with a given ObjId. This is the primary way to initialize a ContentStream. ```rust pub fn new(id: ObjId) -> Self> ``` -------------------------------- ### Test Simple String Creation and Writing Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/string.rs.html This test verifies that a PdfString created with `PdfString::from` is correctly written to a buffer in the expected PDF string format, enclosed in parentheses. ```rust #[test] fn simple_string() { let pdf_string = PdfString::from("This is text."); let mut writer = Vec::default(); pdf_string.write_content(&mut writer).unwrap(); let output = String::from_utf8(writer).unwrap(); insta::assert_snapshot!(output, @"(This is text.)"); } ``` -------------------------------- ### Create Unit from Inches Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/primitives/unit/struct.Unit.html Use this to create a Unit instance from an inch value. The conversion to PDF user space units is demonstrated. ```rust let unit = Unit::from_inch(1.0); assert_eq!(unit.into_user_unit(), 72.0); ``` -------------------------------- ### Rectangle Conversions Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/primitives/rectangle.rs.html Implements conversions for creating Rectangle instances from tuples of `u32` and `f32` values, simplifying initialization. ```APIDOC ## From Tuples for Rectangle Creation Allows creating `Rectangle` instances from tuples of coordinates. ### Implementations - `impl From<(u32, u32, u32, u32)> for Rectangle` - `impl From<(f32, f32, f32, f32)> for Rectangle` ### Usage `Rectangle::from((ll_x, ll_y, tr_x, tr_y))` ``` -------------------------------- ### Set Media Box for Page Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/page/struct.Page.html Sets the media box (page dimensions) for the current Page object. ```rust pub fn set_mediabox(&mut self, media_box: impl Into) ``` -------------------------------- ### Image Configuration Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/image/struct.Image.html Methods for setting the dimensions, position, and other properties of an Image. ```APIDOC ## Image Configuration Methods ### `pub fn set_dimensions(&mut self, width: Unit, height: Unit)` Sets the width and height of this `Image`. ### `pub fn set_width(&mut self, width: Unit)` Sets the width of this `Image`. ### `pub fn set_height(&mut self, height: Unit)` Sets the height of this `Image`. ### `pub fn set_pos(&mut self, position: Position)` Sets the position of this `Image`. ``` -------------------------------- ### Document Creation Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/document/mod.rs.html Provides a builder pattern for creating new PDF documents. ```APIDOC ## Document::builder() ### Description Returns a new [`Builder`] instance to construct a [`Document`]. ### Method `Document::builder()` ### Returns - [`Builder`]: A new builder instance. ``` -------------------------------- ### Write PDF Trailer Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/pdf_writer.rs.html Writes the trailer for the PDF document's cross-reference table, including the root object ID, number of entries, and offsets hash. This function requires the current byte offset and the size of the cross-reference table. ```rust pub fn write_trailer(&mut self, root: ObjId) -> Result<(), io::Error> { self.cross_reference_table.write_trailer( &mut self.inner, self.current_offset, self.cross_reference_table.len(), root, self.cross_reference_table.offsets_hash()?, )?; Ok(()) } ``` -------------------------------- ### Render Custom Font Text in PDF Source: https://docs.rs/pdfgen/0.3.1/src/pdfgen/types/hierarchy/content/text.rs.html Demonstrates rendering text with a custom font and specific positioning. Ensures the output matches the expected PDF content structure. ```rust .to_bytes(Identifier::from_static(b"CustomFnt")) .unwrap(); let output = String::from_utf8_lossy(&subscript_text); insta::assert_snapshot!(output, @r" BT /DeviceRGB cs 0 0 0 sc /CustomFnt 9 Tf 0 -4.9 Td (This is a superscript text content.) Tj ET "); } } ``` -------------------------------- ### ContentStream::new Source: https://docs.rs/pdfgen/0.3.1/pdfgen/types/hierarchy/content/struct.ContentStream.html Creates a new ContentStream with the given ObjId. ```APIDOC ## ContentStream::new ### Description Creates a new `ContentStream` with the given [`ObjId`]. ### Signature ```rust pub fn new(id: ObjId) -> Self ``` ### Parameters * **id** (`ObjId`) - The object ID for the new ContentStream. ``` -------------------------------- ### Default implementation for Document Source: https://docs.rs/pdfgen/0.3.1/pdfgen/struct.Document.html Provides the default value for the Document type, typically an empty document. ```rust fn default() -> Self ``` -------------------------------- ### Create a new page in the document Source: https://docs.rs/pdfgen/0.3.1/pdfgen/struct.Document.html Creates a new page within the PDF document. Use this to add content to the PDF. ```rust pub fn create_page(&mut self) -> &mut Page ```