Add and read annotations, links, and bookmarks

This guide shows developers how to use PDFluent to manipulate PDF structure and markup. It is for Rust developers working with PDF documents.

Add PDFluent to your project

Add the pdfluent crate to Cargo.toml.
toml
[dependencies]
pdfluent = "1.5.0"

Read and parse annotations from a PDF in Rust

Iterate over every annotation on every page. Read annotation type, author, contents, bounding box, colour, and creation date.
rust
use pdfluent::PdfDocument;

fn main() -> pdfluent::Result<()> {
    let doc = PdfDocument::open("reviewed.pdf")?;
    for page in 0..doc.page_count() {
        for a in doc.annotations(page)? {
            println!("{}: {:?}", a.subtype, a.contents);
        }
    }
    Ok(())
}
  1. Step 1

    Open the PDF

    Open the file as a read-only document. You do not need a mutable reference just to read annotations.

    rust
    use pdfluent::PdfDocument;
    
    let doc = PdfDocument::open("reviewed_contract.pdf")?;
  2. Step 2

    Iterate over pages and annotations

    Call annotations() on each page to get a slice of Annotation objects. Each object exposes its type, position, and metadata.

    rust
    for page_idx in 0..doc.page_count() {
        let annotations = doc.annotations(page_idx)?;
        println!("Page {} has {} annotations", page_idx + 1, annotations.len());
    
        for ann in &annotations {
            println!("  Type: {}", ann.subtype);
            println!("  Rect: {:?}", ann.rect);
            println!("  Contents: {:?}", ann.contents);
        }
    }
  3. Step 3

    Filter by annotation type

    Use annotation_type() to select only the types you care about. AnnotationType is an enum with variants for each standard PDF annotation type.

    rust
    for page_idx in 0..doc.page_count() {
        for ann in doc.annotations(page_idx)? {
            if ann.subtype == "Highlight" {
                println!("Highlight at {:?}: {}", ann.rect, ann.contents.unwrap_or_default());
            }
        }
    }
  4. Step 4

    Export annotations to JSON

    Collect all annotations into a serialisable struct. This is useful for syncing review comments to an external system.

    rust
    // AnnotationInfo exposes: subtype, rect (Option<[f64;4]>), contents (Option<String>)
    let mut records = Vec::new();
    for page_idx in 0..doc.page_count() {
        for ann in doc.annotations(page_idx)? {
            records.push(format!(
                "{{\"page\":{},\"type\":\"{}\",\"contents\":{:?}}}",
                page_idx + 1, ann.subtype, ann.contents.unwrap_or_default()
            ));
        }
    }
    println!("[{}]", records.join(","));
  • annotations() returns an empty slice on pages with no annotations. No error is raised.
  • FreeText annotations may have content rendered on the page. The text is also available via contents().
  • Ink annotations have a list of point paths instead of a single rect. Use ann.ink_paths() to read them.
  • Reply annotations (threaded comments) expose reply_to() which returns the ID of the parent annotation.
How do I get the highlighted text content, not just the bounding box?
Call ann.highlighted_text() on a Highlight annotation. PDFluent maps the annotation rectangle back to the text content stream and returns the string that falls within the bounds.
Can I read annotations from a password-protected PDF?
Yes, but you must decrypt the document first. Call PdfDocument::open_with("file.pdf", OpenOptions::new().with_password("password")) before reading annotations.
Are popup annotations returned by annotations()?
Popup annotations are associated with other annotation types and are returned as part of the parent annotation. They do not appear as independent items in the annotations() slice.
How do I delete an annotation after reading it?
Not from the Rust SDK. annotations() reads and lists; adding, editing and deleting annotations are not part of the Rust surface. flatten_annotations() is the one write operation, and it burns existing annotations into the page content rather than removing them.

Add bookmarks (outline) to a PDF in Rust

Build a nested bookmark outline and attach it to any PDF. Bookmarks appear in the navigation panel of PDF viewers and make long documents easier to navigate.
rust
use pdfluent::PdfDocument;
use pdfluent::structure::Outline;

fn main() -> pdfluent::Result<()> {
    let mut doc = PdfDocument::open("report.pdf")?;
    doc.set_outlines(&[
        Outline::new("Introduction", 0),
        Outline::new("Results", 4),
    ])?;
    doc.save("bookmarked.pdf")?;
    Ok(())
}
  1. Step 1

    Open the PDF

    Load the PDF you want to add bookmarks to. The document must already exist; bookmarks reference page indices in the file.

    rust
    use pdfluent::PdfDocument;
    
    let mut doc = PdfDocument::open("manual.pdf")?;
    println!("Pages: {}", doc.page_count());
  2. Step 2

    Build the outline structure

    Create an Outline and add OutlineItem entries. Each item needs a title and a target page index (zero-based). Nest children with .child().

    rust
    use pdfluent::structure::Outline;
    
    let mut part1 = Outline::new("Part I: Basics", 2);
    part1.children.push(Outline::new("Chapter 1", 2));
    part1.children.push(Outline::new("Chapter 2", 6));
    
    let mut part2 = Outline::new("Part II: Advanced", 10);
    part2.children.push(Outline::new("Chapter 3", 10));
    part2.children.push(Outline::new("Chapter 4", 14));
    
    let outline = vec![
        Outline::new("Cover", 0),
        Outline::new("Table of Contents", 1),
        part1,
        part2,
        Outline::new("Index", 18),
    ];
  3. Step 3

    Set the outline on the document

    Call set_outlines() to replace any existing bookmark tree with the new one. The previous outline is discarded.

    rust
    doc.set_outlines(&outline)?;
  4. Step 4

    Save the document

    Write the PDF with the new bookmark tree to disk.

    rust
    doc.save("manual_with_bookmarks.pdf")?;
    println!("Bookmarks written.");
  • Page indices in OutlineItem are zero-based. Page 1 in the viewer is index 0.
  • Nesting depth is unlimited, but most PDF viewers display up to 3-4 levels in the outline panel.
  • set_outlines() replaces the entire outline. To append to an existing outline, read it first with doc.outline(), modify the tree, then set it back.
  • OutlineItem also accepts a named destination with .destination("dest_name") instead of a page index.
