### PDF Startxref Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF Indicates the byte offset from the beginning of the file to the start of the cross-reference table. ```pdf startxref 534 ``` -------------------------------- ### PDF Info Dictionary Example Source: https://github.com/fschutt/printpdf/wiki/1.2.1-Metadata This example demonstrates how to define an 'Info' dictionary with various metadata fields and link it to the trailer. It includes optional fields like Title, Author, Subject, Keywords, Creator, Producer, CreationDate, ModDate, and Trapped. ```pdf 1 0 obj << /Title (Holiday plans) /Author (Mr. Bean) /Subject (After a won lottery, madman invades france) /Keywords (cannes teddy holiday) /Creator (MyPdfProgram) /Producer (printpdf v.0.5.0) /CreationDate (D:20110628115000+02'00') /ModDate (D:20110628115000+02'00') >> trailer << /Info 1 0 R >> ``` -------------------------------- ### PDF Page Content Stream Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF A stream object containing the actual drawing instructions for a page. This example sets the font, position, and displays the text 'Hallo Welt'. ```pdf 6 0 obj << /Length 41 >> stream /F1 48 Tf BT 72 746 Td (Hallo Welt) Tj ET endstream endobj ``` -------------------------------- ### Initialize WASM Module Source: https://github.com/fschutt/printpdf/blob/master/API.md Required setup before invoking any PDF functions. Ensure the WASM file is accessible in the specified directory. ```js // printpdf_bg.wasm needs to be in the same directory as printpdf.js import init, { Pdf_HtmlToDocument, Pdf_BytesToDocument, Pdf_ResourcesForPage, Pdf_PageToSvg, Pdf_DocumentToBytes, } from './pkg/printpdf.js'; async function main() { // Initialize the WASM await init(); // Now we can safely call our PDF functions // ... } main().catch(console.error); ``` -------------------------------- ### Generate PDF from HTML Source: https://github.com/fschutt/printpdf/blob/master/API.md Implementation example for converting HTML strings into a PDF document. ```js const inputObject = { title: "My PDF!", html: "

Hello World!

