resumark 0.1.1

ATS-safe resume typesetting from Markdown — extraction order as a verified contract
Documentation
//! PDF emission over `pdf-writer`.
//!
//! Text is written as Type0/CIDFontType2 with Identity-H encoding and a
//! ToUnicode CMap per font, so extractors recover the exact characters that
//! were laid out. Runs are emitted in their declared `order` — the content
//! stream *is* the extraction contract.

use std::collections::{BTreeMap, BTreeSet, HashMap};

use anyhow::{Context, Result};
use pdf_writer::types::{
    ActionType, AnnotationType, CidFontType, FontFlags, SystemInfo, UnicodeCmap,
};
use pdf_writer::{Content, Finish, Name, Pdf, Rect, Ref, Str, TextStr};
use subsetter::GlyphRemapper;

use crate::fonts::{ALL_ROLES, FontBook};
use crate::layout::Layout;

pub struct DocMeta {
    pub title: String,
    pub author: String,
}

const SUBSET_PREFIX: [&str; 5] = ["AAAAAA", "AAAAAB", "AAAAAC", "AAAAAD", "AAAAAE"];

pub fn write_pdf(layout: &Layout, book: &FontBook, meta: &DocMeta) -> Result<Vec<u8>> {
    // Collect the glyphs each font actually uses, then build a remapper per
    // font: the subset font renumbers glyphs, and text bytes, widths, and
    // ToUnicode must all speak the new numbering.
    let mut used: BTreeMap<usize, BTreeSet<u16>> = BTreeMap::new();
    for page in &layout.pages {
        for t in &page.texts {
            let font = book.get(t.role);
            let set = used.entry(t.role.index()).or_default();
            for c in t.text.chars() {
                if let Some(g) = font.glyph(c) {
                    set.insert(g.gid);
                }
            }
        }
    }
    let mut remappers: BTreeMap<usize, GlyphRemapper> = BTreeMap::new();
    for (&idx, gids) in &used {
        let mut r = GlyphRemapper::new();
        for &gid in gids {
            r.remap(gid);
        }
        remappers.insert(idx, r);
    }

    let mut pdf = Pdf::new();
    let mut alloc = Ref::new(1);
    let catalog_id = alloc.bump();
    let pages_id = alloc.bump();
    let info_id = alloc.bump();

    struct FontRefs {
        type0: Ref,
        cid: Ref,
        descriptor: Ref,
        file: Ref,
        to_unicode: Ref,
    }
    let mut font_refs: BTreeMap<usize, FontRefs> = BTreeMap::new();
    for &idx in used.keys() {
        font_refs.insert(
            idx,
            FontRefs {
                type0: alloc.bump(),
                cid: alloc.bump(),
                descriptor: alloc.bump(),
                file: alloc.bump(),
                to_unicode: alloc.bump(),
            },
        );
    }

    let page_ids: Vec<Ref> = layout.pages.iter().map(|_| alloc.bump()).collect();
    let content_ids: Vec<Ref> = layout.pages.iter().map(|_| alloc.bump()).collect();
    let mut annot_ids: Vec<Vec<Ref>> = Vec::new();
    for page in &layout.pages {
        annot_ids.push(page.links.iter().map(|_| alloc.bump()).collect());
    }

    pdf.catalog(catalog_id).pages(pages_id);
    pdf.pages(pages_id)
        .kids(page_ids.iter().copied())
        .count(page_ids.len() as i32);

    let (w, h) = layout.geom.size;
    for (pi, page) in layout.pages.iter().enumerate() {
        let mut p = pdf.page(page_ids[pi]);
        p.media_box(Rect::new(0.0, 0.0, w, h));
        p.parent(pages_id);
        p.contents(content_ids[pi]);
        {
            let mut resources = p.resources();
            let mut fonts = resources.fonts();
            for role in ALL_ROLES {
                if let Some(fr) = font_refs.get(&role.index()) {
                    fonts.pair(Name(&role.resource_name()), fr.type0);
                }
            }
        }
        if !page.links.is_empty() {
            p.annotations(annot_ids[pi].iter().copied());
        }
        p.finish();

        for (li, link) in page.links.iter().enumerate() {
            let mut a = pdf.annotation(annot_ids[pi][li]);
            a.subtype(AnnotationType::Link);
            a.rect(Rect::new(
                link.rect[0],
                link.rect[1],
                link.rect[2],
                link.rect[3],
            ));
            a.border(0.0, 0.0, 0.0, None);
            a.action()
                .action_type(ActionType::Uri)
                .uri(Str(link.url.as_bytes()));
            a.finish();
        }

        // Content: rules first (under the text), then text runs in declared
        // order — the extraction contract.
        let mut content = Content::new();
        for rule in &page.rules {
            content.set_line_width(rule.width);
            content.set_stroke_rgb(rule.color.0, rule.color.1, rule.color.2);
            content.move_to(rule.x1, rule.y1);
            content.line_to(rule.x2, rule.y2);
            content.stroke();
        }
        let mut texts: Vec<_> = page.texts.iter().collect();
        texts.sort_by_key(|t| t.order);
        for t in texts {
            let font = book.get(t.role);
            let remapper = &remappers[&t.role.index()];
            let mut bytes: Vec<u8> = Vec::with_capacity(t.text.len() * 2);
            for c in t.text.chars() {
                let new_gid = font.glyph(c).and_then(|g| remapper.get(g.gid)).unwrap_or(0);
                bytes.extend_from_slice(&new_gid.to_be_bytes());
            }
            content.begin_text();
            content.set_font(Name(&t.role.resource_name()), t.size);
            content.set_fill_rgb(t.color.0, t.color.1, t.color.2);
            content.next_line(t.x, t.y);
            content.show(Str(&bytes));
            content.end_text();
        }
        pdf.stream(content_ids[pi], &content.finish());
    }

    // Fonts: subset, embed, describe.
    for (&idx, refs) in &font_refs {
        let role = ALL_ROLES[idx];
        let font = book.get(role);
        let remapper = &remappers[&idx];
        let subset = subsetter::subset(&font.data, 0, remapper)
            .map_err(|e| anyhow::anyhow!("subsetting {}: {e:?}", role.postscript_name()))?;

        let base_font = format!("{}+{}", SUBSET_PREFIX[idx], role.postscript_name());

        pdf.type0_font(refs.type0)
            .base_font(Name(base_font.as_bytes()))
            .encoding_predefined(Name(b"Identity-H"))
            .descendant_font(refs.cid)
            .to_unicode(refs.to_unicode);

        let scale = 1000.0 / font.units_per_em;
        // Parse the face once here: the char cmap only covers mapped glyphs,
        // and gid 0 (.notdef) has no char, so advances come from the raw face.
        let face = ttf_parser::Face::parse(&font.data, 0)
            .map_err(|e| anyhow::anyhow!("re-parsing {}: {e}", role.postscript_name()))?;
        // New gids are assigned sequentially, so (old, new) pairs sorted by
        // new gid give one consecutive widths run from 0.
        let mut pairs: Vec<(u16, u16)> = used[&idx]
            .iter()
            .filter_map(|&old| remapper.get(old).map(|new| (old, new)))
            .collect();
        pairs.sort_by_key(|&(_, new)| new);
        let mut width_by_new: HashMap<u16, f32> = HashMap::new();
        for &(old, new) in &pairs {
            let adv = face
                .glyph_hor_advance(ttf_parser::GlyphId(old))
                .unwrap_or(0) as f32;
            width_by_new.insert(new, adv * scale);
        }
        let num_gids = remapper.num_gids();
        let widths: Vec<f32> = (0..num_gids)
            .map(|g| width_by_new.get(&g).copied().unwrap_or(0.0))
            .collect();

        {
            let mut cid = pdf.cid_font(refs.cid);
            cid.subtype(CidFontType::Type2);
            cid.base_font(Name(base_font.as_bytes()));
            cid.system_info(SystemInfo {
                registry: Str(b"Adobe"),
                ordering: Str(b"Identity"),
                supplement: 0,
            });
            cid.font_descriptor(refs.descriptor);
            cid.default_width(0.0);
            cid.cid_to_gid_map_predefined(Name(b"Identity"));
            let mut w = cid.widths();
            w.consecutive(0, widths.iter().copied());
            w.finish();
        }

        let mut desc = pdf.font_descriptor(refs.descriptor);
        desc.name(Name(base_font.as_bytes()));
        desc.flags(FontFlags::NON_SYMBOLIC);
        desc.bbox(Rect::new(
            font.bbox[0] * scale,
            font.bbox[1] * scale,
            font.bbox[2] * scale,
            font.bbox[3] * scale,
        ));
        desc.italic_angle(0.0);
        desc.ascent(font.ascender * scale);
        desc.descent(font.descender * scale);
        desc.cap_height(font.cap_height * scale);
        desc.stem_v(80.0);
        desc.font_file2(refs.file);
        desc.finish();

        let mut stream = pdf.stream(refs.file, &subset);
        stream.pair(Name(b"Length1"), subset.len() as i32);
        stream.finish();

        let mut cmap = UnicodeCmap::new(
            Name(b"ResumarkToUnicode"),
            SystemInfo {
                registry: Str(b"Adobe"),
                ordering: Str(b"Identity"),
                supplement: 0,
            },
        );
        for &(old, new) in &pairs {
            if let Some(c) = font.char_for_gid(old) {
                cmap.pair(new, c);
            }
        }
        pdf.cmap(refs.to_unicode, &cmap.finish());
    }

    pdf.document_info(info_id)
        .title(TextStr(&meta.title))
        .author(TextStr(&meta.author))
        .creator(TextStr("resumark"))
        .producer(TextStr(concat!("resumark ", env!("CARGO_PKG_VERSION"))));

    Ok(pdf.finish())
}

/// Convenience wrapper: render markdown source all the way to PDF bytes.
pub fn render_bytes(
    md: &str,
    book: &FontBook,
    geom: crate::layout::PageGeom,
    max_pages: usize,
    fixed_scale: Option<f32>,
) -> Result<(Vec<u8>, Layout)> {
    let doc = crate::parse::parse(md);
    let layout = crate::fit::autofit(&doc, book, geom, max_pages, fixed_scale);
    let meta = DocMeta {
        title: format!("{} - Resume", doc.name),
        author: doc.name.clone(),
    };
    let bytes = write_pdf(&layout, book, &meta).context("writing PDF")?;
    Ok((bytes, layout))
}