Write PDF interword spaces with actual device fonts

This commit is contained in:
gloamxun committed 2026-11-21 03:09:10 +08:00
1 parent b93d5f55da
commit 514a2d3344
24 files changed
+664 -65

No files matched your search

+294 -44
View File
@@ -3,8 +3,15 @@ use super::PageContent;
use crate::{
execution::FontId,
native_font::NativeFont,
pdf_device::{divide_scaled, print_decimal, print_sp},
pdf_device::{
PdfGraphics, PdfLiteralMode, divide_scaled, print_decimal, print_sp,
text_spaces::{ResolvedSpaceFont, SpaceOperation, SpacePlan, SpaceUse},
},
render::{DisplayItem, DisplayList},
};
use std::collections::{BTreeMap, BTreeSet};
const ONE_BP: i64 = 65_782;
pub(super) struct NativeText {
font: Option<FontId>,
effective_size: i64,
@@ -25,6 +32,8 @@ impl NativeText {
slot: u8,
height: i64,
digits: u8,
space: Option<SpaceUse>,
dedicated: Option<&ResolvedSpaceFont>,
) {
let first = text.is_none();
let state = text.get_or_insert_with(|| {
@@ -39,46 +48,39 @@ impl NativeText {
opened: false,
}
});
if state.font != Some(font.id) {
state.close_string(out);
let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
state.effective_size = size;
state.font = Some(font.id);
out.push_str(&format!(
"/N{} {} Tf\n",
font.id.index(),
print_decimal(number, 4)
));
if space == Some(SpaceUse::InFont) {
out.push_str("<20>");
let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
state.delta_h += Self::char_advance(font, paint, b' ', size);
}
if space == Some(SpaceUse::Dedicated) {
let dedicated = dedicated.expect("resolved PDF space font");
state.select_font(out, &dedicated.font);
out.push_str("( ) Tj\n");
}
state.select_font(out, font);
if state.expansion != font.expansion {
state.close_string(out);
state.expansion = font.expansion;
out.push_str(&format!(
"{} Tz\n",
print_decimal(i64::from(1000 + font.expansion), 1)
));
if !out.measuring {
out.push_str(&format!(
"{} Tz\n",
print_decimal(i64::from(1000 + font.expansion), 1)
));
}
}
let horizontal_size = if font.expansion == 0 {
state.effective_size
} else {
crate::pdf_device::magnify(state.effective_size, 1000 + font.expansion)
};
let (mut shift, shift_out) =
divide_scaled(x - state.start_h - state.delta_h, horizontal_size, 3);
let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0;
let (v, v_out) = if (state.v - y).abs() >= minimum {
divide_scaled(state.v - y, 6_578_176, digits + 2)
} else {
(0, 0)
};
if first || v != 0 || shift.abs() >= 32768 {
let (mut shift, shift_out) = state.horizontal_move(x, state.effective_size, font.expansion);
let (v, v_out) = state.vertical_move(y, digits);
if first || v != 0 || shift.abs() >= 32768 || space == Some(SpaceUse::Dedicated) {
state.close_string(out);
let (h, h_out) = divide_scaled(x - state.start_h, 6_578_176, digits + 2);
out.push_str(&format!(
"{} {} Td\n",
print_decimal(h, digits),
print_decimal(v, digits)
));
if !out.measuring {
out.push_str(&format!(
"{} {} Td\n",
print_decimal(h, digits),
print_decimal(v, digits)
));
}
state.start_h += h_out;
state.v -= v_out;
state.delta_h = 0;
@@ -89,27 +91,102 @@ impl NativeText {
state.opened = true;
}
if shift != 0 {
out.push_str(&format!(" {} ", -shift));
if !out.measuring {
out.push_str(&format!(" {} ", -shift));
}
state.delta_h += shift_out;
}
out.push_str(&format!("<{slot:02X}>"));
if !out.measuring {
out.push_str(&format!("<{slot:02X}>"));
}
state.delta_h += Self::char_advance(font, paint, slot, state.effective_size);
}
fn select_font(&mut self, out: &mut PageContent, font: &NativeFont) {
if self.font != Some(font.id) {
self.close_string(out);
let (number, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
self.effective_size = size;
self.font = Some(font.id);
if !out.measuring {
out.push_str(&format!(
"/N{} {} Tf\n",
font.id.index(),
print_decimal(number, 4)
));
}
}
}
fn char_advance(
font: &NativeFont,
paint: &crate::native_font::NativeFontPaint,
slot: u8,
size: i64,
) -> i64 {
let advance = match &paint.program {
crate::native_font::NativeFontProgram::Pk(pk) => pk.advances[&slot],
crate::native_font::NativeFontProgram::Type1(_) => {
divide_scaled(
font.metrics().width(char::from(slot)),
state.effective_size,
4,
)
.1
divide_scaled(font.metrics().width(char::from(slot)), size, 4).1
}
};
state.delta_h += if font.expansion == 0 {
if font.expansion == 0 {
advance
} else {
crate::pdf_device::magnify(advance, 1000 + font.expansion)
};
}
}
fn horizontal_move(&self, x: i64, size: i64, expansion: i32) -> (i64, i64) {
divide_scaled(
x - self.start_h - self.delta_h,
Self::expanded_size(size, expansion),
3,
)
}
fn expanded_size(size: i64, expansion: i32) -> i64 {
if expansion == 0 {
size
} else {
crate::pdf_device::magnify(size, 1000 + expansion)
}
}
fn vertical_move(&self, y: i64, digits: u8) -> (i64, i64) {
let minimum = divide_scaled(6_578_176, 10i64.pow(u32::from(digits) + 2), 0).0;
if (self.v - y).abs() >= minimum {
divide_scaled(self.v - y, 6_578_176, digits + 2)
} else {
(0, 0)
}
}
pub(super) fn explicit_space(
text: &mut Option<Self>,
out: &mut PageContent,
x: i64,
y: i64,
height: i64,
digits: u8,
dedicated: &ResolvedSpaceFont,
) {
Self::glyph(
text,
out,
x,
y,
&dedicated.font,
&dedicated.paint,
b' ',
height,
digits,
None,
None,
);
Self::break_string(text, out);
}
fn close_string(&mut self, out: &mut PageContent) {
if self.opened {
out.push_str("] TJ\n");
@@ -133,6 +210,179 @@ impl NativeText {
}
}
#[derive(Default)]
pub(super) struct FontHistory {
used: BTreeSet<FontId>,
first_scalable: BTreeMap<String, FontId>,
}
impl FontHistory {
fn record(&mut self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) {
if self.used.insert(font.id)
&& matches!(
paint.program,
crate::native_font::NativeFontProgram::Type1(_)
)
&& !self.first_scalable.contains_key(&font.name)
{
self.first_scalable.insert(font.name.clone(), font.id);
}
}
fn has_space(&self, font: &NativeFont, paint: &crate::native_font::NativeFontPaint) -> bool {
// Only the first font for a shared scalable TFM gets the space test.
self.first_scalable
.get(&font.name)
.is_none_or(|id| *id == font.id)
&& paint.has_pdf_space(font)
}
}
/// Determine real font use with the same text moves used by the PDF writer.
pub(super) fn plan_spaces(
page: &DisplayList,
fonts: &mut FontHistory,
load: impl FnOnce() -> Result<ResolvedSpaceFont, String>,
) -> Result<SpacePlan, String> {
let Some(settings) = &page.pdf_text_spaces else {
for item in &page.items {
if let DisplayItem::NativeGlyph {
font,
paint: Some(paint),
..
} = item
{
fonts.record(font, paint);
}
}
return Ok(SpacePlan::default());
};
let digits = page.pdf.as_ref().map_or(3, |pdf| pdf.file.decimal_digits);
let mut automatic = settings.automatic_at_start;
let mut plan = SpacePlan::default();
let mut load = Some(load);
let mut text: Option<NativeText> = None;
let mut out = PageContent::measuring();
for (index, item) in page.items.iter().enumerate() {
match item {
DisplayItem::PdfTextSpace {
operation: SpaceOperation::Automatic(enabled),
..
} => {
automatic = *enabled;
}
DisplayItem::PdfTextSpace {
x,
y,
operation: SpaceOperation::Explicit,
} => {
if plan.dedicated.is_none() {
plan.dedicated = Some(load.take().expect("space font loader used once")()?);
}
let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint);
NativeText::explicit_space(
&mut text,
&mut out,
*x,
*y,
page.height,
digits,
dedicated,
);
}
DisplayItem::NativeGlyph {
x,
y,
font,
paint,
slot,
..
} => {
let paint = paint
.as_ref()
.ok_or("native font was not resolved before planning PDF text spaces")?;
let (_, size) = divide_scaled(font.size_sp(), 6_578_176, 6);
if NativeText::expanded_size(size, font.expansion) <= 0 {
return Err("native PDF font size rounds to zero in the pdfTeX profile".into());
}
let already_used = fonts.used.contains(&font.id);
fonts.record(font, paint);
let mut space = None;
if let Some(cursor) = &text
&& automatic
{
let (width, shrink) = settings
.parameters
.get(font.id.index() as usize)
.copied()
.unwrap_or_else(|| {
(
font.metrics().param(1) as i32,
font.metrics().param(3) as i32,
)
});
let prior_size = NativeText::expanded_size(size, cursor.expansion);
let movement = if prior_size > 0 {
cursor.horizontal_move(*x, size, cursor.expansion).1
} else {
0
};
if i64::from(width) > ONE_BP
&& movement > i64::from(width) - i64::from(shrink) - ONE_BP / 10
&& cursor.vertical_move(*y, digits).0 == 0
{
if fonts.has_space(font, paint) {
if cursor.opened && (cursor.font == Some(font.id) || already_used) {
space = Some(SpaceUse::InFont);
let previous = cursor.font.expect("open text string has a font");
plan.in_font.insert(previous);
plan.spaces_in_previous_font |= previous != font.id;
}
} else {
space = Some(SpaceUse::Dedicated);
if plan.dedicated.is_none() {
plan.dedicated =
Some(load.take().expect("space font loader used once")()?);
}
let dedicated = plan.dedicated.as_ref().unwrap();
fonts.record(&dedicated.font, &dedicated.paint);
}
}
}
if let Some(space) = space {
plan.before_glyph.insert(index, space);
}
NativeText::glyph(
&mut text,
&mut out,
*x,
*y,
font,
paint,
*slot,
page.height,
digits,
space,
plan.dedicated.as_ref(),
);
}
DisplayItem::PdfGraphics {
operation:
PdfGraphics::Literal {
mode: PdfLiteralMode::Direct,
..
},
..
} => {
NativeText::break_string(&mut text, &mut out);
}
_ => NativeText::finish(&mut text, &mut out),
}
}
Ok(plan)
}
pub(super) fn rule(
out: &mut PageContent,
x: i64,