Resolve imported PDF Type 1 device fonts in native previews
This commit is contained in:
1 parent
c0970bdbf6
commit
b640b26eff
12 files changed
+586
-106
No files matched your search
@@ -304,6 +304,17 @@ impl DecodedType1 {
|
||||
}
|
||||
|
||||
impl NativeFontCache {
|
||||
/// Resolve a PDF device font using the same exact program identity as native text.
|
||||
pub fn pdf_device_type1(
|
||||
&self,
|
||||
files: &mut impl crate::execution::SourceProvider,
|
||||
name: &str,
|
||||
from: &str,
|
||||
) -> Result<Option<Arc<Type1Font>>, String> {
|
||||
Ok(device_type1::find_program(files, self, name, None, from)?
|
||||
.map(|(_, decoded)| decoded.program.clone()))
|
||||
}
|
||||
|
||||
// The caller reads the actual resource and verifies its bytes on this
|
||||
// revision before asking for the decoded representation.
|
||||
fn type1(&self, resource: &LoadedResource, transform: Type1Transform) -> Result<Arc<DecodedType1>, String> {
|
||||
@@ -429,7 +440,8 @@ fn resolve_physical_fonts(
|
||||
let Some((first, _, _)) = used.values().next() else {
|
||||
return Ok(());
|
||||
};
|
||||
let captured = pages.iter().rev().find_map(|page| page.pdf_font_bindings.as_deref());
|
||||
let captured_bindings = pages.iter().rev().filter_map(|page| page.pdf_font_bindings.as_deref());
|
||||
let captured = captured_bindings.clone().next();
|
||||
let default_map = if captured.is_none() {
|
||||
load_map(files, "pdftex.map", &first.resource.version.path)?
|
||||
} else {
|
||||
@@ -448,8 +460,11 @@ fn resolve_physical_fonts(
|
||||
for (id, (font, slots, expanded)) in used {
|
||||
let entry = if font.pdf_space_font && font.name == "pdftexspace" {
|
||||
Some(Arc::new(dedicated_space_map(&font)))
|
||||
} else if let Some(bindings) = captured {
|
||||
bindings.font(&font)?
|
||||
} else if captured.is_some() {
|
||||
// Pending Form lists may precede the last real page in execution
|
||||
// order, even when the host appends them for physical font painting.
|
||||
captured_bindings.clone().find_map(|bindings| bindings.font(&font).ok())
|
||||
.ok_or_else(|| format!("PDF font {} has no captured map binding", font.name))?
|
||||
} else if let Some(map) = &default_map {
|
||||
find_map_entry(map, &font.name, files, &mut subfonts)?.map(Arc::new)
|
||||
} else {
|
||||
|
||||
@@ -1,11 +1,11 @@
|
||||
//! Unembedded pdfTeX Type 1 fonts retain a device name and optional local outlines.
|
||||
use super::{
|
||||
NativeFont, NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource,
|
||||
DecodedType1, NativeFont, NativeFontCache, NativeFontPaint, NativeFontProgram, actual_resource,
|
||||
encoding_vector, map::MapEntry, verify_resource,
|
||||
};
|
||||
use crate::{
|
||||
execution::SourceProvider,
|
||||
resources::ResourceKind,
|
||||
resources::{ResourceKind, ResourceVersion},
|
||||
type1::{Type1Font, Type1Transform, standard_encoding},
|
||||
};
|
||||
use std::{
|
||||
@@ -46,6 +46,43 @@ fn standard_flags(name: &str) -> Option<i32> {
|
||||
})
|
||||
}
|
||||
|
||||
pub(super) fn find_program(
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
name: &str,
|
||||
tfm: Option<&str>,
|
||||
from: &str,
|
||||
) -> Result<Option<(ResourceVersion, Arc<DecodedType1>)>, String> {
|
||||
if name.is_empty()
|
||||
|| name
|
||||
.bytes()
|
||||
.any(|byte| matches!(byte, b'/' | b'\\' | b':' | 0))
|
||||
{
|
||||
return Ok(None);
|
||||
}
|
||||
let lowercase = name.to_ascii_lowercase();
|
||||
let candidates = std::iter::once(name)
|
||||
.chain(tfm.filter(|tfm| *tfm != name))
|
||||
.chain(
|
||||
(lowercase != name && tfm != Some(lowercase.as_str())).then_some(lowercase.as_str()),
|
||||
);
|
||||
for candidate in candidates {
|
||||
for extension in ["pfb", "pfa"] {
|
||||
let file = format!("{candidate}.{extension}");
|
||||
let Some(resource) = files.optional_font_file(ResourceKind::Type1, &file, from)? else {
|
||||
continue;
|
||||
};
|
||||
let resource = verify_resource(resource, ResourceKind::Type1, &file)?;
|
||||
if let Ok(decoded) = cache.type1(&resource, Type1Transform::default())
|
||||
&& decoded.program.name == name
|
||||
{
|
||||
return Ok(Some((resource.version, decoded)));
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(None)
|
||||
}
|
||||
|
||||
pub(super) fn resolve(
|
||||
files: &mut impl SourceProvider,
|
||||
cache: &NativeFontCache,
|
||||
@@ -56,31 +93,11 @@ pub(super) fn resolve(
|
||||
) -> Result<NativeFontPaint, String> {
|
||||
let from = entry.from.to_string_lossy();
|
||||
let mut resources: Vec<_> = entry.version.iter().cloned().collect();
|
||||
let mut preview = None;
|
||||
let candidates = [name, font.name.as_str()];
|
||||
for (index, candidate) in candidates.into_iter().enumerate() {
|
||||
if index == 1 && candidate == name {
|
||||
break;
|
||||
}
|
||||
for extension in ["pfb", "pfa"] {
|
||||
let file = format!("{candidate}.{extension}");
|
||||
let Some(resource) = files.optional_font_file(ResourceKind::Type1, &file, &from)?
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
let resource = verify_resource(resource, ResourceKind::Type1, &file)?;
|
||||
if let Ok(decoded) = cache.type1(&resource, Type1Transform::default())
|
||||
&& decoded.program.name == name
|
||||
{
|
||||
resources.push(resource.version);
|
||||
preview = Some(decoded);
|
||||
break;
|
||||
}
|
||||
}
|
||||
if preview.is_some() {
|
||||
break;
|
||||
}
|
||||
}
|
||||
let preview =
|
||||
find_program(files, cache, name, Some(&font.name), &from)?.map(|(version, decoded)| {
|
||||
resources.push(version);
|
||||
decoded
|
||||
});
|
||||
let encoding = if let Some(file) = &entry.encoding {
|
||||
let encoding = actual_resource(files, ResourceKind::Encoding, file, &from)?;
|
||||
let vector = encoding_vector(&encoding.data)?;
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
//! Native image XObjects and the resource objects reachable from their content.
|
||||
mod bmp;
|
||||
mod destinations;
|
||||
mod device_fonts;
|
||||
mod jpeg;
|
||||
mod icc;
|
||||
mod imported_fonts;
|
||||
@@ -56,6 +57,8 @@ pub struct PdfImage {
|
||||
pub(crate) color_space: Option<i32>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
imported_fonts: Vec<imported_fonts::ImportedType1>,
|
||||
#[serde(default, skip_serializing_if = "Vec::is_empty")]
|
||||
device_type1_fonts: Vec<String>,
|
||||
#[serde(default, skip_serializing_if = "Option::is_none")]
|
||||
pdftex_source: Option<imports::SourceGraph>,
|
||||
}
|
||||
@@ -419,6 +422,7 @@ impl PdfImage {
|
||||
objects: Vec::new(),
|
||||
color_space: self.color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
}
|
||||
}
|
||||
@@ -558,6 +562,7 @@ impl PdfImage {
|
||||
objects,
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
}
|
||||
}
|
||||
@@ -607,6 +612,7 @@ impl PdfImage {
|
||||
objects: vec![vec![part]],
|
||||
color_space: None,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
})
|
||||
}
|
||||
@@ -896,12 +902,18 @@ impl PdfImage {
|
||||
objects: graph.bodies,
|
||||
color_space: None,
|
||||
imported_fonts,
|
||||
device_type1_fonts: device_fonts::capture(&doc, inherited(b"Resources")),
|
||||
pdftex_source,
|
||||
},
|
||||
[left, bottom],
|
||||
))
|
||||
}
|
||||
|
||||
/// Unembedded Type 1 names recorded from this selected PDF page.
|
||||
pub fn device_type1_fonts(&self) -> &[String] {
|
||||
&self.device_type1_fonts
|
||||
}
|
||||
|
||||
pub(crate) fn extent(&self) -> [f64; 2] {
|
||||
self.extent.map(f64::from_bits)
|
||||
}
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
//! Device fonts reachable from the selected page's drawing resources.
|
||||
use super::resolved;
|
||||
use lopdf::{Dictionary, Document, Object};
|
||||
use std::collections::{BTreeSet, HashSet};
|
||||
|
||||
pub(super) fn capture(doc: &Document, resources: Option<&Object>) -> Vec<String> {
|
||||
let Some(resources) = resources.and_then(|value| resolved(doc, value).ok()) else {
|
||||
return Vec::new();
|
||||
};
|
||||
let mut pending = vec![resources];
|
||||
let mut seen = HashSet::new();
|
||||
let mut names = BTreeSet::new();
|
||||
while let Some(resources) = pending.pop() {
|
||||
let Ok(dict) = resources.as_dict() else {
|
||||
continue;
|
||||
};
|
||||
if !seen.insert(std::ptr::from_ref(dict)) {
|
||||
continue;
|
||||
}
|
||||
if let Some(fonts) = get(doc, dict, b"Font").and_then(|value| value.as_dict().ok()) {
|
||||
for (_, font) in fonts.iter() {
|
||||
if let Some(font) = resolved(doc, font)
|
||||
.ok()
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
{
|
||||
capture_font(doc, font, &mut names, &mut pending);
|
||||
}
|
||||
}
|
||||
}
|
||||
for group in [b"XObject".as_slice(), b"Pattern"] {
|
||||
if let Some(objects) = get(doc, dict, group).and_then(|value| value.as_dict().ok()) {
|
||||
for (_, object) in objects.iter() {
|
||||
if let Ok(Object::Stream(stream)) = resolved(doc, object)
|
||||
&& let Some(resources) = get(doc, &stream.dict, b"Resources")
|
||||
{
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if let Some(states) = get(doc, dict, b"ExtGState").and_then(|value| value.as_dict().ok()) {
|
||||
for (_, state) in states.iter() {
|
||||
let Some(state) = resolved(doc, state)
|
||||
.ok()
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
if let Some(values) =
|
||||
get(doc, state, b"Font").and_then(|value| value.as_array().ok())
|
||||
&& let Some(font) = values
|
||||
.first()
|
||||
.and_then(|value| resolved(doc, value).ok())
|
||||
.and_then(|value| value.as_dict().ok())
|
||||
{
|
||||
capture_font(doc, font, &mut names, &mut pending);
|
||||
}
|
||||
if let Some(mask) = get(doc, state, b"SMask").and_then(|value| value.as_dict().ok())
|
||||
&& let Some(Object::Stream(form)) = get(doc, mask, b"G")
|
||||
&& let Some(resources) = get(doc, &form.dict, b"Resources")
|
||||
{
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
names.into_iter().collect()
|
||||
}
|
||||
|
||||
fn get<'a>(doc: &'a Document, dict: &'a Dictionary, key: &[u8]) -> Option<&'a Object> {
|
||||
resolved(doc, dict.get(key).ok()?).ok()
|
||||
}
|
||||
|
||||
fn capture_font<'a>(
|
||||
doc: &'a Document,
|
||||
font: &'a Dictionary,
|
||||
names: &mut BTreeSet<String>,
|
||||
pending: &mut Vec<&'a Object>,
|
||||
) {
|
||||
match get(doc, font, b"Subtype").and_then(|value| value.as_name().ok()) {
|
||||
Some(b"Type1") => {
|
||||
let Some(name) = get(doc, font, b"BaseFont")
|
||||
.and_then(|value| value.as_name().ok())
|
||||
.and_then(|bytes| std::str::from_utf8(bytes).ok())
|
||||
else {
|
||||
return;
|
||||
};
|
||||
let descriptor =
|
||||
get(doc, font, b"FontDescriptor").and_then(|value| value.as_dict().ok());
|
||||
if !descriptor.is_some_and(|dict| {
|
||||
[b"FontFile".as_slice(), b"FontFile2", b"FontFile3"]
|
||||
.into_iter()
|
||||
.any(|key| dict.has(key))
|
||||
}) {
|
||||
names.insert(name.to_owned());
|
||||
}
|
||||
}
|
||||
Some(b"Type3") => {
|
||||
if let Some(resources) = get(doc, font, b"Resources") {
|
||||
pending.push(resources);
|
||||
}
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
}
|
||||
@@ -147,6 +147,7 @@ pub(super) fn read(
|
||||
objects: vec![vec![Part::Png(image)]],
|
||||
color_space,
|
||||
imported_fonts: Vec::new(),
|
||||
device_type1_fonts: Vec::new(),
|
||||
pdftex_source: None,
|
||||
restored_pdf_origin: None,
|
||||
},
|
||||
|
||||
Reference in new issue
Block a user