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

3579 lines
133 KiB
Rust
Executable File
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
//! 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, HashSet};
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::pdf_device::{
catalog::{CatalogAction, CatalogTarget, PdfOutline, StructureTarget},
links::DestinationId,
};
use crate::render::{DisplayItem, DisplayList, FontFace};
use crate::type1::Type1Font;
#[path = "pdf_text.rs"]
pub(crate) mod native_text;
pub(crate) mod type1_fonts;
#[path = "pdf_objects.rs"]
pub(crate) mod objects;
#[path = "pdf_pk.rs"]
mod pk_fonts;
#[path = "pdf_opentype.rs"]
mod opentype_fonts;
#[path = "pdf_opentype_unicode.rs"]
pub(crate) mod opentype_unicode;
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 expanded_ligature_text(text: &str) -> String {
text.chars()
.map(|c| match c {
'ff' => "ff".into(),
'fi' => "fi".into(),
'fl' => "fl".into(),
'ffi' => "ffi".into(),
'ffl' => "ffl".into(),
c => c.to_string(),
})
.collect()
}
fn type1_tounicode(by_code: &BTreeMap<u8, char>) -> Vec<u8> {
let texts = by_code
.iter()
.map(|(slot, c)| (*slot, expanded_ligature_text(&c.to_string())))
.collect();
type1_tounicode_texts(&texts)
}
fn type1_tounicode_texts(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
let hex = by_code
.iter()
.map(|(slot, text)| {
(
*slot,
text.encode_utf16().map(|n| format!("{n:04X}")).collect(),
)
})
.collect();
type1_tounicode_hex(&hex)
}
fn type1_tounicode_hex(by_code: &BTreeMap<u8, String>) -> Vec<u8> {
to_unicode_map(by_code, 2)
}
fn to_unicode_map<T: Ord + std::fmt::UpperHex>(by_code: &BTreeMap<T, String>, digits: usize) -> Vec<u8> {
let max_code = "F".repeat(digits);
let min_code = "0".repeat(digits);
let mut map = format!(
"/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\n1 begincodespacerange\n<{min_code}> <{max_code}>\nendcodespacerange\n",
);
let entries: Vec<_> = by_code.iter().collect();
for chunk in entries.chunks(100) {
map.push_str(&format!("{} beginbfchar\n", chunk.len()));
for (slot, text) in chunk {
map.push_str(&format!("<{slot:0digits$X}> <{text}>\n"));
}
map.push_str("endbfchar\n");
}
map.push_str("endcmap\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)
}
/// Signed rounding for actual TFM dimensions in PDF font units.
fn native_font_units(value: i64, size: i64, factor: i64) -> i64 {
let n = value * factor;
if n < 0 {
-((-n + size / 2) / size)
} else {
(n + size / 2) / size
}
}
fn native_pdf_font_size(size: i64) -> i64 {
// pdf_use_font quantizes to 0.0001bp, then keeps divide_scaled's
// scaled_out remainder. The declared widths use this effective TeX size.
let denominator = 6_578_176; // 100bp in TeX sp, without a rounded 1bp.
let mut remainder = (size * 1_000_000) % denominator;
if remainder * 2 >= denominator {
remainder -= denominator;
}
size - remainder / 1_000_000
}
struct NativeTextRun {
font: crate::execution::FontId,
expansion: i32,
size: i64,
y: i64,
cursor: f64,
point_size: f64,
text: String,
}
impl NativeTextRun {
fn flush(run: &mut Option<Self>, content: &mut PageContent) {
if let Some(run) = run.take() {
content.push_str(&run.text);
if run.expansion == 0 {
content.push_str("] TJ ET\n");
} else {
content.push_str("] TJ 100 Tz ET\n");
}
}
}
fn push(&mut self, x: f64, slot: u8, face: &crate::native_font::NativeFont) {
// Advance by the declared rounded width, then consume the remaining
// position difference through a real TJ adjustment. Per-glyph Tm
// resets lose the pdfTeX profile's text-position quantization.
let kern = if self.point_size == 0.0 {
0.0
} else {
((self.cursor - x) * 1000.0 / self.point_size).round()
};
if kern != 0.0 {
self.text.push_str(&format!(" {kern:.0} "));
}
self.text.push_str(&format!("<{slot:02X}>"));
let m = face.metrics();
let width = native_font_units(
m.width(char::from(slot)),
native_pdf_font_size(m.size_sp()),
10_000,
) as f64
/ 10.0;
self.cursor += (width - kern) * self.point_size / 1000.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
}
/// The PDF stream can contain an 8-bit TeX literal. Keep its bytes alongside
/// the device origin used by subsequent positioned text, rules, and images.
#[derive(Default)]
struct PageContent {
bytes: Vec<u8>,
origin: crate::pdf_device::DeviceOrigin,
measuring: bool,
}
impl PageContent {
fn measuring() -> Self {
Self { measuring: true, ..Self::default() }
}
fn push_str(&mut self, text: &str) {
if !self.measuring {
self.bytes.extend_from_slice(text.as_bytes());
}
}
fn push(&mut self, byte: u8) {
if !self.measuring {
self.bytes.push(byte);
}
}
fn move_origin(&mut self, point: [i64; 2], units: crate::render::DisplayUnits, digits: u8) {
let Some([h, v]) = self.origin.move_to(point, units, digits) else {
return;
};
self.push_str(&format!(
"1 0 0 1 {} {} cm\n",
crate::pdf_device::print_decimal(h, digits),
crate::pdf_device::print_decimal(v, digits),
));
}
}
fn append_page_procset(output: &mut Vec<u8>, page: &DisplayList, has_rgb_image: bool) {
use crate::pdf_image::RasterProcSet;
let mut text = page.pdf_space_plan.as_ref().is_some_and(|plan| plan.dedicated.is_some());
let mut gray = false;
let mut color = has_rgb_image;
let mut indexed = false;
for item in &page.items {
match item {
DisplayItem::NativeGlyph { .. } | DisplayItem::OpenTypeGlyph { .. }
| DisplayItem::MathGlyph { .. } | DisplayItem::Text { .. } => text = true,
DisplayItem::PdfImage { image, .. } => match image.image.raster_procset() {
Some(RasterProcSet::Gray) => gray = true,
Some(RasterProcSet::Color) => color = true,
Some(RasterProcSet::Indexed) => indexed = true,
None => {}
},
_ => {}
}
}
output.extend_from_slice(b" /ProcSet [/PDF");
for (used, name) in [
(text, b" /Text".as_slice()),
(gray, b" /ImageB"),
(color || indexed, b" /ImageC"),
(indexed, b" /ImageI"),
] {
if used {
output.extend_from_slice(name);
}
}
output.push(b']');
}
pub(crate) fn prepare_text_spaces(
pages: &mut [DisplayList],
mut resolve: impl FnMut(
std::sync::Arc<crate::native_font::NativeFont>,
Option<crate::pdf_device::PdfPageData>,
) -> Result<crate::pdf_device::text_spaces::ResolvedSpaceFont, String>,
) -> Result<(), String> {
if !pages.iter().any(|page| page.pdf_text_spaces.is_some()) {
return Ok(());
}
let mut fonts = native_text::FontHistory::default();
let mut selected = None;
for page in pages {
let plan = native_text::plan_spaces(page, &mut fonts, || {
if let Some(font) = &selected {
return Ok(Some(crate::pdf_device::text_spaces::ResolvedSpaceFont::clone(font)));
}
let font = page.pdf_text_spaces.as_ref()
.and_then(|settings| settings.dedicated_font.clone())
.ok_or("PDF space planner requires the font selected during shipout")?;
let font = resolve(font, page.pdf.clone())?;
selected = Some(font.clone());
Ok(Some(font))
})?.expect("PDF export always resolves the selected space font");
if page.pdf_text_spaces.is_some() {
page.pdf_resources.needs_pdf_for_preview |= plan.spaces_in_previous_font
|| plan.dedicated.as_ref()
.is_some_and(|font| !font.paint.glyph_paths[&b' '].is_empty());
page.pdf_space_plan = Some(plan);
}
}
Ok(())
}
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,
opentype: &BTreeMap<crate::execution::FontId, opentype_fonts::EmbeddedFont>,
font_opacities: &BTreeMap<u8, String>,
) -> Vec<u8> {
let digits = list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits);
let pt = |n: i64| {
if list.units == crate::render::DisplayUnits::TeX {
crate::pdf_device::print_sp(n, digits)
} else {
pt(n)
}
};
use crate::pdf_device::{PdfDriver, PdfGraphics, PdfLiteralMode};
use crate::render::DisplayUnits;
let mut content = PageContent::default();
content.push_str("q\n0 0 0 rg\n");
if list.magnification != 1000 {
let ratio = f64::from(list.magnification) / 1000.0;
content.push_str(&format!("{ratio:.3} 0 0 {ratio:.3} 0 0 cm\n"));
}
if let Some(color) = &list.pdf_background {
content.push_str(&format!(
"q\n{}\n0 0 {} {} re f\nQ\n", color.literal(), pt(list.width), pt(height)
));
}
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)
));
}
let mut native_text: Option<NativeTextRun> = None;
let mut tex_text: Option<native_text::NativeText> = None;
let mut opentype_text = opentype_fonts::TextState::default();
let bp_per_unit = list.units.bp(1);
let one_inch = (72_000. / (bp_per_unit * f64::from(list.magnification))).round() as i64;
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
for (index, item) in list.items.iter().enumerate() {
if !matches!(item, DisplayItem::OpenTypeGlyph { .. }) {
opentype_text.finish(&mut content);
}
if matches!(
item,
DisplayItem::NativeGlyph { .. } | DisplayItem::MathGlyph { .. } | DisplayItem::Text { .. }
) {
opentype_text.reset_matrix();
}
if let DisplayItem::PdfTextSpace { x, y, operation } = item {
if let Some(dedicated) = list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref())
&& *operation == crate::pdf_device::text_spaces::SpaceOperation::Explicit
{
if tex_text.is_none() {
content.move_origin([0, 0], list.units, digits);
}
native_text::NativeText::explicit_space(
&mut tex_text, &mut content, *x, *y, height, digits, dedicated,
);
}
continue;
}
let literal = match item {
DisplayItem::PdfGraphics {
x,
y,
operation: PdfGraphics::Literal { mode, bytes },
} => Some((*x, *y, *mode, bytes.as_ref())),
DisplayItem::PdfColor {
x, y, mode, program, ..
} => Some((*x, *y, *mode, program.literal().as_bytes())),
_ => None,
};
if let Some((x, y, mode, bytes)) = literal {
NativeTextRun::flush(&mut native_text, &mut content);
let previous_origin = content.origin.position();
let special_origin = mode.xdv_origin([x, height - y], height, list.magnification);
match mode {
PdfLiteralMode::Direct => {
native_text::NativeText::break_string(&mut tex_text, &mut content);
}
PdfLiteralMode::Page | PdfLiteralMode::Origin => {
native_text::NativeText::finish(&mut tex_text, &mut content);
if mode == PdfLiteralMode::Origin {
content.move_origin([x, height - y], list.units, digits);
}
}
PdfLiteralMode::XdvOrigin | PdfLiteralMode::XdvDirect => {
native_text::NativeText::finish(&mut tex_text, &mut content);
if let Some(point) = special_origin {
content.move_origin(point, list.units, digits);
}
}
}
content.bytes.extend_from_slice(bytes);
content.push(b'\n');
if special_origin.is_some() {
content.move_origin(previous_origin, list.units, digits);
}
continue;
}
if list.units == DisplayUnits::TeX {
if let DisplayItem::NativeGlyph {
x,
y,
font,
slot,
paint,
..
} = item
{
assert!(paint.is_some(), "native glyph program must be resolved");
if tex_text.is_none() {
content.move_origin([0, 0], list.units, digits);
}
native_text::NativeText::glyph(
&mut tex_text,
&mut content,
*x,
*y,
font,
paint.as_ref().unwrap(),
*slot,
height,
xdv.then_some(one_inch),
digits,
list.pdf_space_plan.as_ref().and_then(|plan| plan.before_glyph.get(&index)).copied(),
list.pdf_space_plan.as_ref().and_then(|plan| plan.dedicated.as_ref()),
);
continue;
}
native_text::NativeText::finish(&mut tex_text, &mut content);
if let DisplayItem::Rule {
x,
y,
width,
height: rule_height,
} = item
{
let [h, v] = content.origin.position();
if list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv) {
native_text::xdv_rule(
&mut content, *x - h, height - *y - v - *rule_height, *width, *rule_height, digits,
);
} else {
native_text::rule(
&mut content, *x - h, *y + v, *width, *rule_height, height, digits,
);
}
continue;
}
}
if let Some(run) = &native_text {
if run.point_size == 0.0
|| !matches!(item,DisplayItem::NativeGlyph{font,size,y,..}if font.id==run.font && font.expansion==run.expansion && *size==run.size && *y==run.y)
{
NativeTextRun::flush(&mut native_text, &mut content);
}
}
let [h, v] = content.origin.position();
let px = |x| pt(x - h);
let py = |y| pt(height - y - v);
match item {
DisplayItem::OpenTypeActualText(text) => match text {
Some(text) => opentype_fonts::begin_actual_text(&mut content, text, true),
None => content.push_str("EMC\n"),
},
DisplayItem::OpenTypeColor(color) => {
if let Some([r, g, b, alpha]) = color {
let [r, g, b] = [*r, *g, *b].map(|channel| f64::from(channel) / 255.);
let opacity = &font_opacities[alpha];
content.push_str(&format!(
"q {r:.3} {g:.3} {b:.3} RG {r:.3} {g:.3} {b:.3} rg /{opacity} gs\n",
));
} else {
content.push_str("Q\n");
}
}
DisplayItem::OpenTypeGlyph { x, y, size, font, glyph, text, .. } => {
opentype[&font.id].paint(
&mut opentype_text, &mut content, font, *glyph, text,
*size, *x - h, height - *y - v, bp_per_unit,
[one_inch - h, height - one_inch - v], xdv, !font_opacities.is_empty(),
);
}
DisplayItem::NativeGlyph {
x,
y,
size,
font,
slot,
paint,
..
} => {
assert!(
paint.is_some(),
"native font resources must be resolved before PDF output"
);
let run = native_text.get_or_insert_with(|| {
let point_size =
native_font_units(font.size_sp(), 6_578_176, 1_000_000) as f64 / 10_000.0;
let spacing = if font.expansion == 0 {
String::new()
} else {
format!("{} Tz ", crate::pdf_device::print_decimal(
i64::from(1000 + font.expansion), 1,
))
};
NativeTextRun {
font: font.id,
expansion: font.expansion,
size: *size,
y: *y,
cursor: px(*x).parse().unwrap(),
point_size: point_size * f64::from(1000 + font.expansion) / 1000.0,
text: format!(
"BT /N{} {point_size:.4} Tf {spacing}1 0 0 1 {} {} Tm [",
font.id.index(),
px(*x),
py(*y)
),
}
});
run.push(list.units.bp(*x), *slot, font);
}
DisplayItem::MathGlyph {
x,
y,
size,
face,
slot,
..
} => {
content.push_str(&format!(
"BT /M{} {} Tf 1 0 0 1 {} {} Tm <{slot:02X}> Tj ET\n",
face.0,
pt(*size),
px(*x),
py(*y)
));
}
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),
px(*x),
py(*y),
operand
));
}
DisplayItem::Background(_) => {}
DisplayItem::Rect {
x,
y,
width,
height,
color,
} => {
content.push_str(&format!(
"{:.3} {:.3} {:.3} rg\n{} {} {} {} re f\n",
color[0] as f64 / 255.0,
color[1] as f64 / 255.0,
color[2] as f64 / 255.0,
px(*x),
py(*y + *height),
pt(*width),
pt(*height)
));
}
DisplayItem::Rule {
x,
y,
width,
height: rule_height,
} => {
content.push_str(&format!(
"{} {} {} {} re f\n",
px(*x),
py(*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),
px(*x1),
py(*y1),
px(*x2),
py(*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),
px(*x),
py(*y + *image_height)
));
}
}
DisplayItem::PdfImage {
x,
y,
width,
height: image_height,
image,
} => {
if let Some(placement) = &image.xdv {
let [a, b, c, d, tx, ty] = placement.paint_matrix();
let inch = 72.0 * 1000.0 / f64::from(list.magnification);
let [origin_x, origin_y] = [inch, list.units.bp(height) - inch];
// The XDV driver rounds the image translation relative
// to its page origin, with three decimals by default.
let round = |value: f64| (value * 1000.0).round() / 1000.0;
let [left, bottom] = placement.layout_offset;
let x = round(list.units.bp(*x - left) + tx - origin_x) + round(origin_x)
- list.units.bp(h);
let y = round(
list.units.bp(height - *y - *image_height - bottom) + ty - origin_y,
) + round(origin_y) - list.units.bp(v);
let [a, b, c, d, x, y] = [a, b, c, d, x, y].map(crate::pdf_image::real);
content.push_str(&format!("q {a} {b} {c} {d} {x} {y} cm "));
if let Some(clip) = placement.clip() {
let [x, y, w, h] = clip.map(|value| {
crate::pdf_image::real((value * 1000.0).round() / 1000.0)
});
content.push_str(&format!("{x} {y} {w} {h} re W n "));
}
content.push_str(&format!("/PI{} Do Q\n", image.id));
continue;
}
let [sx, sy] = if image.image.raster_frame().is_some()
&& list.units == crate::render::DisplayUnits::TeX
{
[
crate::pdf_device::print_sp(*width, 4),
crate::pdf_device::print_sp(*image_height, 4),
]
} else if list.units == crate::render::DisplayUnits::TeX {
let [natural_width, natural_height] = image.image.natural;
// pdfTeX out_image prints a six-decimal ratio of scaled
// dimensions, while translation follows pdfdecimaldigits.
let scale = |placed, natural| {
let (coefficient, _) = crate::pdf_device::divide_scaled(placed, natural, 6);
crate::pdf_device::print_decimal(coefficient, 6)
};
[
scale(*width, natural_width),
scale(*image_height, natural_height),
]
} else {
let [natural_width, natural_height] = image.image.extent();
[
crate::pdf_image::real(list.units.bp(*width) / natural_width),
crate::pdf_image::real(list.units.bp(*image_height) / natural_height),
]
};
let [dx, dy] = image.image.restored_pdf_origin.map_or([0, 0], |origin| {
let placed = [*width, *image_height];
std::array::from_fn(|axis| {
crate::pdf_device::divide_scaled(
placed[axis] * origin[axis], image.image.natural[axis], 0,
).0
})
});
let name = image.id;
content.push_str(&format!(
"q {sx} 0 0 {sy} {} {} cm /PI{name} Do Q\n",
px(*x - dx),
py(*y + *image_height + dy)
));
}
DisplayItem::Frame {
x,
y,
width,
height,
color,
thickness,
} => {
content.push_str(&format!(
"{:.3} {:.3} {:.3} RG\n{:.3} w\n{} {} {} {} re S\n0 0 0 RG\n1 w\n",
color[0] as f64 / 255.0,
color[1] as f64 / 255.0,
color[2] as f64 / 255.0,
*thickness as f64 / 65_536.0,
px(*x),
pt(list.height - *y - *height - v),
pt(*width),
pt(*height)
));
}
DisplayItem::Link { .. } | DisplayItem::PdfTextSpace { .. } => {}
DisplayItem::PdfImageObject(_) => {}
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(b'\n');
}
DisplayItem::PdfColor { .. } => unreachable!("color handled before text"),
DisplayItem::PdfGraphics { x, y, operation } => {
let xdv = list.pdf.as_ref().is_some_and(|pdf| pdf.driver == PdfDriver::Xdv);
let device_origin = list.units == DisplayUnits::TeX && !xdv;
if device_origin {
content.move_origin([*x, height - *y], list.units, digits);
} else if xdv {
content.move_origin([0, 0], list.units, digits);
}
match operation {
PdfGraphics::Save => content.push_str("q\n"),
PdfGraphics::Restore { shift: [dx, dy] } => {
content.push_str("Q\n");
if !device_origin && (*dx != 0 || *dy != 0) {
content.push_str(&format!(
"1 0 0 1 {} {} cm\n", pt(*dx), pt(-*dy),
));
}
}
PdfGraphics::Matrix(matrix) | PdfGraphics::SaveMatrix(matrix) => {
if matches!(operation, PdfGraphics::SaveMatrix(_)) {
content.push_str("q\n");
}
let coordinates = if device_origin {
[0.0, 0.0]
} else if xdv {
[list.units.bp(*x), list.units.bp(height - *y)]
} else {
[*x, height - *y].map(|coordinate| {
pt(coordinate).parse::<f64>().expect("formatted PDF dimension")
})
};
let [a, b, c, d, e, f] = matrix
.about(coordinates[0], coordinates[1], false)
.0
.map(crate::pdf_image::real);
content.push_str(&format!("{a} {b} {c} {d} {e} {f} cm\n"));
}
PdfGraphics::Literal { .. } => unreachable!("literal handled before text"),
}
}
}
}
opentype_text.finish(&mut content);
NativeTextRun::flush(&mut native_text, &mut content);
native_text::NativeText::finish(&mut tex_text, &mut content);
content.push_str("Q\n");
content.bytes
}
/// 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(" ")))
}
fn native_information_dictionary(info: crate::pdf_device::PdfInfo<'_>) -> Vec<u8> {
// pdfTeX suppresses defaults based on the raw byte spelling anywhere in
// the expanded list. Preserve the supplied PDF syntax verbatim.
let supplied = |key: &[u8]| info.entries.windows(key.len()).any(|value| value == key);
let mut object = b"<<\n".to_vec();
if !supplied(b"/Producer") {
object.extend_from_slice(b"/Producer (texrra Route-D native)\n");
}
if !info.entries.is_empty() {
object.extend_from_slice(info.entries);
object.push(b'\n');
}
if !supplied(b"/Creator") {
object.extend_from_slice(b"/Creator (TeX)\n");
}
if let Some(date) = info.date {
for key in ["CreationDate", "ModDate"] {
let name = format!("/{key}");
if !supplied(name.as_bytes()) {
writeln!(&mut object, "{name} ({date})").unwrap();
}
}
}
if !supplied(b"/Trapped") {
object.extend_from_slice(b"/Trapped /False\n");
}
object.extend_from_slice(b">>");
object
}
/// 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(),
None,
None,
None,
&mut Vec::new(),
).expect("valid PDF display lists")
}
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(),
None,
None,
None,
&mut Vec::new(),
).expect("valid PDF display lists")
}
/// Strict token-kernel output: every glyph has its measured native resource
/// and an actual resolved program. A legacy text/family node is an error;
/// it cannot enter the AST painter's font selection or replacement path.
pub fn display_lists_to_native_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
) -> Result<Vec<u8>, String> {
native_pdf(pages, page_width, page_height, origin, None, None).map(|document| document.bytes)
}
/// A complete native export, including diagnostics produced by font writing.
#[derive(Debug)]
pub struct NativePdfDocument {
pub bytes: Vec<u8>,
pub diagnostics: Vec<String>,
}
/// Native job output uses each actual shipout's captured canvas and scale.
/// Use the document form when the caller owns a diagnostic sink.
pub fn shipout_lists_to_native_pdf(
pages: &[DisplayList],
options: crate::pdf_unicode::PdfFinalOptions<'_>,
) -> Result<Vec<u8>, String> {
shipout_lists_to_native_pdf_document(pages, options).map(|document| document.bytes)
}
pub fn shipout_lists_to_native_pdf_document(
pages: &[DisplayList],
options: crate::pdf_unicode::PdfFinalOptions<'_>,
) -> Result<NativePdfDocument, String> {
native_pdf(
pages,
0,
0,
PageOrigin::default(),
Some(options.compression),
Some(options),
)
}
fn native_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
final_compression: Option<i32>,
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
) -> Result<NativePdfDocument, String> {
let mut fonts = BTreeMap::new();
if final_compression.is_some() && pages.is_empty() {
return Err("no native PDF shipouts".into());
}
for page in pages {
if final_compression.is_some() {
let p = page
.pdf
.as_ref()
.ok_or("native DVI output cannot be exported by the PDF driver")?;
if p.file.major < 1
|| p.file.minor > 9
|| p.file.object_compression > 3
|| p.file.decimal_digits > 4
|| p.stream_compression > 9
|| !(72..=8000).contains(&p.file.pk_resolution)
|| (p.file.major == 1 && p.file.minor < 5 && p.file.object_compression > 0)
{
return Err("invalid captured native PDF file options".into());
}
if page.units != crate::render::DisplayUnits::TeX {
return Err("native PDF requires original TeX sp coordinates".into());
}
if let Some(first) = pages.first().and_then(|p| p.pdf.as_ref()) {
if first.file != p.file {
return Err("inconsistent native PDF file options".into());
}
}
}
if !(1..=32768).contains(&page.magnification) {
return Err("invalid native page magnification".into());
}
if page.pdf_text_spaces.is_some() && page.pdf_space_plan.is_none() {
return Err("native PDF text spaces require actual font resolution".into());
}
for item in &page.items {
match item {
DisplayItem::Text {..} | DisplayItem::MathGlyph {..} => return Err("native PDF requires actual native font snapshots, not legacy text or master glyphs".into()),
DisplayItem::NativeGlyph {font,slot,paint,..} => {
if native_pdf_font_size(font.metrics().size_sp()) <= 0 {
return Err("native PDF font size rounds to zero in the pdfTeX profile".into());
}
let paint=paint.as_ref().ok_or_else(||format!("native font {} has no resolved output program",font.name))?;
if page.units != crate::render::DisplayUnits::TeX && matches!(paint.program,crate::native_font::NativeFontProgram::Pk(_)) {
return Err("native PK PDF requires actual shipout device coordinates".into());
}
if paint.encoding.len()!=256 || paint.encoding[*slot as usize]==".notdef" || !paint.glyph_paths.contains_key(slot) || !font.has_slot(*slot) {
return Err(format!("native font {} has no output encoding for slot {slot}",font.name));
}
if let Some((old_font,old_paint))=fonts.insert(font.id,(font,paint)) {
if !old_font.same_base(font) || old_paint != paint {
return Err("inconsistent native font snapshots or programs in PDF output".into());
}
}
}
_=>{},
}
}
}
if final_compression.is_some_and(|level| level > 9)
&& (!fonts.is_empty()
|| pages
.first()
.and_then(|p| p.pdf.as_ref())
.is_some_and(|p| p.file.object_compression > 0))
{
return Err("invalid native PDF final stream compression level".into());
}
let raw_objects = unicode.and_then(|options| options.objects);
let page_tree = unicode.map_or(&[][..], |options| options.page_tree_attributes);
let font_attributes: BTreeMap<_, _> = fonts.keys().filter_map(|&font| {
let settings = unicode?.fonts.pdf_settings(font)?;
(!settings.attributes.is_empty()).then_some((font, settings.attributes.as_slice()))
}).collect();
let resources = if raw_objects.is_some()
|| !font_attributes.is_empty()
|| !page_tree.is_empty()
|| pages.iter().any(|page| !page.pdf_resources.entries.is_empty()
|| !page.pdf_resources.attributes.is_empty()
|| page.pdf_links.destinations.iter().any(|destination| destination.structure.is_some()))
{
let (catalog, info) = if raw_objects.is_some() {
(
unicode.and_then(|options| options.catalog).map(|catalog| catalog.entries.as_slice()),
unicode.filter(|options| !options.omit_info).map(|options| options.info.entries),
)
} else {
(None, None)
};
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
pages, raw_objects, font_attributes, page_tree, catalog, info,
)?)
} else {
None
};
let mut diagnostics = Vec::new();
let bytes = write_pdf(
pages,
page_width,
page_height,
origin,
FontBackend::ComputerModern,
&PdfMetadata::default(),
final_compression,
unicode,
resources,
&mut diagnostics,
)?;
Ok(NativePdfDocument { bytes, diagnostics })
}
/// Write PDFs with Liberation TrueType outlines and a document Info dictionary.
pub fn display_lists_to_pdf_with_truetype_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::TrueType,
metadata,
None,
None,
None,
&mut Vec::new(),
).expect("valid PDF display lists")
}
/// 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,
None,
None,
None,
&mut Vec::new(),
).expect("valid PDF display lists")
}
fn write_math_font(
objects: &mut Vec<Vec<u8>>,
face: crate::math_font::MathFontId,
used: &BTreeMap<u8, char>,
) -> usize {
let font = face.type1();
let id = objects.len() + 1;
let descriptor = id + 1;
let program = id + 2;
let unicode = id + 3;
let first = *used.keys().next().expect("used math font");
let last = *used.keys().next_back().unwrap();
let widths = (first..=last)
.map(|slot| {
format!(
"{:.3}",
face.metrics().width(char::from(slot)) as f64 * 1000.0 / face.design_size() as f64
)
})
.collect::<Vec<_>>()
.join(" ");
objects.push(format!(
"<< /Type /Font /Subtype /Type1 /BaseFont /{} /FirstChar {first} /LastChar {last} /Widths [{widths}] /FontDescriptor {descriptor} 0 R /ToUnicode {unicode} 0 R >>",
font.name
).into_bytes());
let [left, bottom, right, top] = font.bbox;
// FontBBox is an outline bound, not the Latin ascender/descender used by
// text selection. Derive these from the actual optical master's TFM.
let (ascent, descent, cap_height) = if matches!(
face.family(),
crate::math_engine_tex::MathFont::Roman | crate::math_engine_tex::MathFont::Italic
) {
let m = face.metrics();
let em = face.design_size();
let units = |n: i64| (n * 1000 + em / 2) / em;
(
units(m.height('d')),
-units(m.depth('p')),
units(m.height('H')),
)
} else {
(top as i64, bottom as i64, top as i64)
};
objects.push(format!(
"<< /Type /FontDescriptor /FontName /{} /Flags 4 /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle 0 /Ascent {ascent} /Descent {descent} /CapHeight {cap_height} /StemV 69 /FontFile {program} 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(used);
let mut stream = format!("<< /Length {} >>\nstream\n", cmap.len()).into_bytes();
stream.extend_from_slice(&cmap);
stream.extend_from_slice(b"\nendstream");
objects.push(stream);
id
}
fn native_pdf_name(name: &str) -> String {
name.bytes()
.map(|b| {
if (33..=126).contains(&b) && !b"#%()/<>[]{}".contains(&b) {
char::from(b).to_string()
} else {
format!("#{b:02X}")
}
})
.collect()
}
fn native_type1_parameters(
font: &Type1Font,
paint: &crate::native_font::NativeFontPaint,
metrics: &crate::tfm::TfmMetrics,
) -> String {
let [left, bottom, right, top] = paint.bbox;
let units = |n: i64| native_font_units(n, native_pdf_font_size(metrics.size_sp()), 1000);
// TFM slot conventions of the profile, independent of glyph names in
// mathematical or externally reencoded fonts.
let ascent = units(metrics.height('h'));
let descent = (-units(metrics.depth('y'))).min(0);
let cap = units(metrics.height('H'));
let x_height = units(metrics.x_height());
let flags =
4 | if font.is_fixed_pitch { 1 } else { 0 } | if font.italic_angle != "0" { 64 } else { 0 };
let angle = if font.transform.slant == 0 {
font.italic_angle.clone()
} else {
font.italic_angle.parse::<f64>().unwrap_or(0.).round().to_string()
};
if let Some(xdv) = paint.xdv_descriptor {
let [left, bottom, right, top] = font.bbox;
let [ascent, descent, cap, stem_v] = xdv.metrics();
let flags = flags | (i32::from(!font.name.contains("Sans")) << 1)
| (i32::from(font.name.contains("Caps")) << 17)
| (i32::from(xdv.force_bold) << 18);
format!("/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /StemV {stem_v}")
} else {
let flags = paint.descriptor_flags.unwrap_or(4);
let stem_v = paint.stem_v;
format!("/Flags {flags} /FontBBox [{left} {bottom} {right} {top}] /ItalicAngle {angle} /Ascent {ascent} /Descent {descent} /CapHeight {cap} /XHeight {x_height} /StemV {stem_v}")
}
}
fn write_native_font(
objects: &mut Vec<Vec<u8>>,
face: &crate::native_font::NativeFont,
paint: &crate::native_font::NativeFontPaint,
used: &BTreeMap<u8, char>,
compression: u8,
options: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
diagnostics: &mut Vec<String>,
reference: Option<&type1_fonts::Reference>,
) -> usize {
let font = match &paint.program {
crate::native_font::NativeFontProgram::Type1(font) => font,
crate::native_font::NativeFontProgram::Pk(pk) => {
return pk_fonts::write_font(objects, face.id, pk, used, compression);
}
};
let id = objects.len() + 1;
objects.push(Vec::new());
let m = face.metrics();
let descriptor = reference.map_or_else(
|| type1_fonts::write_full(objects, font, &native_type1_parameters(font, paint, m), compression),
|shared| shared.object,
);
let unicode = objects.len() + 1;
let first = *used.keys().next().unwrap();
let last = *used.keys().next_back().unwrap();
let widths = (first..=last)
.map(|slot| {
format!(
"{:.1}",
native_font_units(
m.width(char::from(slot)),
native_pdf_font_size(m.size_sp()),
10_000
) as f64
/ 10.0
)
})
.collect::<Vec<_>>()
.join(" ");
let differences = paint
.encoding
.iter()
.map(|n| format!("/{}", native_pdf_name(n)))
.collect::<Vec<_>>()
.join(" ");
let cmap = if let Some(options) = options {
if options.fonts.pdf_settings(face.id).is_some_and(|settings| settings.omit_builtin_unicode) {
None
} else if options.generate_unicode > 0 && !options.glyph_unicode.is_empty() {
let texts = paint
.encoding
.iter()
.enumerate()
.filter_map(|(slot, name)| {
options
.glyph_unicode
.lookup(&face.name, name)
.map(|hex| (slot as u8, hex))
})
.collect();
Some(type1_tounicode_hex(&texts))
} else {
if options.generate_unicode > 0 && diagnostics.is_empty() {
diagnostics.push("no GlyphToUnicode entry has been inserted yet!".into());
}
None
}
} else {
let texts = used
.keys()
.filter_map(|slot| {
crate::type1::glyph_unicode_text(&paint.encoding[*slot as usize])
.map(|s| (*slot, expanded_ligature_text(&s)))
})
.collect();
Some(type1_tounicode_texts(&texts))
};
let unicode_ref = if cmap.is_some() {
format!(" /ToUnicode {unicode} 0 R")
} else {
String::new()
};
let name = native_pdf_name(reference.map_or(font.name.as_str(), |shared| shared.name.as_str()));
objects[id - 1] = format!("<< /Type /Font /Subtype /Type1 /BaseFont /{name} /FirstChar {first} /LastChar {last} /Widths [{widths}] /Encoding << /Type /Encoding /Differences [0 {differences}] >> /FontDescriptor {descriptor} 0 R {unicode_ref} >>").into_bytes();
if let Some(cmap) = cmap {
objects.push(objects::stream("", &cmap, compression));
}
id
}
fn pdf_file_specification(out: &mut Vec<u8>, file: &[u8]) {
out.extend_from_slice(b"/F ");
if file.starts_with(b"(") && file.ends_with(b")") {
out.extend_from_slice(file);
} else {
out.push(b'(');
for &byte in file {
if matches!(byte, b'(' | b')' | b'\\') {
out.push(b'\\');
}
out.push(byte);
}
out.push(b')');
}
out.push(b' ');
}
#[derive(Default)]
struct PdfNavigation {
pages: Vec<usize>,
named: BTreeMap<String, String>,
numbered: BTreeMap<i32, usize>,
structures: BTreeMap<DestinationId<String>, usize>,
threads: BTreeMap<DestinationId<String>, usize>,
}
fn destination_identifier(id: &DestinationId<String>) -> String {
match id {
DestinationId::Name(name) => format!("name{{{name}}}"),
DestinationId::Number(number) => format!("num{number}"),
}
}
fn catalog_action_bytes(
action: &CatalogAction,
destinations: &mut PdfNavigation,
objects: &mut Vec<Vec<u8>>,
diagnostics: &mut Vec<String>,
) -> Vec<u8> {
let PdfNavigation { pages, named, numbered, structures, threads } = destinations;
let mut output = b"<< ".to_vec();
match action {
CatalogAction::User(object) => output.clone_from(object),
CatalogAction::GoTo {
target,
file,
window,
structure,
} => {
if let Some(file) = file {
pdf_file_specification(&mut output, file);
if let Some(window) = window {
write!(&mut output, "/NewWindow {window} ").unwrap();
}
output.extend_from_slice(b"/S /GoToR /D ");
} else {
output.extend_from_slice(b"/S /GoTo /D ");
}
match target {
CatalogTarget::Destination(DestinationId::Name(name)) => {
if file.is_none() && !named.contains_key(name) {
diagnostics.push(format!(
"destination name{{{name}}} has been referenced but does not exist, replaced by a fixed one"
));
named.insert(name.clone(), format!("[{} 0 R /Fit]", pages[0]));
}
output.extend_from_slice(pdf_text(name).as_bytes());
}
CatalogTarget::Destination(DestinationId::Number(number)) => {
let id = numbered.entry(*number).or_insert_with(|| {
diagnostics.push(format!(
"destination num{number} has been referenced but does not exist, replaced by a fixed one"
));
objects.push(format!("[{} 0 R /Fit]", pages[0]).into_bytes());
objects.len()
});
write!(&mut output, "{id} 0 R").unwrap();
}
CatalogTarget::Page { number, view } => {
let index = (*number - 1) as usize;
if file.is_some() {
write!(&mut output, "[{index} ").unwrap();
} else {
let page = pages.get(index).copied().unwrap_or_else(|| {
diagnostics.push(format!(
"page {number} has been referenced but does not exist"
));
objects.push(Vec::new());
objects.len()
});
write!(&mut output, "[{page} 0 R ").unwrap();
}
output.extend_from_slice(view);
output.push(b']');
}
}
match structure {
Some(StructureTarget::Local(destination)) => {
let id = structures.entry(destination.clone()).or_insert_with(|| {
diagnostics.push(format!(
"structure destination {} has been referenced but does not exist",
destination_identifier(destination)
));
// pdfTeX leaves the missing destination in the free list.
objects.push(Vec::new());
objects.len()
});
write!(&mut output, " /SD {id} 0 R").unwrap();
}
Some(StructureTarget::Remote(bytes)) => {
output.extend_from_slice(b" /SD ");
output.extend_from_slice(bytes);
}
None => {}
}
output.extend_from_slice(b"\n>>");
}
CatalogAction::Thread { destination, file } => {
let mut local_id = None;
if let Some(file) = file {
pdf_file_specification(&mut output, file);
} else {
let (title, identifier) = match destination {
DestinationId::Name(name) => (name.clone(), format!("name{{{name}}}")),
DestinationId::Number(number) => (number.to_string(), format!("num{number}")),
};
local_id = Some(*threads.entry(destination.clone()).or_insert_with(|| {
diagnostics.push(format!(
"thread destination {identifier} has been referenced but does not exist, replaced by a fixed one"
));
// Link the missing thread's single empty bead to the first page.
let thread = objects.len() + 1;
let bead = thread + 1;
objects.push(format!("<< /I << /Title {} >> /F {bead} 0 R >>", pdf_text(&title)).into_bytes());
objects.push(format!(
"<< /T {thread} 0 R /V {bead} 0 R /N {bead} 0 R /P {} 0 R /R [0 0 0 0] >>",
pages[0]
).into_bytes());
thread
}));
}
output.extend_from_slice(b"/S /Thread /D ");
match destination {
DestinationId::Name(name) => output.extend_from_slice(pdf_text(name).as_bytes()),
DestinationId::Number(number) => {
if let Some(id) = local_id {
write!(&mut output, "{id} 0 R").unwrap();
} else {
write!(&mut output, "{number}").unwrap();
}
}
}
output.extend_from_slice(b" >>");
}
}
output
}
#[derive(Clone, Default)]
struct OutlinePosition {
parent: usize,
first: Option<usize>,
last: Option<usize>,
previous: Option<usize>,
next: Option<usize>,
visible_children: usize,
}
fn write_pdf_outlines(
outlines: &[PdfOutline<Vec<u8>>],
action_ids: &[usize],
objects: &mut Vec<Vec<u8>>,
) -> usize {
let mut positions = vec![OutlinePosition::default(); outlines.len() + 1];
let mut parents = vec![(0, usize::MAX)];
for (offset, outline) in outlines.iter().enumerate() {
let index = offset + 1;
let (parent, remaining) = parents.last_mut().unwrap();
let parent = *parent;
*remaining -= 1;
positions[parent].first.get_or_insert(index);
if let Some(previous) = positions[parent].last.replace(index) {
positions[previous].next = Some(index);
positions[index].previous = Some(previous);
}
positions[index].parent = parent;
if outline.count != 0 {
parents.push((index, outline.count.unsigned_abs() as usize));
} else {
while parents.last().is_some_and(|(_, remaining)| *remaining == 0) {
parents.pop();
}
}
}
for (offset, outline) in outlines.iter().enumerate().rev() {
let position = &positions[offset + 1];
let visible = if outline.count > 0 { position.visible_children } else { 0 };
let parent = position.parent;
positions[parent].visible_children += visible + 1;
}
let root_id = objects.len() + 1;
objects.resize_with(root_id + outlines.len(), Vec::new);
let root = &positions[0];
// pdfTeX uses the current sibling at the end of input as the root's Last.
let last = positions[parents.last().unwrap().0].last.map_or(0, |index| root_id + index);
objects[root_id - 1] = format!(
"<< /Type /Outlines /First {} 0 R /Last {last} 0 R /Count {} >>",
root_id + root.first.unwrap(),
root.visible_children,
)
.into_bytes();
for (offset, (outline, action_id)) in outlines.iter().zip(action_ids).enumerate() {
let position = &positions[offset + 1];
let mut title = Vec::with_capacity(outline.title.len() + 2);
title.push(b'(');
title.extend_from_slice(&outline.title);
title.push(b')');
objects.push(title);
let mut entry = format!(
"<< /Title {} 0 R /A {action_id} 0 R /Parent {} 0 R",
objects.len(),
root_id + position.parent,
)
.into_bytes();
for (key, index) in [
("Prev", position.previous),
("Next", position.next),
("First", position.first),
("Last", position.last),
] {
if let Some(index) = index {
write!(&mut entry, " /{key} {} 0 R", root_id + index).unwrap();
}
}
if position.visible_children != 0 {
let sign = if outline.count < 0 { "-" } else { "" };
write!(&mut entry, " /Count {sign}{}", position.visible_children).unwrap();
}
if !outline.attributes.is_empty() {
entry.push(b'\n');
entry.extend_from_slice(&outline.attributes);
entry.push(b'\n');
}
entry.extend_from_slice(b" >>");
objects[root_id + offset] = entry;
}
root_id
}
fn write_pdf(
pages: &[DisplayList],
page_width: i64,
page_height: i64,
origin: PageOrigin,
backend: FontBackend,
metadata: &PdfMetadata,
final_compression: Option<i32>,
unicode: Option<crate::pdf_unicode::PdfFinalOptions<'_>>,
resources: Option<crate::pdf_device::page_resources::ResourceOutput>,
diagnostics: &mut Vec<String>,
) -> Result<Vec<u8>, String> {
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
// Native math uses exact slots and optical masters, independent of the
// document's Times/Liberation text backend and Unicode face remapping.
let mut math_used: BTreeMap<crate::math_font::MathFontId, BTreeMap<u8, char>> = BTreeMap::new();
for page in pages {
for item in &page.items {
if let DisplayItem::MathGlyph {
face,
slot,
character,
..
} = item
{
math_used
.entry(*face)
.or_default()
.insert(*slot, *character);
}
}
}
let mut math_font_ids = BTreeMap::new();
for (face, used) in &math_used {
math_font_ids.insert(*face, write_math_font(&mut objects, *face, used));
}
let mut native_used = BTreeMap::new();
let mut type1_names = HashSet::new();
let mut type1_descriptor_faces = HashMap::new();
let mut opentype_used = opentype_fonts::UsedFonts::default();
for page in pages {
for item in &page.items {
if let DisplayItem::NativeGlyph {
font,
paint,
slot,
character,
..
} = item
{
let paint = paint
.as_ref()
.expect("resolve native font resources before PDF output");
let entry = native_used.entry(font.id).or_insert_with(|| {
// pdfTeX registers one font object per scalable TFM name
// when used and writes those objects in reverse order.
// The last newly used TFM for an embedded variant supplies its shared
// descriptor, while each font keeps its own encoding.
if let Some(program) = paint.type1_program_key() {
if type1_names.insert((program, font.name.as_str())) {
type1_descriptor_faces.insert(program, font.id);
}
}
(font.clone(), paint.clone(), BTreeMap::new())
});
assert!(
entry.0.same_base(font),
"native font ids from different jobs cannot share a PDF"
);
entry.2.insert(*slot, *character);
} else if let DisplayItem::OpenTypeGlyph { font, glyph, text, .. } = item {
opentype_used.observe(font, *glyph, text)?;
}
}
}
let opentype = opentype_used.write(
&mut objects,
final_compression.unwrap_or(0).clamp(0, 9) as u8,
unicode,
)?;
for plan in pages.iter().filter_map(|page| page.pdf_space_plan.as_ref()) {
for id in &plan.in_font {
native_used.get_mut(id).expect("painted space font").2.insert(b' ', ' ');
}
if let Some(font) = &plan.dedicated {
native_used.entry(font.font.id).or_insert_with(|| (
font.font.clone(), font.paint.clone(), BTreeMap::from([(b' ', ' ')]),
));
}
}
// Use the form registered by shipout when one exists. A placement
// retains its measured source image and can precede that registration.
let declarations = pages.iter().flat_map(|list| &list.items).filter_map(|item| {
if let DisplayItem::PdfImageObject(object) = item {
Some((object.image.id, object.image.image.as_ref(), object.attributes.as_slice(), object.compression))
} else {
None
}
});
let placements = pages.iter().flat_map(|list| {
let compression = list.pdf.as_ref().map_or(0, |pdf| pdf.stream_compression);
list.items.iter().filter_map(move |item| {
if let DisplayItem::PdfImage { image, .. } = item {
Some((image.id, image.image.as_ref(), &[][..], compression))
} else {
None
}
})
});
let mut image_ids = HashSet::new();
let images: Vec<_> = declarations.chain(placements)
.filter(|(id, ..)| image_ids.insert(*id))
.collect();
let compression = final_compression.unwrap_or(0).clamp(0, 9) as u8;
let mut type1_plans = type1_fonts::FontPlans::default();
// pdfTeX collects included font descriptors as it writes forms. The
// TeX font dictionaries and their glyph marks are finalized afterward.
for (_, image, _, _) in &images {
for font in image.mapped_type1_fonts() {
type1_plans.include(font);
}
}
for (face, paint, used) in native_used.values() {
let crate::native_font::NativeFontProgram::Type1(program) = &paint.program else {
continue;
};
let Some(key) = paint.type1_program_key() else {
continue;
};
let (owner, owner_paint) = type1_descriptor_faces.get(&key)
.map_or((face, paint), |id| {
let (face, paint, _) = &native_used[id];
(face, paint)
});
let glyphs = used.keys().map(|slot| paint.encoding[usize::from(*slot)].as_str());
type1_plans.paint(key, program, owner_paint.subset,
|| native_type1_parameters(program, owner_paint, owner.metrics()), glyphs);
}
let omit_charset = unicode.is_some_and(|options| options.omit_charset);
let type1_references = type1_plans.write(&mut objects, compression, omit_charset)?;
let mut native_font_ids = BTreeMap::new();
for (&id, (face, paint, used)) in &native_used {
native_font_ids.insert(
id,
write_native_font(
&mut objects,
face,
paint,
used,
compression,
unicode,
diagnostics,
paint.type1_program_key().and_then(|key| type1_references.get(&key)),
),
);
}
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| {
// A Times/TrueType document still wants the real Computer Modern
// math faces: the Liberation fallback has different glyph sizes,
// so formulas would be narrower and shorter than TeX.
let type1_math = backend == FontBackend::TrueType && (6..=10).contains(&slot);
if (backend != FontBackend::ComputerModern && !type1_math) || !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 resources = if resources.is_none() && pages.iter().any(|page| {
page.items.iter().any(|item| matches!(item, DisplayItem::OpenTypeColor(Some(_))))
}) {
Some(crate::pdf_device::page_resources::ResourceOutput::prepare(
pages, None, BTreeMap::new(), &[], None, None,
)?)
} else {
resources
};
let remapped = resources
.map(|resources| resources.append(&mut objects, diagnostics))
.transpose()?;
if let Some(resources) = &remapped {
for (font, entries) in &resources.fonts {
if !entries.is_empty() {
let body = &mut objects[native_font_ids[font] - 1];
body.truncate(body.len() - 2);
body.extend_from_slice(b"\n");
body.extend_from_slice(entries);
body.extend_from_slice(b"\n>>");
}
}
}
let mut kids = Vec::new();
let mut navigation = PdfNavigation::default();
let mut annotation_actions = Vec::new();
let mut xdv_annotations = Vec::new();
let pdf_version = pages
.first()
.and_then(|page| page.pdf.as_ref())
.map_or((1, 4), |pdf| (pdf.file.major, i32::from(pdf.file.minor)));
let mut unwritten_color_spaces = BTreeMap::new();
let form_ids: BTreeMap<_, _> = images.into_iter().map(|(id, image, attributes, compression)| {
let color_space = image.color_space.map(|number| {
let Ok(reference) = u32::try_from(number) else {
return i64::from(number);
};
if let Some(mapped) = remapped.as_ref().and_then(|r| r.object_numbers.get(&reference)) {
return i64::from(*mapped);
}
// A colorspace number is a reference only. Keep an unwritten target
// free rather than materializing it or colliding with a device object.
*unwritten_color_spaces.entry(reference).or_insert_with(|| {
objects.push(Vec::new());
objects.len() as i64
})
});
let object = image.append_to(
&mut objects, attributes, compression, pdf_version, &type1_references, color_space,
);
(id, object)
}).collect();
let mut png_group = None;
for (page_index, list) in pages.iter().enumerate() {
let png_group_ref = if !list.pdf_resources.has_page_group
&& list.items.iter().any(|item| {
matches!(item, DisplayItem::PdfImage { image, .. }
if image.image.png_transparency(pdf_version))
})
{
let id = *png_group.get_or_insert_with(|| {
objects.push(b"<< /Type /Group /S /Transparency /CS /DeviceRGB /I true >>".to_vec());
objects.len()
});
format!(" /Group {id} 0 R")
} else {
String::new()
};
let width = if final_compression.is_some() {
list.width
} else {
width
};
let height = if final_compression.is_some() {
list.height
} else {
height
};
let physical = |n: i64| -> String {
let scaled = crate::pdf_device::magnify(n, list.magnification);
if list.units == crate::render::DisplayUnits::TeX {
crate::pdf_device::print_sp(
scaled,
list.pdf.as_ref().map_or(3, |p| p.file.decimal_digits),
)
} else {
pt(scaled)
}
};
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 reserved_page = remapped.as_ref()
.and_then(|resources| resources.page_objects.get(&page_index))
.copied();
let page_id = reserved_page.unwrap_or(objects.len() + 1);
let content_id = objects.len() + 1 + usize::from(reserved_page.is_none());
let image_base = content_id + 1;
let mut xobjects = used
.iter()
.map(|(_, slot)| format!("/Im{slot} {} 0 R", image_base + *slot))
.collect::<Vec<_>>()
.join(" ");
let forms = list
.items
.iter()
.filter_map(|item| match item {
DisplayItem::PdfImage { image, .. } => Some(image.id),
_ => None,
})
.collect::<std::collections::BTreeSet<_>>();
for id in forms {
xobjects.push_str(&format!(" /PI{id} {} 0 R", form_ids[&id]));
}
let mut 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(" ");
for (face, id) in &math_font_ids {
fonts.push_str(&format!(" /M{} {id} 0 R", face.0));
}
for (face, id) in &native_font_ids {
fonts.push_str(&format!(" /N{} {id} 0 R", face.index()));
}
if !opentype.is_empty() {
let open_fonts: BTreeSet<_> = list.items.iter().filter_map(|item| match item {
DisplayItem::OpenTypeGlyph { font, .. } => Some(font.id),
_ => None,
}).collect();
for id in open_fonts {
fonts.push_str(&format!(" /U{} {} 0 R", id.index(), opentype[&id].object));
}
}
let resources = if xobjects.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 native_annotation_base = annotation_base + links.len();
let mut next_annotation = native_annotation_base;
let native_annotation_ids: Vec<_> = list.pdf_links.annotations.iter().enumerate()
.map(|(index, _)| {
remapped.as_ref()
.and_then(|resources| resources.link_objects.get(&(page_index, index)).copied())
.unwrap_or_else(|| {
let id = next_annotation;
next_annotation += 1;
id
})
})
.collect();
let xdv_annotation_ids = next_annotation..next_annotation + list.pdf_links.xdv_annotations.len();
let annotation_refs = (annotation_base..native_annotation_base)
.chain(native_annotation_ids.iter().copied())
.chain(xdv_annotation_ids.clone())
.map(|id| format!("{id} 0 R"))
.collect::<Vec<_>>()
.join(" ");
let annots = if annotation_refs.is_empty() {
String::new()
} else {
format!(" /Annots [{annotation_refs}]")
};
navigation.pages.push(page_id);
kids.push(format!("{page_id} 0 R"));
let decorated = !list.pdf_resources.attributes.is_empty();
let mut page = b"<< /Type /Page".to_vec();
if !decorated {
page.extend_from_slice(b" /Parent 2 0 R");
}
if !crate::pdf_device::page_attributes::supplies_media_box(&list.pdf_resources.attributes) {
page.extend_from_slice(format!(" /MediaBox [0 0 {} {}]", physical(width), physical(height)).as_bytes());
}
page.extend_from_slice(b" /Resources ");
let additional = remapped.as_ref().map(|resources| resources.pages[page_index].as_slice())
.unwrap_or_default();
let writes_procset = list.pdf.as_ref().is_some_and(|pdf| pdf.writes_procset());
if !additional.is_empty() || writes_procset {
page.extend_from_slice(&resources.as_bytes()[..resources.len() - 2]);
page.extend_from_slice(additional);
if writes_procset {
append_page_procset(&mut page, list, !used.is_empty());
}
page.extend_from_slice(b" >>");
} else {
page.extend_from_slice(resources.as_bytes());
}
if decorated {
page.extend_from_slice(format!(" /Contents {content_id} 0 R ").as_bytes());
page.extend_from_slice(&remapped.as_ref().expect("validated page dictionary").page_attributes[page_index]);
page.extend_from_slice(format!(" /Parent 2 0 R{annots}{png_group_ref} >>").as_bytes());
} else {
page.extend_from_slice(format!("{annots} /Contents {content_id} 0 R{png_group_ref} >>").as_bytes());
}
if let Some(id) = reserved_page {
objects[id - 1] = page;
} else {
objects.push(page);
}
let mut names = BTreeMap::new();
for (index, slot) in &used {
names.insert(*index, format!("Im{slot}"));
}
let no_font_opacity = BTreeMap::new();
let font_opacities = remapped.as_ref().map_or(
&no_font_opacity, |resources| &resources.font_opacities[page_index],
);
let content = page_content(
list,
height,
&names,
faces,
&cm_views,
&fallback_font_ids,
origin,
&opentype,
font_opacities,
);
objects.push(objects::stream(
"",
&content,
list.pdf.as_ref().map_or(0, |p| p.stream_compression),
));
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 [{} {} {} {}] {link_border} /A << /S /URI /URI ({}) >> >>",
physical(*x),
physical(height - *y - *link_height),
physical(*x + *width),
physical(height - *y),
escape(url)
)
.into_bytes(),
);
}
for (index, (annotation, id)) in list.pdf_links.annotations.iter().zip(native_annotation_ids).enumerate() {
use crate::pdf_device::links::AnnotationAction;
let [left, top, right, bottom] = annotation.rect;
let coordinates = [left, height - bottom, right, height - top].map(physical);
let entries = remapped.as_ref().and_then(|resources|
resources.annotations[page_index][index].as_deref());
let mut body = if let Some(entries) = entries {
let mut body = format!("<< /Type /Annot /Rect [{}] ", coordinates.join(" ")).into_bytes();
body.extend_from_slice(entries);
body
} else {
format!("<< /Type /Annot {} /Rect [{}] ",
annotation.attributes, coordinates.join(" ")).into_bytes()
};
match &annotation.action {
AnnotationAction::User(raw) if entries.is_none() => body.extend_from_slice(raw.as_bytes()),
AnnotationAction::User(_) => {}
AnnotationAction::GotoName(name) => {
write!(&mut body, " /Subtype /Link /A << /S /GoTo /D {} >>", pdf_text(name)).unwrap();
}
AnnotationAction::Catalog(action) => {
// A local action may use a structure or page in a later shipout.
body.extend_from_slice(b" /Subtype /Link /A ");
annotation_actions.push((id, body, action));
if id == objects.len() + 1 {
objects.push(Vec::new());
}
continue;
}
}
body.extend_from_slice(b" >>");
if id == objects.len() + 1 {
objects.push(body);
} else {
objects[id - 1] = body;
}
}
for (id, annotation) in xdv_annotation_ids.zip(&list.pdf_links.xdv_annotations) {
debug_assert_eq!(id, objects.len() + 1);
xdv_annotations.push((id, annotation));
objects.push(Vec::new());
}
for destination in &list.pdf_links.destinations {
use crate::pdf_device::links::DestinationView;
let x = physical(destination.point[0]);
let y = physical(height - destination.point[1]);
let view = match destination.view {
DestinationView::Xyz(zoom) => {
let zoom = zoom.filter(|n| *n > 0).map_or("null".to_owned(),
|n| crate::pdf_device::print_decimal(i64::from(n), 3));
format!("/XYZ {x} {y} {zoom}")
}
DestinationView::Fit => "/Fit".into(),
DestinationView::FitB => "/FitB".into(),
DestinationView::FitH => format!("/FitH {y}"),
DestinationView::FitV => format!("/FitV {x}"),
DestinationView::FitBH => format!("/FitBH {y}"),
DestinationView::FitBV => format!("/FitBV {x}"),
DestinationView::FitR([left, top, right, bottom]) => {
let coordinates = [left, height - bottom, right, height - top].map(physical);
format!("/FitR {}", coordinates.join(" "))
}
};
if let Some(number) = destination.structure {
use std::collections::btree_map::Entry;
match navigation.structures.entry(destination.destination.clone()) {
Entry::Vacant(entry) => {
let structure = remapped.as_ref().expect("structure objects were remapped")
.structure_objects[&number];
objects.push(format!("[{structure} 0 R {view}]").into_bytes());
entry.insert(objects.len());
}
Entry::Occupied(entry) => diagnostics.push(format!(
"structure destination with the same identifier ({}) has been already used, duplicate ignored",
destination_identifier(entry.key())
)),
}
} else {
let object = || format!("[{page_id} 0 R {view}]");
match &destination.destination {
DestinationId::Name(name) => {
navigation.named.entry(name.clone()).or_insert_with(object);
}
DestinationId::Number(number) => {
navigation.numbered.entry(*number).or_insert_with(|| {
objects.push(object().into_bytes());
objects.len()
});
}
}
}
}
}
objects[1] = format!(
"<< /Type /Pages /Kids [{}] /Count {}",
kids.join(" "),
pages.len()
)
.into_bytes();
if let Some(resources) = &remapped && !resources.page_tree_attributes.is_empty() {
objects[1].push(b' ');
objects[1].extend_from_slice(&resources.page_tree_attributes);
}
objects[1].extend_from_slice(b" >>");
for (id, mut body, action) in annotation_actions {
body.extend(catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics));
body.extend_from_slice(b" >>");
objects[id - 1] = body;
}
let mut catalog = "<< /Type /Catalog /Pages 2 0 R".to_owned();
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 = navigation.pages
.get(entry.page)
.or_else(|| navigation.pages.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();
catalog.push_str(&format!(" /Outlines {root_id} 0 R"));
}
let extra = unicode.and_then(|options| options.catalog);
let mut action_object = |action| {
let body = catalog_action_bytes(action, &mut navigation, &mut objects, diagnostics);
objects.push(body);
objects.len()
};
let action = extra.and_then(|extra| extra.open_action.as_ref()).map(&mut action_object);
if let Some(extra) = extra.filter(|extra| !extra.outlines.is_empty()) {
let action_ids: Vec<_> = extra.outlines.iter()
.map(|outline| action_object(&outline.action))
.collect();
let outlines = write_pdf_outlines(&extra.outlines, &action_ids, &mut objects);
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
}
let xdv = unicode.and_then(|options| options.xdv_navigation);
let keep_xdv_destinations = unicode.is_some_and(|options| options.xdv_keep_destinations);
let mut xdv_names = BTreeMap::new();
if !keep_xdv_destinations {
let mut references: Vec<_> = xdv.into_iter().flat_map(|view| view.named_references())
.chain(xdv_annotations.iter().filter_map(|(_, annotation)| annotation.named_reference()))
.collect();
references.sort_unstable_by_key(|(order, _)| *order);
for (_, name) in references {
let index = xdv_names.len();
xdv_names.entry(name.to_vec()).or_insert_with(|| format!("{index:x}").into_bytes());
}
}
for (id, annotation) in xdv_annotations {
objects[id - 1] = annotation.pdf(&navigation.pages, &xdv_names)?;
}
if let Some(xdv) = xdv {
let open_depth = unicode.unwrap().xdv_outline_open_depth;
if let Some(outlines) = xdv.write_outlines(
&navigation.pages, &mut objects, &xdv_names, open_depth,
)? {
catalog.push_str(&format!(" /Outlines {outlines} 0 R"));
}
}
if !navigation.threads.is_empty() {
let mut ids: Vec<_> = navigation.threads.into_values().collect();
ids.sort_unstable_by(|left, right| right.cmp(left));
let references: Vec<_> = ids.iter().map(|id| format!("{id} 0 R")).collect();
objects.push(format!("[{}]", references.join(" ")).into_bytes());
catalog.push_str(&format!(" /Threads {} 0 R", objects.len()));
}
let destinations = navigation.named;
let mut xdv_destinations = BTreeMap::new();
for list in pages {
for destination in &list.pdf_links.xdv_destinations {
use std::collections::btree_map::Entry;
match xdv_destinations.entry(destination.name.as_slice()) {
Entry::Vacant(entry) => {
entry.insert((destination, list.height, list.magnification));
}
Entry::Occupied(entry) => diagnostics.push(format!(
"xdvipdfmx: warning: Object @{} already defined.",
String::from_utf8_lossy(entry.key()),
)),
}
}
}
for name in xdv_names.keys() {
if !xdv_destinations.contains_key(name.as_slice()) {
diagnostics.push(format!("xdvipdfmx: warning: PDF destination {:?} not defined.",
String::from_utf8_lossy(name)));
}
}
let mut retained = BTreeMap::new();
for (name, (destination, height, magnification)) in xdv_destinations {
let name = if keep_xdv_destinations {
name
} else if let Some(reference) = xdv_names.get(name) {
reference
} else {
continue;
};
let page_object = navigation.pages.get(destination.page - 1)
.ok_or_else(|| format!("XDV destination refers to nonexistent page {}", destination.page))?;
retained.insert(name, destination.array(*page_object, height, magnification));
}
if !retained.is_empty() {
let entries: Vec<_> = retained.into_iter().map(|(name, value)| {
let name = format!("<{}>", name.iter().map(|byte| format!("{byte:02X}")).collect::<String>());
(name, value)
}).collect();
let first = &entries.first().unwrap().0;
let last = &entries.last().unwrap().0;
let names = entries.iter().map(|(name, value)| format!("{name} {value}")).collect::<Vec<_>>().join(" ");
objects.push(format!("<< /Names [{names}] /Limits [{first} {last}] >>").into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
} else if !destinations.is_empty() {
let mut entries = Vec::with_capacity(destinations.len());
let first = pdf_text(destinations.first_key_value().unwrap().0);
let last = pdf_text(destinations.last_key_value().unwrap().0);
for (name, destination) in destinations {
objects.push(destination.into_bytes());
entries.push(format!("{} {} 0 R", pdf_text(&name), objects.len()));
}
objects.push(format!("<< /Names [{}] /Limits [{first} {last}] >>",
entries.join(" ")).into_bytes());
catalog.push_str(&format!(" /Names << /Dests {} 0 R >>", objects.len()));
}
objects[0] = if let Some(xdv) = xdv {
xdv.finish_catalog(&catalog, &navigation.pages)?
} else {
let mut catalog = catalog.into_bytes();
if let Some(extra) = extra {
let entries = remapped.as_ref().and_then(|resources| resources.catalog.as_deref())
.unwrap_or(&extra.entries);
if !entries.is_empty() {
catalog.push(b'\n');
catalog.extend_from_slice(entries);
catalog.push(b'\n');
}
if let Some(id) = action {
write!(&mut catalog, " /OpenAction {id} 0 R").unwrap();
}
}
catalog.extend_from_slice(b" >>");
catalog
};
if let Some(level) = final_compression {
let device = pages[0].pdf.as_ref().expect("validated native PDF options");
let info = if unicode.is_some_and(|options| options.omit_info) {
None
} else {
let dictionary = match unicode {
Some(options) => {
let info = crate::pdf_device::PdfInfo {
entries: remapped.as_ref().and_then(|resources| resources.info.as_deref())
.unwrap_or(options.info.entries),
date: options.info.date,
};
if device.driver == crate::pdf_device::PdfDriver::Xdv {
crate::pdf_device::xdv_document::information_dictionary(info, diagnostics)?
} else {
native_information_dictionary(info)
}
}
None => metadata_object(metadata)
.map(String::into_bytes)
.unwrap_or_else(|| b"<< /Producer (texrra Route-D native) >>".to_vec()),
};
objects.push(dictionary);
Some(objects.len())
};
return Ok(objects::serialize(&objects, info, &device.file, level.clamp(0, 9) as u8));
}
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(),
);
Ok(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 truetype_pdf_keeps_cmmi_for_math() {
let mut list = crate::render::DisplayList::default();
list.width = 612 * 65_536;
list.height = 792 * 65_536;
list.push(crate::render::DisplayItem::Text {
font: crate::render::FontFace::MathItalic,
x: 72 * 65_536,
y: 100 * 65_536,
size: 10 * 65_536,
text: "α".to_string(),
});
list.push(crate::render::DisplayItem::Text {
font: crate::render::FontFace::Roman,
x: 72 * 65_536,
y: 120 * 65_536,
size: 10 * 65_536,
text: "Body".to_string(),
});
let pdf = super::display_lists_to_pdf_with_truetype_and_metadata(
&[list],
612 * 65_536,
792 * 65_536,
super::PageOrigin::default(),
&super::PdfMetadata::default(),
);
let text = String::from_utf8_lossy(&pdf);
assert!(text.contains("/BaseFont /CMMI10"), "missing CMMI10");
assert!(
text.contains("/BaseFont /LiberationSerif"),
"missing body face"
);
}
#[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(),
magnification: 1000,
..Default::default()
};
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(),
magnification: 1000,
..Default::default()
},
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
},
];
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"));
}
#[test]
fn metadata_writes_the_pdf_info_dictionary() {
let pages = vec![DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
}];
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(),
magnification: 1000,
..Default::default()
},
DisplayList {
width: 612 * 65536,
height: 792 * 65536,
items: Vec::new(),
images: Vec::new(),
magnification: 1000,
..Default::default()
},
];
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"));
}
#[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 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}");
}
}