Files
texrra-engine/crates/texrra-tex-core/src/pdf.rs
T

1689 lines
57 KiB
Rust
Executable File

//! Minimal PDF writer for route-D display lists.
//!
//! Embedded true-type text faces, filled rectangles,
//! and raw-RGB image XObjects.
use std::collections::BTreeSet;
use std::collections::{BTreeMap, HashMap};
use std::io::Write as _;
use std::sync::OnceLock;
use flate2::Compression;
use flate2::write::ZlibEncoder;
use rusttype::Font;
use crate::cmr10::Cmr10Metrics;
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
const FACE_COUNT: usize = 17;
fn deflate(bytes: &[u8]) -> Vec<u8> {
let mut encoder = ZlibEncoder::new(Vec::new(), Compression::default());
encoder.write_all(bytes).expect("deflate font stream");
encoder.finish().expect("finish font stream")
}
struct PdfFace {
bytes: &'static [u8],
base: &'static str,
italic_angle: i32,
font: OnceLock<Font<'static>>,
}
static FULL_FACES: [PdfFace; FACE_COUNT] = [
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Bold.ttf"),
base: "LiberationSerif-Bold",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-BoldItalic.ttf"),
base: "LiberationSerif-BoldItalic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationMono-Regular.ttf"),
base: "LiberationMono",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Regular.ttf"),
base: "LiberationSans",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-MathItalic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathSymbol",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathExtension",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathBlackboard",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathFraktur",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Bold.ttf"),
base: "LiberationSans-Bold",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSans-Italic.ttf"),
base: "LiberationSans-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-SmallCaps",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-Slanted",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationSerif-BoldItalic.ttf"),
base: "LiberationSerif-BoldSlanted",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset/LiberationMono-Italic.ttf"),
base: "LiberationMono-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
];
static MIN_FACES: [PdfFace; FACE_COUNT] = [
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Bold.ttf"),
base: "LiberationSerif-Bold",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-BoldItalic.ttf"),
base: "LiberationSerif-BoldItalic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationMono-Regular.ttf"),
base: "LiberationMono",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Regular.ttf"),
base: "LiberationSans",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-MathItalic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathSymbol",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathExtension",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathBlackboard",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-MathFraktur",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Bold.ttf"),
base: "LiberationSans-Bold",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSans-Italic.ttf"),
base: "LiberationSans-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Regular.ttf"),
base: "LiberationSerif-SmallCaps",
italic_angle: 0,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-Italic.ttf"),
base: "LiberationSerif-Slanted",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationSerif-BoldItalic.ttf"),
base: "LiberationSerif-BoldSlanted",
italic_angle: -12,
font: OnceLock::new(),
},
PdfFace {
bytes: include_bytes!("../../../assets/fonts-subset-min/LiberationMono-Italic.ttf"),
base: "LiberationMono-Italic",
italic_angle: -12,
font: OnceLock::new(),
},
];
fn minimal_text_char(ch: char) -> bool {
ch.is_ascii()
|| matches!(
ch,
'\u{00A0}'
| '\u{00A9}'
| '\u{00AE}'
| '\u{00B0}'
| '\u{00B1}'
| '\u{00B5}'
| '\u{00B7}'
| '\u{00D7}'
| '\u{2013}'
| '\u{2014}'
| '\u{2018}'
| '\u{2019}'
| '\u{201C}'
| '\u{201D}'
| '\u{2022}'
| '\u{2026}'
| '\u{00B9}'
| '\u{00B2}'
| '\u{00B3}'
| '\u{2070}'..='\u{2079}' | '\u{2248}' | '\u{223C}' | '\u{03BC}'
)
}
fn face(font: FontFace, faces: &'static [PdfFace; FACE_COUNT]) -> &'static PdfFace {
&faces[font as usize]
}
#[allow(dead_code)]
pub(crate) fn full_face_size(font: FontFace) -> usize {
FULL_FACES[font as usize].bytes.len()
}
fn face_font(face: &'static PdfFace) -> &'static Font<'static> {
face.font
.get_or_init(|| Font::from_bytes(face.bytes).expect("embedded face"))
}
fn glyph_hex(face: &'static PdfFace, text: &str) -> String {
let font = face_font(face);
let mut out = String::new();
for character in text.chars() {
let id = font.glyph(character).id().0;
out.push_str(&format!("{id:04X}"));
}
out
}
fn tounicode_cmap(face: &'static PdfFace, characters: &BTreeSet<char>) -> Vec<u8> {
let font = face_font(face);
let mut map = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n /CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n 1 begincodespacerange\n<0000> <FFFF>\nendcodespacerange\n",
);
let mut entries = std::collections::BTreeMap::new();
for character in characters {
if (*character as u32) <= 0xffff {
entries.insert(font.glyph(*character).id().0, *character);
}
}
map.push_str(&format!("{} beginbfchar\n", entries.len()));
for (id, character) in entries {
map.push_str(&format!("<{id:04X}> <{:04X}>\n", character as u32));
}
map.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
map.into_bytes()
}
/// ToUnicode CMap for a single-byte Type1 font. Glyph names are ambiguous
/// (`Omega` in the Adobe Glyph List is the ohm sign), so the requested
/// characters are mapped explicitly.
fn type1_tounicode(by_code: &BTreeMap<u8, char>) -> Vec<u8> {
let mut map = String::from(
"/CIDInit /ProcSet findresource begin\n12 dict begin\nbegincmap\n /CIDSystemInfo << /Registry (Adobe) /Ordering (UCS) /Supplement 0 >> def\n /CMapName /Adobe-Identity-UCS def\n/CMapType 2 def\n 1 begincodespacerange\n<00> <FF>\nendcodespacerange\n",
);
let entries: Vec<(&u8, &char)> = by_code
.iter()
.filter(|(_, character)| (**character as u32) <= 0xffff)
.collect();
map.push_str(&format!("{} beginbfchar\n", entries.len()));
for (code, character) in entries {
map.push_str(&format!("<{code:02X}> <{:04X}>\n", *character as u32));
}
map.push_str("endbfchar\nendcmap\nCMapName currentdict /CMap defineresource pop\nend\nend\n");
map.into_bytes()
}
fn cid_widths(
face: &'static PdfFace,
slot: usize,
used: &std::collections::BTreeSet<char>,
) -> String {
let font = face_font(face);
let metrics = Cmr10Metrics::for_pdf_slot(slot);
let mut entries = Vec::new();
let mut characters = used.clone();
characters.extend((0x20u8..=0x7e).map(char::from));
for character in characters {
if character.is_control() {
continue;
}
let glyph = font.glyph(character);
let id = glyph.id().0;
let width = metrics.width(character) * 1000 / (10 * 65_536);
entries.push((id, width));
}
entries.sort_unstable();
entries.dedup_by_key(|(id, _)| *id);
let mut out = String::from("[");
for (id, width) in entries {
out.push_str(&format!(" {id} [{width}]"));
}
out.push_str(" ]");
out
}
fn escape(text: &str) -> String {
let mut out = String::new();
for character in text.chars() {
match character {
'(' => out.push_str("\\("),
')' => out.push_str("\\)"),
'\\' => out.push_str("\\\\"),
c if c.is_ascii() => out.push(c),
c if (c as u32) <= 0xFF => out.push_str(&format!("\\{:03o}", c as u32)),
_ => out.push('?'),
}
}
out
}
fn pt(value: i64) -> String {
format!("{:.3}", value as f64 / 65_536.0)
}
fn font_resource(font: FontFace) -> &'static str {
match font {
FontFace::Roman => "F1",
FontFace::Bold => "F2",
FontFace::Italic => "F3",
FontFace::BoldItalic => "F4",
FontFace::Mono => "F5",
FontFace::Sans => "F6",
FontFace::MathItalic => "F7",
FontFace::MathSymbol => "F8",
FontFace::MathExtension => "F9",
FontFace::MathBlackboard => "F10",
FontFace::MathFraktur => "F11",
FontFace::SansBold => "F12",
FontFace::SansItalic => "F13",
FontFace::SmallCaps => "F14",
FontFace::Slanted => "F15",
FontFace::BoldSlanted => "F16",
FontFace::MonoItalic => "F17",
}
}
/// Which outline format the PDF writer embeds for text.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum FontBackend {
/// Embedded Liberation TrueType subsets (the default).
TrueType,
/// Knuth's Computer Modern Type1 programs when they cover the text.
ComputerModern,
}
/// Knuth's Computer Modern Type1 programs, in `FontFace` order.
fn type1_bytes(slot: usize) -> Option<&'static [u8]> {
static PFBS: [Option<&'static [u8]>; FACE_COUNT] = [
Some(include_bytes!("../../../assets/fonts/cmr10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmbx10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmti10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmbxti10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmtt10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmss10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmmi10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmsy10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmex10.pfb")),
Some(include_bytes!("../../../assets/fonts/msbm10.pfb")),
Some(include_bytes!("../../../assets/fonts/eufm10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmssbx10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmssi10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmcsc10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmsl10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmbxsl10.pfb")),
Some(include_bytes!("../../../assets/fonts/cmitt10.pfb")),
];
PFBS[slot]
}
fn type1_fonts() -> &'static [Option<Type1Font>; FACE_COUNT] {
static FONTS: OnceLock<[Option<Type1Font>; FACE_COUNT]> = OnceLock::new();
FONTS
.get_or_init(|| std::array::from_fn(|slot| type1_bytes(slot).and_then(Type1Font::from_pfb)))
}
/// TeX page origin offsets (`\hoffset`, `\voffset`) in scaled points.
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct PageOrigin {
pub h_offset: i64,
pub v_offset: i64,
}
fn write_type0_font(
objects: &mut Vec<Vec<u8>>,
face: &'static PdfFace,
slot: usize,
used: &BTreeSet<char>,
) -> usize {
let type0_id = objects.len() + 1;
let cid_id = type0_id + 1;
let descriptor_id = type0_id + 2;
let file_id = type0_id + 3;
let tounicode_id = type0_id + 4;
let base = face.base;
objects.push(
format!(
"<< /Type /Font /Subtype /Type0 /BaseFont /{base} /Encoding /Identity-H /DescendantFonts [{cid_id} 0 R] /ToUnicode {tounicode_id} 0 R >>"
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /Font /Subtype /CIDFontType2 /BaseFont /{base} /CIDSystemInfo << /Registry (Adobe) /Ordering (Identity) /Supplement 0 >> /FontDescriptor {descriptor_id} 0 R /DW 500 /W {} >>",
cid_widths(face, slot, used)
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{base} /Flags 32 /FontBBox [-500 -300 1200 1000] /ItalicAngle {} /Ascent 900 /Descent -250 /CapHeight 700 /StemV 80 /FontFile2 {file_id} 0 R >>",
face.italic_angle
)
.into_bytes(),
);
let font_bytes = crate::subset::subset_font(face.bytes, face_font(face), used);
let compressed = deflate(&font_bytes);
let mut font_stream = format!(
"<< /Length {} /Length1 {} /Filter /FlateDecode >>\nstream\n",
compressed.len(),
font_bytes.len()
)
.into_bytes();
font_stream.extend_from_slice(&compressed);
font_stream.extend_from_slice(b"\nendstream");
objects.push(font_stream);
let cmap = tounicode_cmap(face, used);
let compressed_cmap = deflate(&cmap);
let mut cmap_object = format!(
"<< /Length {} /Filter /FlateDecode >>\nstream\n",
compressed_cmap.len()
)
.into_bytes();
cmap_object.extend_from_slice(&compressed_cmap);
cmap_object.extend_from_slice(b"\nendstream");
objects.push(cmap_object);
type0_id
}
fn page_content(
list: &DisplayList,
height: i64,
image_names: &BTreeMap<usize, String>,
faces: &'static [PdfFace; FACE_COUNT],
cm_codes: &[Option<&BTreeMap<char, u8>>],
fallback_ids: &[usize; FACE_COUNT],
origin: PageOrigin,
) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
if let Some(DisplayItem::Background(color)) = list.items.first() {
content.push_str(&format!(
"{:.3} {:.3} {:.3} rg\n0 0 {} {} re f\n0 0 0 rg\n",
color[0] as f64 / 255.0,
color[1] as f64 / 255.0,
color[2] as f64 / 255.0,
pt(list.width),
pt(height)
));
}
if origin != PageOrigin::default() {
content.push_str(&format!(
"1 0 0 1 {} {} cm\n",
pt(origin.h_offset),
pt(-origin.v_offset)
));
}
for item in &list.items {
match item {
DisplayItem::Text {
x,
y,
size,
text,
font,
} => {
let slot = *font as usize;
let covered = cm_codes
.get(slot)
.and_then(|entry| entry.as_ref())
.filter(|codes| text.chars().all(|character| codes.contains_key(&character)));
let (operand, resource) = match covered {
Some(codes) => {
let mut literal = String::from("(");
for character in text.chars() {
if let Some(code) = codes.get(&character) {
literal.push_str(&format!("\\{:03o}", code));
}
}
literal.push(')');
(literal, font_resource(*font).to_string())
}
None if fallback_ids[slot] != 0 => (
format!("<{}>", glyph_hex(face(*font, faces), text)),
format!("T{}", slot + 1),
),
None => (
format!("<{}>", glyph_hex(face(*font, faces), text)),
font_resource(*font).to_string(),
),
};
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
resource,
pt(*size),
pt(*x),
pt(height - *y),
operand
));
}
DisplayItem::Background(_) => {}
DisplayItem::Rule {
x,
y,
width,
height: rule_height,
} => {
content.push_str(&format!(
"{} {} {} {} re f\n",
pt(*x),
pt(height - *y - *rule_height),
pt(*width),
pt(*rule_height)
));
}
DisplayItem::Line {
x1,
y1,
x2,
y2,
width: line_width,
} => {
content.push_str(&format!(
"{} w {} {} m {} {} l S\n",
pt(*line_width),
pt(*x1),
pt(height - *y1),
pt(*x2),
pt(height - *y2)
));
}
DisplayItem::Image {
x,
y,
width,
height: image_height,
index,
} => {
if let Some(name) = image_names.get(index) {
content.push_str(&format!(
"q {} 0 0 {} {} {} cm /{name} Do Q\n",
pt(*width),
pt(*image_height),
pt(*x),
pt(height - *y - *image_height)
));
}
}
DisplayItem::Link { .. } => {}
DisplayItem::Fill([r, g, b]) => {
content.push_str(&format!(
"{:.3} {:.3} {:.3} rg\n",
*r as f64 / 255.0,
*g as f64 / 255.0,
*b as f64 / 255.0
));
}
DisplayItem::Special(special) => {
content.push_str(special);
content.push('\n');
}
}
}
content.push_str("Q\n");
content
}
/// Document information written into the PDF Info dictionary.
#[derive(Clone, Debug, Default, PartialEq, Eq)]
pub struct PdfMetadata {
pub title: Option<String>,
pub author: Option<String>,
pub subject: Option<String>,
pub keywords: Option<String>,
pub outline: Vec<PdfOutlineEntry>,
/// Border and colour for URI link annotations, when set.
pub link_border: Option<[u8; 3]>,
}
/// One flat bookmark pointing at a page of the exported document.
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct PdfOutlineEntry {
pub title: String,
pub page: usize,
/// Heading depth, with 1 as the top level.
pub level: u8,
}
fn pdf_text(value: &str) -> String {
if value.chars().all(|character| {
(' '..='~').contains(&character)
&& character != '('
&& character != ')'
&& character != '\\'
}) {
format!("({value})")
} else {
let mut text = String::from("<FEFF");
for unit in value.encode_utf16() {
text.push_str(&format!("{unit:04X}"));
}
text.push('>');
text
}
}
fn metadata_object(metadata: &PdfMetadata) -> Option<String> {
let mut fields = Vec::new();
if let Some(title) = &metadata.title {
fields.push(format!("/Title {}", pdf_text(title)));
}
if let Some(author) = &metadata.author {
fields.push(format!("/Author {}", pdf_text(author)));
}
if let Some(subject) = &metadata.subject {
fields.push(format!("/Subject {}", pdf_text(subject)));
}
if let Some(keywords) = &metadata.keywords {
fields.push(format!("/Keywords {}", pdf_text(keywords)));
}
if fields.is_empty() {
return None;
}
fields.push("/Producer (texrra route-D)".to_string());
fields.push("/Creator (texrra route-D)".to_string());
Some(format!("<< {} >>", fields.join(" ")))
}
/// Write several display lists as a multi-page PDF at the default page origin.
pub fn display_lists_to_pdf(pages: &[DisplayList], page_height: i64) -> Vec<u8> {
display_lists_to_pdf_with_origin(pages, page_height, PageOrigin::default())
}
/// Write several display lists as a multi-page PDF, translating the page body
/// by TeX page origin offsets.
pub fn display_lists_to_pdf_with_origin(
pages: &[DisplayList],
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
display_lists_to_pdf_with_paper(
pages,
pages
.iter()
.map(|page| page.width)
.max()
.unwrap_or(612 * 65_536)
.max(612 * 65_536),
page_height.max(792 * 65_536),
origin,
)
}
/// Write several display lists as a multi-page PDF with an explicit paper
/// size (TeX `\paperwidth`/`\paperheight`) and page origin offsets.
pub fn display_lists_to_pdf_with_paper(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::TrueType,
&PdfMetadata::default(),
)
}
fn descendant_count(children: &HashMap<usize, Vec<usize>>, node: usize) -> usize {
children
.get(&node)
.map(|kids| {
kids.iter()
.map(|kid| 1 + descendant_count(children, *kid))
.sum()
})
.unwrap_or(0)
}
/// Write PDFs with Knuth's Computer Modern Type1 outlines whenever the programs
/// cover the text, falling back to Liberation TrueType for other characters.
pub fn display_lists_to_pdf_with_cm_type1(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::ComputerModern,
&PdfMetadata::default(),
)
}
/// Write PDFs with Computer Modern Type1 outlines and a document Info dictionary.
pub fn display_lists_to_pdf_with_cm_type1_and_metadata(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
metadata: &PdfMetadata,
) -> Vec<u8> {
write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::ComputerModern,
metadata,
)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
backend: FontBackend,
metadata: &PdfMetadata,
) -> Vec<u8> {
let width = page_width;
let height = page_height;
let mut objects: Vec<Vec<u8>> = Vec::new();
objects.push(b"<< /Type /Catalog /Pages 2 0 R >>".to_vec());
objects.push(Vec::new()); // pages object filled below
let mut used_faces = [false; FACE_COUNT];
let mut used_chars: [BTreeSet<char>; FACE_COUNT] = Default::default();
for page in pages {
for item in &page.items {
if let DisplayItem::Text { font, text, .. } = item {
used_faces[*font as usize] = true;
used_chars[*font as usize].extend(text.chars());
}
}
}
let cm_faces: Vec<Option<(&'static Type1Font, BTreeMap<char, u8>)>> = (0..FACE_COUNT)
.map(|slot| {
if backend != FontBackend::ComputerModern || !used_faces[slot] {
return None;
}
let font = type1_fonts()[slot].as_ref()?;
if slot == FontFace::MathSymbol as usize || slot == FontFace::MathExtension as usize {
let codes = used_chars[slot]
.iter()
.filter_map(|character| {
let code = if slot == FontFace::MathSymbol as usize {
crate::cmr10::math_symbol_slot(*character).or_else(|| {
character.is_ascii_uppercase().then_some(*character as u8)
})
} else {
crate::cmr10::math_extension_slot(*character)
};
code.map(|code| (*character, code))
})
.collect();
return Some((font, codes));
}
let codes = used_chars[slot]
.iter()
.filter_map(|character| font.code_for(*character).map(|code| (*character, code)))
.collect();
Some((font, codes))
})
.collect();
let cm_views: Vec<Option<&BTreeMap<char, u8>>> = cm_faces
.iter()
.map(|entry| entry.as_ref().map(|(_, codes)| codes))
.collect();
let mut fallback_chars: [BTreeSet<char>; FACE_COUNT] = Default::default();
for slot in 0..FACE_COUNT {
if let Some((_, codes)) = &cm_faces[slot] {
for character in &used_chars[slot] {
if !codes.contains_key(character) {
fallback_chars[slot].insert(*character);
}
}
}
}
let minimal = pages.iter().all(|page| {
page.items.iter().all(|item| match item {
DisplayItem::Text { text, .. } => text.chars().all(minimal_text_char),
_ => true,
})
});
let faces: &'static [PdfFace; FACE_COUNT] = if minimal { &MIN_FACES } else { &FULL_FACES };
let mut font_ids = [0usize; FACE_COUNT];
let mut fallback_font_ids = [0usize; FACE_COUNT];
for (slot, face) in faces.iter().enumerate() {
if !used_faces[slot] {
continue;
}
if let Some((font, codes)) = &cm_faces[slot] {
let font_id = objects.len() + 1;
let descriptor_id = font_id + 1;
let file_id = font_id + 2;
let tounicode_id = font_id + 3;
font_ids[slot] = font_id;
let metrics = Cmr10Metrics::for_pdf_slot(slot);
let mut by_code = BTreeMap::new();
for (character, code) in codes {
by_code.insert(*code, *character);
}
let first = *by_code.keys().next().unwrap_or(&32);
let last = *by_code.keys().next_back().unwrap_or(&32);
let mut widths = Vec::new();
let mut differences = Vec::new();
let mut next_code = first;
for code in first..=last {
let width = by_code.get(&code).map_or(0, |character| {
let width = match slot {
slot if slot == FontFace::MathSymbol as usize => {
crate::cmr10::math_symbol_width(*character)
.unwrap_or_else(|| metrics.width(*character))
}
slot if slot == FontFace::MathExtension as usize => {
crate::cmr10::math_extension_width(*character)
.unwrap_or_else(|| metrics.width(*character))
}
_ => metrics.width(*character),
};
(width * 100 / 65_536) as i64
});
widths.push(width.to_string());
let glyph = if slot == FontFace::MathSymbol as usize
|| slot == FontFace::MathExtension as usize
{
font.name_for_code(code).map(|name| (code, name))
} else {
by_code
.get(&code)
.and_then(|character| font.code_and_name_for(*character))
};
if let Some((code, name)) = glyph {
if code != next_code {
differences.push(code.to_string());
}
differences.push(format!("/{name}"));
next_code = code + 1;
}
}
objects.push(
format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{}] /Encoding << /Type /Encoding /Differences [{}] >> /FontDescriptor {descriptor_id} 0 R /ToUnicode {tounicode_id} 0 R >>",
font.name,
widths.join(" "),
differences.join(" ")
)
.into_bytes(),
);
objects.push(
format!(
"<< /Type /FontDescriptor /FontName /{} /Flags 34 /FontBBox [-40 -250 1009 750] /ItalicAngle 0 /Ascent 694 /Descent -194 /CapHeight 683 /StemV 69 /FontFile {file_id} 0 R >>",
font.name
)
.into_bytes(),
);
let mut stream = format!(
"<< /Length {} /Length1 {} /Length2 {} /Length3 {} >>\nstream\n",
font.program.len(),
font.length1,
font.length2,
font.length3
)
.into_bytes();
stream.extend_from_slice(&font.program);
stream.extend_from_slice(b"\nendstream");
objects.push(stream);
let cmap = type1_tounicode(&by_code);
let mut cmap_object = format!("<< /Length {} >>\nstream\n", cmap.len()).into_bytes();
cmap_object.extend_from_slice(&cmap);
cmap_object.extend_from_slice(b"\nendstream");
objects.push(cmap_object);
if !fallback_chars[slot].is_empty() {
fallback_font_ids[slot] =
write_type0_font(&mut objects, face, slot, &fallback_chars[slot]);
}
continue;
}
font_ids[slot] = write_type0_font(&mut objects, face, slot, &used_chars[slot]);
}
let mut kids = Vec::new();
let mut page_ids: Vec<usize> = Vec::new();
for list in pages {
let mut used = BTreeMap::new();
for item in &list.items {
if let DisplayItem::Image { index, .. } = item {
let next = used.len();
used.entry(*index).or_insert(next);
}
}
let page_id = objects.len() + 1;
let content_id = page_id + 1;
let image_base = content_id + 1;
let xobjects = used
.iter()
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
.collect::<Vec<_>>()
.join(" ");
let fonts = (0..FACE_COUNT)
.filter(|slot| used_faces[*slot])
.flat_map(|slot| {
let mut entries = Vec::new();
if font_ids[slot] != 0 {
entries.push(format!("/F{} {} 0 R", slot + 1, font_ids[slot]));
}
if fallback_font_ids[slot] != 0 {
entries.push(format!("/T{} {} 0 R", slot + 1, fallback_font_ids[slot]));
}
entries
})
.collect::<Vec<_>>()
.join(" ");
let resources = if used.is_empty() {
format!("<< /Font << {fonts} >> >>")
} else {
format!("<< /Font << {fonts} >> /XObject << {xobjects} >> >>")
};
let links = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::Link {
x,
y,
width,
height,
url,
} => Some((*x, *y, *width, *height, url.clone())),
_ => None,
})
.collect::<Vec<_>>();
let annotation_base = image_base + used.len();
let annots = if links.is_empty() {
String::new()
} else {
let refs = (0..links.len())
.map(|index| {
format!("/Annots [{}]", (annotation_base + index))
.replace("/Annots [", "")
.replacen("]", "", 1)
})
.collect::<Vec<_>>()
.join(" ");
format!(" /Annots [{refs}]")
};
page_ids.push(page_id);
kids.push(format!("{page_id} 0 R"));
objects.push(
format!(
"<< /Type /Page /Parent 2 0 R /MediaBox [0 0 {} {}] /Resources {resources}{annots} /Contents {content_id} 0 R >>",
pt(width),
pt(height)
)
.into_bytes(),
);
let mut names = BTreeMap::new();
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let content = page_content(
list,
height,
&names,
faces,
&cm_views,
&fallback_font_ids,
origin,
);
objects.push(
format!(
"<< /Length {} >>\nstream\n{}endstream",
content.len(),
content
)
.into_bytes(),
);
for (index, _) in &used {
let image = &list.images[*index];
let mut object = format!(
"<< /Type /XObject /Subtype /Image /Width {} /Height {} /ColorSpace /DeviceRGB /BitsPerComponent 8 /Length {} >>\nstream\n",
image.width,
image.height,
image.rgb.len()
)
.into_bytes();
object.extend_from_slice(&image.rgb);
object.extend_from_slice(b"\nendstream");
objects.push(object);
}
let link_border = match metadata.link_border {
Some([red, green, blue]) => format!(
"/Border [0 0 1] /C [{:.3} {:.3} {:.3}]",
red as f64 / 255.0,
green as f64 / 255.0,
blue as f64 / 255.0
),
None => "/Border [0 0 0]".to_string(),
};
for (index, (x, y, width, link_height, url)) in links.iter().enumerate() {
let _ = index;
objects.push(
format!(
"<< /Type /Annot /Subtype /Link /Rect [{:.3} {:.3} {:.3} {:.3}] {link_border} /A << /S /URI /URI ({}) >> >>",
*x as f64 / 65_536.0,
(height as f64 - *y as f64 - *link_height as f64) / 65_536.0,
(*x + *width) as f64 / 65_536.0,
(height as f64 - *y as f64) / 65_536.0,
escape(url)
)
.into_bytes(),
);
}
}
objects[1] = format!(
"<< /Type /Pages /Kids [{}] /Count {} >>",
kids.join(" "),
pages.len()
)
.into_bytes();
if !metadata.outline.is_empty() {
let root_id = objects.len() + 1;
objects.push(Vec::new());
let item_ids: Vec<usize> = (0..metadata.outline.len())
.map(|_| {
objects.push(Vec::new());
objects.len()
})
.collect();
// Nest entries by heading level: an entry is a child of the nearest
// preceding entry with a strictly smaller level.
let mut parents: Vec<Option<usize>> = vec![None; metadata.outline.len()];
let mut stack: Vec<usize> = Vec::new();
let mut children: HashMap<usize, Vec<usize>> = HashMap::new();
for index in 0..metadata.outline.len() {
let level = metadata.outline[index].level;
while let Some(&top) = stack.last() {
if metadata.outline[top].level >= level {
stack.pop();
} else {
break;
}
}
let parent = stack.last().copied();
parents[index] = parent;
children
.entry(parent.unwrap_or(usize::MAX))
.or_default()
.push(index);
stack.push(index);
}
for (index, entry) in metadata.outline.iter().enumerate() {
let page_id = page_ids
.get(entry.page)
.or_else(|| page_ids.last())
.copied()
.unwrap_or(0);
let parent_id = parents[index].map_or(root_id, |parent| item_ids[parent]);
let mut dict = format!(
"<< /Title {} /Parent {} 0 R /Dest [{} 0 R /Fit]",
pdf_text(&entry.title),
parent_id,
page_id
);
let siblings = &children[&parents[index].unwrap_or(usize::MAX)];
if let Some(position) = siblings.iter().position(|candidate| *candidate == index) {
if position > 0 {
dict.push_str(&format!(" /Prev {} 0 R", item_ids[siblings[position - 1]]));
}
if position + 1 < siblings.len() {
dict.push_str(&format!(" /Next {} 0 R", item_ids[siblings[position + 1]]));
}
}
if let Some(kids) = children.get(&index) {
if !kids.is_empty() {
dict.push_str(&format!(
" /First {} 0 R /Last {} 0 R /Count {}",
item_ids[kids[0]],
item_ids[kids[kids.len() - 1]],
descendant_count(&children, index)
));
}
}
dict.push_str(" >>");
objects[item_ids[index] - 1] = dict.into_bytes();
}
let roots = &children[&usize::MAX];
objects[root_id - 1] = format!(
"<< /Type /Outlines /First {} 0 R /Last {} 0 R /Count {} >>",
item_ids[roots[0]],
item_ids[roots[roots.len() - 1]],
metadata.outline.len()
)
.into_bytes();
objects[0] =
format!("<< /Type /Catalog /Pages 2 0 R /Outlines {root_id} 0 R >>").into_bytes();
}
let info_ref = match metadata_object(metadata) {
Some(object) => {
objects.push(object.into_bytes());
format!(" /Info {} 0 R", objects.len())
}
None => String::new(),
};
let mut pdf: Vec<u8> = b"%PDF-1.4\n".to_vec();
let mut offsets = Vec::new();
for (index, object) in objects.iter().enumerate() {
offsets.push(pdf.len());
pdf.extend_from_slice(format!("{} 0 obj\n", index + 1).as_bytes());
pdf.extend_from_slice(object);
pdf.extend_from_slice(b"\nendobj\n");
}
let xref = pdf.len();
pdf.extend_from_slice(
format!("xref\n0 {}\n0000000000 65535 f \n", objects.len() + 1).as_bytes(),
);
for offset in &offsets {
pdf.extend_from_slice(format!("{:010} 00000 n \n", offset).as_bytes());
}
pdf.extend_from_slice(
format!(
"trailer\n<< /Size {} /Root 1 0 R{} >>\nstartxref\n{}\n%%EOF\n",
objects.len() + 1,
info_ref,
xref
)
.as_bytes(),
);
pdf
}
/// Write one page; kept for the single-page spike and tests.
pub fn display_list_to_pdf(list: &DisplayList, page_height: i64) -> Vec<u8> {
display_lists_to_pdf(std::slice::from_ref(list), page_height)
}
#[cfg(test)]
mod tests {
use super::{FULL_FACES, cid_widths, escape, face_font};
use std::collections::BTreeSet;
#[test]
fn widths_cover_used_latin1_characters() {
let face = &FULL_FACES[0];
let accent = char::from_u32(0xe9).unwrap();
let id = face_font(face).glyph(accent).id().0;
let mut used = BTreeSet::new();
used.insert(accent);
let widths = cid_widths(face, 0, &used);
assert!(widths.contains(&format!("{id} [500]")), "{widths}");
}
#[test]
fn latin1_text_is_octal_escaped_in_the_content_stream() {
assert_eq!(escape("café"), "caf\\351");
assert_eq!(escape("über"), "\\374ber");
assert_eq!(escape("中文"), "??");
}
}
#[cfg(test)]
mod type1_pdf_tests {
use super::*;
fn hello_list() -> DisplayList {
let mut list = DisplayList {
width: 200 * 65_536,
height: 100 * 65_536,
items: Vec::new(),
images: Vec::new(),
};
list.push(DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Hi".to_string(),
font: FontFace::Roman,
});
list
}
fn write(list: &[DisplayList]) -> Vec<u8> {
display_lists_to_pdf_with_cm_type1(list, 200 * 65_536, 800 * 65_536, PageOrigin::default())
}
#[test]
fn type1_fonts_map_omega_to_the_requested_code() {
let font = type1_fonts()[0].as_ref().expect("cmr10 type1 program");
let code = font.code_for('\u{3a9}').expect("omega in cmr10");
let mut by_code = std::collections::BTreeMap::new();
by_code.insert(code, '\u{3a9}');
let cmap = String::from_utf8_lossy(&type1_tounicode(&by_code)).to_string();
assert!(cmap.contains(&format!("<{code:02X}> <03A9>")), "{cmap}");
}
#[test]
fn outline_entries_become_pdf_bookmarks() {
let pages = vec![
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
];
let metadata = PdfMetadata {
title: Some("Book".into()),
outline: vec![
PdfOutlineEntry {
title: "1 One".into(),
page: 0,
level: 1,
},
PdfOutlineEntry {
title: "2 Two".into(),
page: 1,
level: 1,
},
],
..PdfMetadata::default()
};
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
&pages,
612 * 65536,
792 * 65536,
PageOrigin::default(),
&metadata,
))
.to_string();
assert!(pdf.contains("/Type /Outlines"));
assert!(pdf.contains("/Title (1 One)"));
assert!(pdf.contains("/Title (2 Two)"));
assert!(pdf.contains("/Count 2"));
assert!(pdf.contains("/Dest ["));
assert!(pdf.contains("/Outlines"));
}
fn metadata_writes_the_pdf_info_dictionary() {
let pages = vec![DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
}];
let metadata = PdfMetadata {
title: Some("Plain Title".into()),
author: Some("Ada".into()),
subject: None,
keywords: None,
outline: Vec::new(),
link_border: None,
};
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
&pages,
612 * 65536,
792 * 65536,
PageOrigin::default(),
&metadata,
))
.to_string();
assert!(pdf.contains("/Title (Plain Title)"));
assert!(pdf.contains("/Author (Ada)"));
assert!(pdf.contains("/Producer (texrra route-D)"));
assert!(pdf.contains("/Info"));
let unicode = PdfMetadata {
title: Some("Ωmega".into()),
..PdfMetadata::default()
};
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
&pages,
612 * 65536,
792 * 65536,
PageOrigin::default(),
&unicode,
))
.to_string();
assert!(pdf.contains("/Title <FEFF03A9"));
}
#[test]
fn nested_outline_entries_nest_by_level() {
let pages = vec![
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
},
];
let metadata = PdfMetadata {
outline: vec![
PdfOutlineEntry {
title: "1 One".into(),
page: 0,
level: 1,
},
PdfOutlineEntry {
title: "1.1 Sub".into(),
page: 0,
level: 2,
},
PdfOutlineEntry {
title: "2 Two".into(),
page: 1,
level: 1,
},
],
..PdfMetadata::default()
};
let pdf = String::from_utf8_lossy(&display_lists_to_pdf_with_cm_type1_and_metadata(
&pages,
612 * 65536,
792 * 65536,
PageOrigin::default(),
&metadata,
))
.to_string();
assert!(pdf.contains("/Title (1.1 Sub)"));
assert!(pdf.contains("/Count 3"));
assert!(pdf.contains("/First"));
assert!(pdf.contains("/Last"));
}
fn type1_backend_embeds_computer_modern_outlines() {
let pdf = write(&[hello_list()]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/Subtype /Type1"), "{text}");
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("/FontFile"), "{text}");
assert!(text.contains("(\\110\\151)"), "{text}");
assert!(!text.contains("/Subtype /Type0"), "{text}");
}
#[test]
fn bold_text_embeds_cmbx10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Bold".to_string(),
font: FontFace::Bold,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMBX10"), "{text}");
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
}
#[test]
fn sans_bold_text_embeds_cmssbx10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Sans".to_string(),
font: FontFace::SansBold,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMSSBX10"), "{text}");
}
#[test]
fn sans_italic_text_embeds_cmssi10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Sans".to_string(),
font: FontFace::SansItalic,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMSSI10"), "{text}");
}
#[test]
fn small_caps_text_embeds_cmcsc10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Small".to_string(),
font: FontFace::SmallCaps,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMCSC10"), "{text}");
}
#[test]
fn slanted_text_embeds_cmsl10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Slanted".to_string(),
font: FontFace::Slanted,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMSL10"), "{text}");
}
#[test]
fn bold_slanted_text_embeds_cmbxsl10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Slanted".to_string(),
font: FontFace::BoldSlanted,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMBXSL10"), "{text}");
}
#[test]
fn mono_italic_text_embeds_cmitt10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "Mono".to_string(),
font: FontFace::MonoItalic,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMITT10"), "{text}");
}
#[test]
fn math_italic_text_embeds_cmmi10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "x".to_string(),
font: FontFace::MathItalic,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMMI10"), "{text}");
assert!(text.contains("(\\170)"), "{text}");
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
}
#[test]
fn math_operators_embed_cmex10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "\u{2211}".to_string(),
font: FontFace::MathExtension,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMEX10"), "{text}");
assert!(text.contains("/summationtext"), "{text}");
assert!(!text.contains("/BaseFont /CMR10"), "{text}");
}
#[test]
fn mathbb_letters_embed_msbm10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "A".to_string(),
font: FontFace::MathBlackboard,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /MSBM10"), "{text}");
assert!(text.contains("(\\101)"), "{text}");
}
#[test]
fn mathfrak_letters_embed_eufm10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "A".to_string(),
font: FontFace::MathFraktur,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /EUFM10"), "{text}");
assert!(text.contains("(\\101)"), "{text}");
}
#[test]
fn mathcal_letters_embed_cmsy10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "A".to_string(),
font: FontFace::MathSymbol,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMSY10"), "{text}");
assert!(text.contains("(\\101)"), "{text}");
}
#[test]
fn math_symbols_embed_cmsy10() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "\u{00D7}".to_string(),
font: FontFace::MathSymbol,
};
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMSY10"), "{text}");
assert!(text.contains("/multiply"), "{text}");
}
#[test]
fn type1_backend_mixes_type1_and_fallback_fonts() {
let mut list = hello_list();
list.items.clear();
for (index, character) in "café".chars().enumerate() {
list.items.push(DisplayItem::Text {
x: index as i64 * 20 * 65_536,
y: 800_000,
size: 655_360,
text: character.to_string(),
font: FontFace::Roman,
});
}
let pdf = write(&[list]);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMR10"), "{text}");
assert!(text.contains("(\\143)"), "{text}");
assert!(text.contains("/Subtype /Type0"), "{text}");
assert!(text.contains("/T1 "), "{text}");
}
#[test]
fn pdffonts_accepts_the_embedded_type1_font() {
let probe = std::process::Command::new("pdffonts").arg("-v").output();
if probe.is_err() {
return;
}
let pdf = write(&[hello_list()]);
let path = std::env::temp_dir().join(format!(
"texrra-type1-{}-{}.pdf",
std::process::id(),
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map(|value| value.subsec_nanos())
.unwrap_or(0)
));
std::fs::write(&path, &pdf).expect("write pdf");
let output = std::process::Command::new("pdffonts")
.arg(&path)
.output()
.expect("run pdffonts");
let _ = std::fs::remove_file(&path);
let stdout = String::from_utf8_lossy(&output.stdout);
assert!(stdout.contains("Type 1"), "{stdout}");
assert!(stdout.contains("CMR10"), "{stdout}");
}
}