krilla

repository·main·Indexed 19 days ago

https://github.com/laurenzv/krilla

A high-level Rust crate for generating PDF files using 2D graphics primitives. Built on top of pdf-writer, it provides an interface for drawing shapes, text, gradients, and images, supporting PDF versions 1.4 through 2.0 and standards such as PDF/A and PDF/UA. It includes the krilla-svg extension for rendering SVG files into PDF. Note that krilla is a graphics library and does not handle high-level document layout tasks like page breaking or table creation.

Tokens
26.6K
Snippets
69
Records
122
Agent score
65%

What's inside krilla

  1. Overview of krilla

    main

    krilla is a high-level Rust crate designed for creating PDF files. It abstracts the complexities of the PDF format by providing high-level 2D graphics primitives such as fills, strokes, gradients, glyphs, and images. It is built on top of the pdf-writer crate.

    Target Use Case

    krilla is ideal for libraries that already have an intermediate representation of layouted content (e.g., from HTML or other sources) and need to translate that layout into a PDF.

    Note: krilla is a low-level graphics library for PDF generation. It does not handle high-level document layout tasks like text layouting, table creation, page breaking, or inserting headers/footers. For those tasks, consider using typst.

  2. Convert SVG files to PDF with krilla-svg

    main
    The krilla-svg crate is an extension for krilla that enables rendering SVG files into PDF format. It is built upon the usvg library. To use it, integrate it with krilla to facilitate the conversion process. For implementation details, refer to the examples in the crates/krilla-svg/examples directory of the repository.
  3. Configure PDF/UA-1 compliance mode

    main

    When using krilla in PDF/UA-1 mode, the library enforces several accessibility and structural requirements to ensure the output conforms to the PDF/UA-1 standard.

    Key behaviors in this mode:

    • PDF Version: Defaults to PDF 1.7 (supports any version up to 1.7).
    • Document Metadata: Forces the user to provide a document title and automatically sets DisplayDocTitle to true.
    • Structure Tree: Writes the pdfuaid:part attribute, maps non-standard structure types, and ensures artifacts are never included in the structure tree.
    • Navigation: Enforces the setting of a document outline.
    • Annotations: Ensures all annotations have alternate text and writes the TabOrder property for pages with a struct parent.
    • Fonts: Uses Identity-H encoding, includes CIDToGIDMap, cmap (with WMode entry), and ToUnicode mappings. It only uses CID fonts (not TrueType).
  4. Core graphics features in krilla

    main

    The krilla library provides a wide range of 2D graphics capabilities for PDF generation:

    • Paths & Shapes: Filling and stroking arbitrary paths, clip paths, and affine transformations.
    • Text: A high-level API for rendering character sequences and a low-level API for positioned glyphs. Includes excellent OpenType font support (including color fonts).
    • Color & Effects: Alpha and luminosity masks, blend modes, layer isolation, and various gradients (linear, radial, sweep) and patterns.
    • Images: Embedding bitmap images and SVG images (via the krilla-svg crate).
    • Performance: Optional multi-threading support via rayon for faster compression and image processing.

    PDF Specification Support

    • Document Structure: Document outlines, page labels, annotations, links, and (named) destinations.
    • Metadata & Accessibility: Document metadata and support for creating accessible PDFs via tagged PDF.
    • Versions & Standards: Supports PDF versions 1.4 through 2.0, and validated export modes including PDF/A-1, PDF/A-2, PDF/A-3, PDF/A-4, and PDF/UA-1.
  5. Understand PDF/A-4 conformance in krilla

    main

    When using krilla in PDF/A-4 export mode, the library enforces PDF version 2.0. This mode is designed for long-term archiving and has specific constraints and capabilities:

    Core Capabilities

    • Graphics: Supports transparency and device-independent colors using compatible ICC profiles (RGB only for output intents).
    • Fonts: Uses IDENTITY-H encoding, embeds CIDtoGIDMap for Type2 CID fonts, embeds cmaps, font programs, and ToUnicode entries. It ensures Unicode values are valid (not U+FEFF or U+FFFE) and forbids characters in the private use area.
    • Metadata: Always requires metadata and includes document identifiers and minimal xmpMM:History entries.
    • Annotations: Only supports link annotations.

    Limitations and Unsupported Features

    • Security: No support for encryption, permissions, or digital signatures.
    • Interactivity: No support for interactive forms, JavaScript actions, or named actions.
    • Images: No support for JPEG2000, thumbnails, or the Interpolate key. Inline images are not used.
    • Advanced PDF Features: No support for linearization, 3D features, geospatial features, or optional content.
    • Embedded Files: By default, embedding files is forbidden in PDF/A-4 mode (see A4-F/A4-E for exceptions).
  6. Understand PDF/A-2 conformance levels in krilla

    main

    PDF/A-2 requires PDF version <= 1.7 and supports three conformance levels in increasing order of strictness:

    1. Level B: The least strict level.
    2. Level U: A subset of Level A, which includes Level B.
    3. Level A: The most strict level.

    When choosing a level, note that Level A adds requirements for Unicode mapping and forbids codepoints in the Unicode private area. Level U adds requirements for ToUnicode mapping and glyph codepoint validation.

  7. Understand PDF/A-1 conformance levels in krilla

    main

    PDF/A-1 requires PDF version <= 1.4 and offers two conformance levels in krilla:

    1. Level B: A subset of Level A. It focuses on basic visual conformance.
    2. Level A: The stricter level which includes all Level B requirements plus support for logical structure (tagged PDF).

    When choosing an export mode, be aware that Level A requires additional metadata and structural information (like document language and structure trees) to be valid.

  8. Configure fills and gradients

    main

    You can style shapes and text using surface.set_fill. The Fill struct accepts a paint which can be a solid color or a gradient.

    Solid Colors

    Use krilla::color::rgb::Color converted into a paint type.

    Linear Gradients

    Use LinearGradient to define a gradient between two points (x1, y1 to x2, y2). It requires a list of Stop objects, where each stop defines an offset (using NormalizedF32), a color, and an opacity.

    use krilla::paint::{LinearGradient, Stop, Fill, FillRule, SpreadMethod};
    use krilla::num::NormalizedF32;
    use krilla::color::rgb;
    
    let lg = LinearGradient {
        x1: 60.0,
        y1: 0.0,
        x2: 140.0,
        y2: 0.0,
        transform: Default::default(),
        spread_method: SpreadMethod::Repeat,
        stops: vec![
            Stop {
                offset: NormalizedF32::new(0.2).unwrap(),
                color: rgb::Color::new(255, 0, 0).into(),
                opacity: NormalizedF32::ONE,
            },
        ],
        anti_alias: false,
    };
    
    surface.set_fill(Some(Fill {
        paint: lg.into(),
        rule: FillRule::EvenOdd,
        opacity: NormalizedF32::ONE
    }));
  9. Understand krilla's compliance and enforcement levels

    main

    Krilla uses a color-coded legend to document how it handles various compliance properties and invariants. When reviewing documentation in the configure directory, use the following legend to understand what is actively enforced, what is unsupported, and what is the responsibility of the user:

    • 🟢 Actively Enforced: Krilla checks this property via code invariants or by returning errors if the property is not fulfilled.
    • 🔵 Unsupported: Krilla fulfills this property simply because the feature is not supported.
    • 🟣 User Responsibility: Krilla cannot enforce this property; the user of the library must ensure compliance.
    • 🔴 Not Enforced: The property is currently not enforced by krilla.
    • 🟠 Undecided/Deferred: The property might be documented or checked in the future, but is currently ignored because it is deemed unnecessary or difficult to implement.
    • - Not Applicable: The property does not apply to krilla (e.g., it is not a reader application).
  10. Understand PDF/A-3 conformance levels

    main

    PDF/A-3 is a PDF version (<= 1.7) that defines three conformance levels. They are ordered from least strict to most strict:

    1. Level B: The basic level.
    2. Level U: Adds additional requirements.
    3. Level A: The most strict level.

    PDF/A-3 is identical to PDF/A-2, with the exception of clause 6.8 regarding embedded files.