", // Suppose we have a base64 version of 'dog.png' we want to embed: images: { "dog.png": "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAA..." }, fonts: { "f1.woff2": "data:font/woff2;base64,..." // supports: ttf, otf, woff, woff2 }, options: { pageWidth: 210, // mm pageHeight: 297 // mm } }; const inputJson = JSON.stringify(inputObject); const outputJson = await Pdf_HtmlToDocument(inputJson); const result = JSON.parse(outputJson); if (result.status === 0) { // result.data.doc is the PdfDocument object console.log("PDF document:", result.data.doc); } else { console.error("Error generating PDF:", result.data); } ``` -------------------------------- ### Basic PDF String Syntax Source: https://github.com/fschutt/printpdf/wiki/1.1.2-Syntax Provides examples of PDF strings enclosed in parentheses. Demonstrates how to include balanced and unbalanced braces, as well as how to escape backslashes. ```plaintext (Hello World) ``` ```plaintext (Text (with balanced) braces) ``` ```plaintext (Text (with \(unbalanced) braces) ``` ```plaintext (Text \\with \\backslashes) ``` -------------------------------- ### Pdf_HtmlToDocument Response Example Source: https://github.com/fschutt/printpdf/blob/master/API.md Example JSON structure returned after a successful HTML to PDF conversion. ```json5 { "status": 0, "data": { "doc": { // Changed from "pdf" to "doc" "metadata": { /* ... */ }, "resources": { /* ... */ }, "bookmarks": { /* ... */ }, "pages": [ { "mediaBox": { /* ... */ }, "trimBox": { /* ... */ }, "cropBox": { /* ... */ }, "ops": [ ... ] } // ... ] } } } ``` -------------------------------- ### PDF Trailer Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF The trailer section provides essential information about the PDF file, including the size of the cross-reference table and references to the root ('Catalog') and information objects. ```pdf trailer << /Size 7 /Info 1 0 R /Root 2 0 R >> ``` -------------------------------- ### Embed Images in PDF Source: https://context7.com/fschutt/printpdf/llms.txt Shows how to load an image from bytes and embed it into a PDF document, with examples of placing it at the default position and with custom transformations (translation, rotation, scaling). Requires the `image` feature flag for decoding. ```rust use printpdf::* fn main() { let mut doc = PdfDocument::new("Image Example"); // Load and decode an image (requires appropriate feature flag) let image_bytes = include_bytes!("assets/dog.png"); let image = RawImage::decode_from_bytes(image_bytes, &mut Vec::new()).unwrap(); // Add image to document resources let image_id = doc.add_image(&image); let ops = vec![ // Place image at default position Op::UseXobject { id: image_id.clone(), transform: XObjectTransform::default(), }, // Place same image with translation, rotation, and scaling Op::UseXobject { id: image_id.clone(), transform: XObjectTransform { translate_x: Some(Pt(300.0)), translate_y: Some(Pt(300.0)), rotate: Some(XObjectRotation { angle_ccw_degrees: 45.0, rotation_center_x: Px(100), rotation_center_y: Px(100), }), scale_x: Some(0.5), scale_y: Some(0.5), dpi: Some(300.0), }, }, ]; let page = PdfPage::new(Mm(210.0), Mm(297.0), ops); let bytes = doc.with_pages(vec![page]).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("image_example.pdf", bytes).unwrap(); } ``` -------------------------------- ### PDF Pages Dictionary Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF Defines the 'Pages' object, which manages page-level settings including page size, resources (fonts, etc.), and a list of individual page objects. This example sets A4 page size and references font 'F1'. ```pdf 3 0 obj << /Type /Pages /MediaBox [0 0 595 842] /Resources << /Font << /F1 4 0 R >> /ProcSet [/PDF /Text] >> /Kids [5 0 R] /Count 1 >> endobj ``` -------------------------------- ### Pdf_BytesToDocument Response Example Source: https://github.com/fschutt/printpdf/blob/master/API.md Example JSON structure returned after parsing a PDF from bytes. ```json5 { "status": 0, "data": { "doc": { /* ... */ }, // The PdfDocument JSON "warnings": [ /* ... */ ] // Array of any PDF parse warnings } } ``` -------------------------------- ### PDF Cross-Reference Table Example Source: https://github.com/fschutt/printpdf/wiki/1.1.3-File-structure The xref table lists the byte offsets of indirect objects within the PDF. It starts with 'xref', followed by object counts, and then individual object entries. Each entry includes the byte offset, generation ID, and type ('f' for free, 'n' for normal). Padding with spaces is important for byte count accuracy. ```pdf xref 0 7 0000000000 65535 f 0000000009 00000 n 0000000050 00000 n 0000000102 00000 n 0000000268 00000 n 0000000374 00000 n 0000000443 00000 n ``` -------------------------------- ### Define a basic printpdf XML document structure Source: https://github.com/fschutt/printpdf/blob/master/SYNTAX.md This example demonstrates the use of head, body, header, footer, and style tags to define document layout and styling. Note that styles defined in the style block override inline styles. ```xml

This will be at the top of each page


Title of my book

Hello World!

