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

904 lines
30 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::BTreeMap;
use std::collections::BTreeSet;
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 = 7;
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(),
},
];
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(),
},
];
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()
}
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",
}
}
/// 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")),
];
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 page_content(
list: &DisplayList,
height: i64,
image_names: &BTreeMap<usize, String>,
faces: &'static [PdfFace; FACE_COUNT],
cm_codes: &[Option<&BTreeMap<char, u8>>],
origin: PageOrigin,
) -> String {
let mut content = String::from("q\n0 0 0 rg\n");
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 operand = match cm_codes
.get(*font as usize)
.and_then(|entry| entry.as_ref())
{
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
}
_ => format!("<{}>", glyph_hex(face(*font, faces), text)),
};
content.push_str(&format!(
"BT /{} {} Tf 1 0 0 1 {} {} Tm {} Tj ET\n",
font_resource(*font),
pt(*size),
pt(*x),
pt(height - *y),
operand
));
}
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::Special(special) => {
content.push_str(special);
content.push('\n');
}
}
}
content.push_str("Q\n");
content
}
/// 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,
)
}
/// 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,
)
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
backend: FontBackend,
) -> 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 !font.covers(used_chars[slot].iter().copied()) {
return None;
}
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 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];
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;
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| {
(metrics.width(*character) * 100 / 65_536) as i64
});
widths.push(width.to_string());
if let Some((code, name)) = by_code
.get(&code)
.and_then(|character| font.code_and_name_for(*character))
{
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 >>",
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);
continue;
}
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;
font_ids[slot] = type0_id;
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_chars[slot])
)
.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_chars[slot]);
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_chars[slot]);
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);
}
let mut kids = 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])
.map(|slot| format!("/F{} {} 0 R", slot + 1, font_ids[slot]))
.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}]")
};
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, 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);
}
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}] /Border [0 0 0] /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();
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,
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_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 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 type1_backend_falls_back_for_uncovered_characters() {
let mut list = hello_list();
list.items[0] = DisplayItem::Text {
x: 0,
y: 800_000,
size: 655_360,
text: "café".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("/Subtype /Type0"), "{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}");
}
}