Support unembedded pdfTeX Type 1 device fonts in export and preview

This commit is contained in:
gloamxun committed 2026-11-28 03:44:29 +08:00
1 parent 60d67bbb7b
commit c0970bdbf6
10 files changed
+466 -34

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
use lopdf::{Dictionary, Document, Stream};
use std::{collections::BTreeMap, sync::Arc};
use texrra_tex_core::{
native_font::NativeFontProgram,
render::{DisplayItem, DisplayList},
type1::Type1Font,
};
#[derive(Default, PartialEq, Eq)]
pub(super) struct PreviewFonts {
programs: BTreeMap<String, Arc<Type1Font>>,
missing: bool,
conflict: Option<String>,
}
impl PreviewFonts {
pub(super) fn collect(pages: &[DisplayList]) -> Self {
let mut fonts = Self::default();
if pages.iter().any(DisplayList::has_embedded_pdf) {
for page in pages {
fonts.collect_from(page);
}
}
fonts
}
fn collect_from(&mut self, page: &DisplayList) {
for item in &page.items {
let DisplayItem::NativeGlyph {
paint: Some(paint), ..
} = item
else {
continue;
};
if let NativeFontProgram::DeviceType1(device) = &paint.program {
if let Some(program) = &device.preview_program {
if let Some(captured) = self.programs.get(&device.name) {
if !Arc::ptr_eq(captured, program) && captured != program {
self.conflict = Some(device.name.clone());
}
} else {
self.programs.insert(device.name.clone(), program.clone());
}
} else {
self.missing = true;
}
}
}
for form in &page.forms {
self.collect_from(&form.list);
}
}
pub(super) fn includes_device_fonts(&self) -> bool {
self.missing || !self.programs.is_empty()
}
/// For PDF-backed previews, attach the same captured local font programs
/// used by the native SVG path to an in-memory copy of the PDF.
pub(super) fn attach(&self, pdf: &[u8]) -> Result<Option<Vec<u8>>, String> {
if let Some(name) = &self.conflict {
return Err(format!(
"conflicting actual fonts for PDF preview device name {name}"
));
}
if self.programs.is_empty() {
return Ok(None);
}
let mut document = Document::load_mem(pdf)
.map_err(|error| format!("could not read PDF device fonts for preview: {error}"))?;
let descriptors: Vec<_> = document
.objects
.iter()
.filter_map(|(&id, object)| {
let descriptor = object.as_dict().ok()?;
if descriptor.get(b"Type").ok()?.as_name().ok()? != b"FontDescriptor"
|| [b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
.into_iter()
.any(|key| descriptor.has(key))
{
return None;
}
let name = descriptor.get(b"FontName").ok()?;
let (_, name) = document.dereference(name).ok()?;
let name = std::str::from_utf8(name.as_name().ok()?).ok()?;
Some((id, self.programs.get(name)?))
})
.collect();
if descriptors.is_empty() {
return Ok(None);
}
let mut streams = BTreeMap::new();
for (id, font) in descriptors {
let stream = *streams.entry(&font.name).or_insert_with(|| {
let mut dictionary = Dictionary::new();
dictionary.set("Length1", font.length1 as i64);
dictionary.set("Length2", font.length2 as i64);
dictionary.set("Length3", font.length3 as i64);
document.add_object(Stream::new(dictionary, font.program.clone()))
});
let descriptor = document.get_object_mut(id).unwrap().as_dict_mut().unwrap();
descriptor.set("FontFile", stream);
}
let mut bytes = Vec::new();
document
.save_to(&mut bytes)
.map_err(|error| format!("could not prepare PDF device fonts for preview: {error}"))?;
Ok(Some(bytes))
}
}