``` -------------------------------- ### PDF Font Object Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF Defines a font resource, specifying its type, subtype, base font name (e.g., Helvetica), and encoding. This example uses a Type1 font with WinAnsiEncoding. ```pdf 4 0 obj << /Type /Font /Subtype /Type1 /BaseFont /Helvetica /Encoding /WinAnsiEncoding >> endobj ``` -------------------------------- ### PDF Trailer Structure Example Source: https://github.com/fschutt/printpdf/wiki/1.1.3-File-structure The trailer section marks the end of the PDF structure. It includes the 'trailer' keyword, a dictionary with essential keys like '/Size' and '/Root', followed by 'startxref' indicating the byte offset of the xref table, and finally '%%EOF' to signify the end of the file. ```pdf trailer << /Size 7 /Info 1 0 R /Root 2 0 R >> startxref 534 %%EOF ``` -------------------------------- ### Draw Graphics on a PDF Page Source: https://github.com/fschutt/printpdf/blob/master/README.md This example shows how to draw various graphical elements like lines and polygons onto a PDF page using the printpdf library. It includes configurations for colors, line styles, and graphic states. ```rust use printpdf::* fn main() { let mut doc = PdfDocument::new("My first PDF"); let line = Line { // Quadratic shape. The "false" determines if the next (following) // point is a bezier handle (for curves) // If you want holes, simply reorder the winding of the points to be // counterclockwise instead of clockwise. points: vec![ (Point::new(Mm(100.0), Mm(100.0)), false), (Point::new(Mm(100.0), Mm(200.0)), false), (Point::new(Mm(300.0), Mm(200.0)), false), (Point::new(Mm(300.0), Mm(100.0)), false), ], is_closed: true, }; // Triangle shape let polygon = Polygon { rings: vec![vec![ (Point::new(Mm(150.0), Mm(150.0)), false), (Point::new(Mm(150.0), Mm(250.0)), false), (Point::new(Mm(350.0), Mm(250.0)), false), ]], mode: PaintMode::FillStroke, winding_order: WindingOrder::NonZero, }; // Graphics config let fill_color = Color::Cmyk(Cmyk::new(0.0, 0.23, 0.0, 0.0, None)); let outline_color = Color::Rgb(Rgb::new(0.75, 1.0, 0.64, None)); let mut dash_pattern = LineDashPattern::default(); dash_pattern.dash_1 = Some(20); let extgstate = ExtendedGraphicsStateBuilder::new() .with_overprint_stroke(true) .with_blend_mode(BlendMode::multiply()) .build(); let page1_contents = vec![ // add line1 (square) Op::SetOutlineColor { col: Color::Rgb(Rgb::new(0.75, 1.0, 0.64, None)) }, Op::SetOutlineThickness { pt: Pt(10.0) }, Op::DrawLine { line: line }, // add line2 (triangle) Op::SaveGraphicsState, Op::LoadGraphicsState { gs: doc.add_graphics_state(extgstate) }, Op::SetLineDashPattern { dash: dash_pattern }, Op::SetLineJoinStyle { join: LineJoinStyle::Round }, Op::SetLineCapStyle { cap: LineCapStyle::Round }, Op::SetFillColor { col: fill_color }, Op::SetOutlineThickness { pt: Pt(15.0) }, Op::SetOutlineColor { col: outline_color }, Op::DrawPolygon { polygon: polygon }, Op::RestoreGraphicsState, ]; let page1 = PdfPage::new(Mm(10.0), Mm(250.0), page1_contents); let pdf_bytes: Vec = doc .with_pages(vec![page1]) .save(&PdfSaveOptions::default()); } ``` -------------------------------- ### PDF Metadata Object Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF Defines metadata for the PDF document, such as the title. Object numbers are arbitrary. ```pdf 1 0 obj << /Title (Hallo Welt) >> endobj ``` -------------------------------- ### PDF Page Object Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF Represents a single page in the PDF. It references its parent 'Pages' object and the 'Contents' stream which describes the page's visual elements. ```pdf 5 0 obj << /Type /Page /Parent 3 0 R /Contents 6 0 R >> endobj ``` -------------------------------- ### PDF Catalog Object Example Source: https://github.com/fschutt/printpdf/wiki/1.1.1-Hello-World-PDF The Catalog object serves as the root of the PDF document's object hierarchy, referencing other essential objects like the Pages dictionary. ```pdf 2 0 obj << /Type /Catalog /Pages 3 0 R >> endobj ``` -------------------------------- ### Execute Content Stream Instructions Source: https://github.com/fschutt/printpdf/wiki/1.1.2-Syntax Instructions use postfix notation to perform actions like text placement in content streams. ```PDF 72 746 Td (Hello World) Tj ``` -------------------------------- ### Create a Basic PDF Document Source: https://github.com/fschutt/printpdf/blob/master/README.md This snippet demonstrates the fundamental process of creating a new PDF document and saving it. It initializes a document, adds a page with a marker, and saves the PDF bytes. ```rust use printpdf::* fn main() { let mut doc = PdfDocument::new("My first PDF"); let page1_contents = vec![Op::Marker { id: "debugging-marker".to_string() }]; let page1 = PdfPage::new(Mm(10.0), Mm(250.0), page1_contents); let pdf_bytes: Vec = doc .with_pages(vec![page1]) .save(&PdfSaveOptions::default()); } ``` -------------------------------- ### Create a Basic PDF Document Source: https://context7.com/fschutt/printpdf/llms.txt Initializes a new PDF document, defines page dimensions, and saves the output to a file. ```rust use printpdf::*; fn main() { // Create a new PDF document with a title let mut doc = PdfDocument::new("My First PDF"); // Define page content using operations let page_contents = vec![ Op::Marker { id: "page-start".to_string() } ]; // Create a page with width=210mm, height=297mm (A4 size) let page = PdfPage::new(Mm(210.0), Mm(297.0), page_contents); // Add pages and save to bytes let pdf_bytes: Vec = doc .with_pages(vec![page]) .save(&PdfSaveOptions::default(), &mut Vec::new()); // Write to file std::fs::write("output.pdf", pdf_bytes).unwrap(); } ``` -------------------------------- ### Begin Marked Content with Properties Source: https://github.com/fschutt/printpdf/blob/master/STRUCTS.md Begins a marked content sequence with an accompanying property list. ```typescript // Begins a marked content sequence with an accompanying property list. interface BeginMarkedContentWithProperties { // Tag for marked content tag: string; // Properties for marked content properties: DictItem[]; } ``` -------------------------------- ### Load and Use Custom Fonts Source: https://github.com/fschutt/printpdf/blob/master/README.md Shows how to load a font from bytes, add it to the document, and write text to the page. Auto-subsetting can be enabled via PdfSaveOptions. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("My first PDF"); let roboto_bytes = include_bytes!("assets/fonts/RobotoMedium.ttf").unwrap() let font_index = 0; let mut warnings = Vec::new(); let font = ParsedFont::from_bytes(&roboto_bytes, font_index, &mut warnings).unwrap(); // If you need custom text shaping (uses the `allsorts` font shaper internally) // let glyphs = font.shape(text); // printpdf automatically keeps track of which fonts are used in the PDF let font_id = doc.add_font(&font); let text_pos = Point { x: Mm(10.0).into(), y: Mm(100.0).into(), }; // from bottom left let page1_contents = vec![ Op::SetLineHeight { lh: Pt(33.0) }, Op::SetWordSpacing { pt: Pt(33.0) }, Op::SetCharacterSpacing { multiplier: 10.0 }, Op::SetTextCursor { pos: text_pos }, // Op::WriteCodepoints { ... } // Op::WriteCodepointsWithKerning { ... } Op::WriteText { items: vec![TextItem::Text("Lorem ipsum".to_string())], font: font_id.clone(), }, Op::AddLineBreak, Op::WriteText { items: vec![TextItem::Text("dolor sit amet".to_string())], font: font_id.clone(), }, Op::AddLineBreak, ]; let save_options = PdfSaveOptions { subset_fonts: true, // auto-subset fonts on save ..Default::default() }; let page1 = PdfPage::new(Mm(10.0), Mm(250.0), page1_contents); let mut warnings = Vec::new(); let pdf_bytes: Vec = doc .with_pages(vec![page1]) .save(&save_options, &mut warnings); } ``` -------------------------------- ### Apply Advanced Text Formatting in Rust Source: https://context7.com/fschutt/printpdf/llms.txt Demonstrates how to manipulate text rendering, spacing, and kerning using Op operations in printpdf. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("Advanced Text Example"); let ops = vec![ Op::StartTextSection, Op::SetTextCursor { pos: Point::new(Mm(20.0), Mm(280.0)) }, Op::SetFont { font: PdfFontHandle::Builtin(BuiltinFont::Helvetica), size: Pt(14.0), }, Op::SetLineHeight { lh: Pt(16.0) }, // Normal text Op::ShowText { items: vec![TextItem::Text("Normal text".to_string())] }, Op::AddLineBreak, // Text with character spacing Op::SetCharacterSpacing { multiplier: 2.0 }, Op::ShowText { items: vec![TextItem::Text("Spaced characters".to_string())] }, Op::SetCharacterSpacing { multiplier: 0.0 }, Op::AddLineBreak, // Text with horizontal scaling Op::SetHorizontalScaling { percent: 150.0 }, Op::ShowText { items: vec![TextItem::Text("Expanded text".to_string())] }, Op::SetHorizontalScaling { percent: 100.0 }, Op::AddLineBreak, // Text with word spacing Op::SetWordSpacing { pt: Pt(10.0) }, Op::ShowText { items: vec![TextItem::Text("Extra word spacing here".to_string())] }, Op::SetWordSpacing { pt: Pt(0.0) }, Op::AddLineBreak, // Stroked text (outline only) Op::SetTextRenderingMode { mode: TextRenderingMode::Stroke }, Op::SetOutlineColor { col: Color::Rgb(Rgb { r: 0.8, g: 0.0, b: 0.0, icc_profile: None }), }, Op::SetOutlineThickness { pt: Pt(0.5) }, Op::ShowText { items: vec![TextItem::Text("Outlined text".to_string())] }, Op::SetTextRenderingMode { mode: TextRenderingMode::Fill }, Op::AddLineBreak, // Manual kerning with TextItem::Offset Op::ShowText { items: vec![ TextItem::Text("A".to_string()), TextItem::Offset(-30.0), TextItem::Text("V".to_string()), TextItem::Offset(-30.0), TextItem::Text("A".to_string()), ], }, Op::EndTextSection, ]; let page = PdfPage::new(Mm(210.0), Mm(297.0), ops); let bytes = doc.with_pages(vec![page]).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("advanced_text.pdf", bytes).unwrap(); } ``` -------------------------------- ### Begin Marked Content Source: https://github.com/fschutt/printpdf/blob/master/STRUCTS.md Begins a marked content sequence with a specified tag. ```typescript // Begins a marked content sequence. interface BeginMarkedContent { // Tag for marked content tag: string; } ``` -------------------------------- ### Basic PDF Name Syntax Source: https://github.com/fschutt/printpdf/wiki/1.1.2-Syntax Demonstrates the standard format for PDF names, which begin with a forward slash '/' followed by a string of printable characters. This is used for document-internal keys and values. ```plaintext /Type /MediaBox ``` -------------------------------- ### Extract Page Resources Source: https://github.com/fschutt/printpdf/blob/master/API.md Use `Pdf_ResourcesForPage` to get resource IDs (xobjects, fonts, layers) for a specific PDF page. This requires the page object as input within a JSON string. Check the status for success. ```typescript interface PdfResourcesForPageInput { page: PdfPage; // single element from `pdfDocument.pages[index]` } ``` ```json5 { "status": 0, "data": { "xobjects": [ "X001", "X012", "X10", ... ], "fonts": [ "F1", "F3", "F4", ... ], "layers": [ "Page1-Layer0138", ... ] } } ``` ```javascript const inputObj = { page: pdfDocument.pages[0] }; const resourcesJson = await Pdf_ResourcesForPage(JSON.stringify(inputObj)); const resourcesResult = JSON.parse(resourcesJson); if (resourcesResult.status === 0) { console.log("Resources for this page:", resourcesResult.data); // data.xobjects, data.fonts, data.layers } else { console.error("Error getting resources:", resourcesResult.data); } ``` -------------------------------- ### Create PDF Layers Source: https://context7.com/fschutt/printpdf/llms.txt Defines and registers layers to organize content, allowing for toggling visibility in PDF viewers. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("Layers Example"); // Create layer definitions let background_layer = Layer { name: "Background".to_string(), creator: "printpdf".to_string(), intent: LayerIntent::View, usage: LayerSubtype::Artwork, }; let text_layer = Layer { name: "Text Content".to_string(), creator: "printpdf".to_string(), intent: LayerIntent::Design, usage: LayerSubtype::Artwork, }; // Register layers with document let bg_layer_id = doc.add_layer(&background_layer); let text_layer_id = doc.add_layer(&text_layer); let ops = vec![ // Background layer content Op::BeginLayer { layer_id: bg_layer_id.clone() }, Op::SetFillColor { col: Color::Rgb(Rgb { r: 0.95, g: 0.95, b: 0.95, icc_profile: None }), }, Op::DrawPolygon { polygon: Polygon { rings: vec![PolygonRing { points: vec![ LinePoint { p: Point { x: Pt(0.0), y: Pt(0.0) }, bezier: false }, LinePoint { p: Point { x: Pt(595.0), y: Pt(0.0) }, bezier: false }, LinePoint { p: Point { x: Pt(595.0), y: Pt(842.0) }, bezier: false }, LinePoint { p: Point { x: Pt(0.0), y: Pt(842.0) }, bezier: false }, ], }], mode: PaintMode::Fill, winding_order: WindingOrder::NonZero, }, }, Op::EndLayer, // Text layer content Op::BeginLayer { layer_id: text_layer_id.clone() }, Op::StartTextSection, Op::SetTextCursor { pos: Point::new(Mm(20.0), Mm(270.0)) }, Op::SetFont { font: PdfFontHandle::Builtin(BuiltinFont::Helvetica), size: Pt(24.0), }, Op::SetLineHeight { lh: Pt(24.0) }, Op::ShowText { items: vec![TextItem::Text("Text on separate layer".to_string())], }, Op::EndTextSection, Op::EndLayer, ]; let page = PdfPage::new(Mm(210.0), Mm(297.0), ops); let bytes = doc.with_pages(vec![page]).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("layers_example.pdf", bytes).unwrap(); } ``` -------------------------------- ### Create Multi-Page Documents with Bookmarks in Rust Source: https://context7.com/fschutt/printpdf/llms.txt Defines page operations and adds navigational bookmarks to a multi-page PDF document. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("Multi-page Example"); // Create page 1: Title page let page1_ops = vec![ Op::StartTextSection, Op::SetTextCursor { pos: Point::new(Mm(50.0), Mm(150.0)) }, Op::SetFont { font: PdfFontHandle::Builtin(BuiltinFont::TimesBold), size: Pt(30.0), }, Op::SetLineHeight { lh: Pt(30.0) }, Op::ShowText { items: vec![TextItem::Text("Document Title".to_string())], }, Op::EndTextSection, ]; // Create page 2: Content page let page2_ops = vec![ Op::StartTextSection, Op::SetTextCursor { pos: Point::new(Mm(20.0), Mm(280.0)) }, Op::SetFont { font: PdfFontHandle::Builtin(BuiltinFont::Helvetica), size: Pt(12.0), }, Op::SetLineHeight { lh: Pt(14.0) }, Op::ShowText { items: vec![TextItem::Text("Chapter 1: Introduction".to_string())], }, Op::EndTextSection, ]; // Create pages let pages = vec![ PdfPage::new(Mm(210.0), Mm(297.0), page1_ops), PdfPage::new(Mm(210.0), Mm(297.0), page2_ops), ]; // Add bookmarks for navigation (1-indexed page numbers) doc.add_bookmark("Title Page", 1); doc.add_bookmark("Chapter 1", 2); let bytes = doc.with_pages(pages).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("multipage_example.pdf", bytes).unwrap(); } ``` -------------------------------- ### CSS Border Radius and Color Split Configurations Source: https://github.com/fschutt/printpdf/blob/master/examples/assets/html/tests/border_radius_colors.html A series of CSS classes demonstrating different border-radius and border-color combinations for box elements. ```css body { font-family: Arial, sans-serif; padding: 20px; } .test-container { margin: 30px 0; } .label { font-size: 14px; margin-bottom: 10px; } /* Test 1: All different colors, same radius */ .box1 { width: 200px; height: 100px; border-radius: 20px; border-top: 5px solid red; border-right: 5px solid green; border-bottom: 5px solid blue; border-left: 5px solid orange; background: #f0f0f0; } /* Test 2: Different widths, different colors */ .box2 { width: 200px; height: 100px; border-radius: 30px; border-top: 3px solid #ff0000; border-right: 8px solid #00ff00; border-bottom: 3px solid #0000ff; border-left: 8px solid #ffaa00; background: #f0f0f0; } /* Test 3: Large radius with color split */ .box3 { width: 150px; height: 150px; border-radius: 50px; border-top: 4px solid purple; border-right: 4px solid cyan; border-bottom: 4px solid magenta; border-left: 4px solid yellow; background: #e8e8e8; } /* Test 4: Elliptical radius */ .box4 { width: 200px; height: 80px; border-radius: 40px 40px 40px 40px / 20px 20px 20px 20px; border-top: 4px solid #cc0000; border-right: 4px solid #00cc00; border-bottom: 4px solid #0000cc; border-left: 4px solid #cc6600; background: #f5f5f5; } /* Test 5: Only two colors (top/bottom same, left/right same) */ .box5 { width: 200px; height: 100px; border-radius: 25px; border-top: 5px solid red; border-right: 5px solid blue; border-bottom: 5px solid red; border-left: 5px solid blue; background: #f0f0f0; } /* Test 6: Single corner radius only */ .box6 { width: 200px; height: 100px; border-top-left-radius: 40px; border-top-right-radius: 0; border-bottom-right-radius: 0; border-bottom-left-radius: 0; border-top: 5px solid red; border-right: 5px solid green; border-bottom: 5px solid blue; border-left: 5px solid orange; background: #f0f0f0; } ``` -------------------------------- ### Create PDF Streams Source: https://github.com/fschutt/printpdf/wiki/1.1.2-Syntax Streams require a dictionary with a /Length entry, followed by the stream keyword and data. ```PDF << /Length 51 >> stream This is a short example stream. Your image data would go here. endstream ``` -------------------------------- ### Configure Extended Graphics State and Blend Modes Source: https://context7.com/fschutt/printpdf/llms.txt Shows how to define an ExtendedGraphicsState and apply it to drawing operations to achieve effects like transparency and blending. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("Graphics State Example"); // Create an extended graphics state with blend mode let extgstate = ExtendedGraphicsStateBuilder::new() .with_overprint_stroke(true) .with_blend_mode(BlendMode::multiply()) .build(); let gs_id = doc.add_graphics_state(extgstate); let ops = vec![ // Draw base rectangle Op::SetFillColor { col: Color::Rgb(Rgb { r: 1.0, g: 0.0, b: 0.0, icc_profile: None }), }, Op::DrawPolygon { polygon: Polygon { rings: vec![PolygonRing { points: vec![ LinePoint { p: Point { x: Pt(100.0), y: Pt(600.0) }, bezier: false }, LinePoint { p: Point { x: Pt(200.0), y: Pt(600.0) }, bezier: false }, LinePoint { p: Point { x: Pt(200.0), y: Pt(500.0) }, bezier: false }, LinePoint { p: Point { x: Pt(100.0), y: Pt(500.0) }, bezier: false }, ], }], mode: PaintMode::Fill, winding_order: WindingOrder::NonZero, }, }, // Apply graphics state and draw overlapping rectangle Op::SaveGraphicsState, Op::LoadGraphicsState { gs: gs_id }, Op::SetFillColor { col: Color::Rgb(Rgb { r: 0.0, g: 0.0, b: 1.0, icc_profile: None }), }, Op::DrawPolygon { polygon: Polygon { rings: vec![PolygonRing { points: vec![ LinePoint { p: Point { x: Pt(150.0), y: Pt(650.0) }, bezier: false }, LinePoint { p: Point { x: Pt(250.0), y: Pt(650.0) }, bezier: false }, LinePoint { p: Point { x: Pt(250.0), y: Pt(550.0) }, bezier: false }, LinePoint { p: Point { x: Pt(150.0), y: Pt(550.0) }, bezier: false }, ], }], mode: PaintMode::Fill, winding_order: WindingOrder::NonZero, }, }, Op::RestoreGraphicsState, ]; let page = PdfPage::new(Mm(210.0), Mm(297.0), ops); let bytes = doc.with_pages(vec![page]).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("graphics_state.pdf", bytes).unwrap(); } ``` -------------------------------- ### Add Link Annotations in Rust Source: https://context7.com/fschutt/printpdf/llms.txt Demonstrates how to insert internal page links and external URL links into a PDF document using link annotations. ```rust use printpdf::*; fn main() { let mut doc = PdfDocument::new("Links Example"); let ops = vec![ Op::StartTextSection, Op::SetTextCursor { pos: Point::new(Mm(20.0), Mm(280.0)) }, Op::SetFont { font: PdfFontHandle::Builtin(BuiltinFont::Helvetica), size: Pt(12.0), }, Op::SetLineHeight { lh: Pt(12.0) }, Op::ShowText { items: vec![TextItem::Text("Click the links below:".to_string())], }, Op::EndTextSection, // Internal link to page 2 Op::LinkAnnotation { link: LinkAnnotation::new( Rect::from_xywh(Pt(100.0), Pt(170.0), Pt(200.0), Pt(30.0)), Actions::go_to(Destination::Xyz { page: 2, left: Some(0.0), top: Some(792.0), zoom: None, }), None, Some(ColorArray::Rgb([0.0, 0.0, 1.0])), None, ), }, // External URL link Op::LinkAnnotation { link: LinkAnnotation::new( Rect::from_xywh(Pt(100.0), Pt(120.0), Pt(200.0), Pt(30.0)), Actions::uri("https://github.com/fschutt/printpdf".to_string()), None, Some(ColorArray::Rgb([0.0, 0.6, 0.0])), None, ), }, ]; let page = PdfPage::new(Mm(210.0), Mm(297.0), ops); let bytes = doc.with_pages(vec![page]).save(&PdfSaveOptions::default(), &mut Vec::new()); std::fs::write("links_example.pdf", bytes).unwrap(); } ``` -------------------------------- ### Render HTML to PDF Source: https://github.com/fschutt/printpdf/blob/master/README.md Utilizes the XML/HTML layout system to generate PDF content. Requires the "html" feature flag. ```rust // needs --features="html" use printpdf::*; fn main() { // See https://fschutt.github.io/printpdf for an interactive WASM demo! let html = r#"

Hello!

World!

Chapter {attr:chapter} * {attr:subsection}

{builtin:pagenum}