Can I link a bookmark to a specific position on a page, not just the page number?
Yes. Use .destination_xy(page, x, y) to jump to specific coordinates on the page, or .destination_fit_rect(page, rect) to zoom the view to a bounding box.
How do I programmatically build bookmarks from a table of contents text file?
Parse the text file to get title and page number pairs, then loop over them to build OutlineItem objects. For nested structures, maintain a stack to track the current depth.
Can bookmarks be bold or italic?
Yes. Call .bold(true) or .italic(true) on an OutlineItem. You can also set a colour with .color(Color::rgb(0.8, 0.0, 0.0)) for red chapter headings.
What happens to bookmarks when I merge PDFs?
PdfMerger can wrap each source document bookmarks under a new top-level entry. Set MergeOptions::with_bookmarks(BookmarkMergeStrategy::Concat) to keep them organised.

Read the bookmark outline from a PDF in Rust

Extract the complete bookmark tree from a PDF. Read titles, page destinations, nesting depth, and link targets for every outline entry.
rust
use pdfluent::PdfDocument;

fn main() -> pdfluent::Result<()> {
    let doc = PdfDocument::open("report.pdf")?;
    for o in doc.outlines()? {
        println!("{} -> page {:?}", o.title, o.page);
    }
    Ok(())
}
  1. Step 1

    Open the PDF

    A read-only borrow is enough to access the outline.

    rust
    use pdfluent::PdfDocument;
    
    let doc = PdfDocument::open("ebook.pdf")?;
  2. Step 2

    Access the outline

    Call doc.outline() which returns an Option<Outline>. It is None if the PDF has no bookmarks.

    rust
    let outlines = doc.outlines()?;
    
    if outlines.is_empty() {
        println!("No bookmarks found in this PDF");
    } else {
        println!("Document has {} top-level bookmarks", outlines.len());
    }
  3. Step 3

    Traverse the bookmark tree

    Each OutlineItem has a title(), page_index(), and a children() slice. Use a recursive function or a stack to walk the full tree.

    rust
    use pdfluent::structure::Outline;
    
    fn walk(items: &[Outline], depth: usize) {
        for item in items {
            let page = item.page.map(|p| p + 1).unwrap_or(0);
            println!("{}{} (page {})", "  ".repeat(depth), item.title, page);
            walk(&item.children, depth + 1);
        }
    }
    
    walk(&doc.outlines()?, 0);
  4. Step 4

    Export the outline to a flat list

    Flatten the nested tree into a Vec for downstream processing such as building a table of contents.

    rust
    use pdfluent::structure::Outline;
    
    #[derive(Debug)]
    struct BookmarkEntry {
        title: String,
        page: usize,
        depth: usize,
    }
    
    fn flatten(items: &[Outline], depth: usize, out: &mut Vec<BookmarkEntry>) {
        for item in items {
            out.push(BookmarkEntry {
                title: item.title.clone(),
                page: item.page.unwrap_or(0),
                depth,
            });
            flatten(&item.children, depth + 1, out);
        }
    }
    
    let mut entries = Vec::new();
    flatten(&doc.outlines()?, 0, &mut entries);
  • page_index() returns a zero-based index. Add 1 to convert to the human-readable page number.
  • Some bookmarks point to named destinations rather than a direct page index. Use item.destination() to read those.
  • Bookmarks can also link to external URIs or other documents. Check item.action_type() before assuming a page target.
  • outline() returns None for PDFs without an /Outlines entry in the document catalog.
How do I check if a bookmark points to an external URL?
Call item.action_type() which returns an OutlineAction enum. If it is OutlineAction::Uri, call item.uri() to get the URL string.
Can I modify the outline tree and save it back?
Yes. Get the outline with doc.outline(), build a modified tree based on it, then call doc.set_outlines(modified_outline). See the add-bookmarks guide for details.
How do I count the total number of bookmarks including nested ones?
Use the flatten approach from Step 5 above. The length of the resulting Vec is the total count of all outline entries across all depths.
Are open/closed states of bookmarks preserved?
Yes. Call item.is_open() to read the initial expansion state. Set .open(false) on an OutlineItem when building an outline to mark it collapsed by default.