use crate::{DictItem, Op};
fn is_text_state(op: &Op) -> bool {
matches!(
op,
Op::SetFont { .. }
| Op::SetFillColor { .. }
| Op::SetOutlineColor { .. }
| Op::SetTextRenderingMode { .. }
| Op::SetCharacterSpacing { .. }
| Op::SetWordSpacing { .. }
| Op::SetHorizontalScaling { .. }
| Op::SetLineOffset { .. }
| Op::SetLineHeight { .. }
)
}
fn positions_first(ops: &[Op]) -> bool {
for op in ops {
match op {
Op::SetTextMatrix { .. } => return true,
Op::ShowText { .. }
| Op::SetTextCursor { .. }
| Op::AddLineBreak
| Op::MoveTextCursorAndSetLeading { .. }
| Op::MoveToNextLineShowText { .. }
| Op::SetSpacingMoveAndShowText { .. } => return false,
Op::EndTextSection => return true, _ => {}
}
}
true
}
fn actual_text(op: &Op) -> Option<&[u8]> {
let Op::BeginMarkedContentWithProperties { tag, properties: DictItem::Dict { map } } = op else {
return None;
};
if tag != "Span" || map.len() != 1 {
return None;
}
match map.get("ActualText") {
Some(DictItem::String { data, literal: false }) if data.starts_with(&[0xFE, 0xFF]) => Some(data),
_ => None,
}
}
fn span_baseline(ops: &[Op]) -> Option<f32> {
let mut depth = 0usize;
for op in ops {
match op {
Op::SetTextMatrix { matrix } if depth == 0 => return Some(matrix.as_array()[5]),
Op::BeginMarkedContent { .. } | Op::BeginMarkedContentWithProperties { .. } => depth += 1,
Op::EndMarkedContent | Op::EndMarkedContentWithProperties => {
if depth == 0 {
return None;
}
depth -= 1;
}
_ => {}
}
}
None
}
pub(crate) fn merge_text_runs(ops: &[Op]) -> Vec<Op> {
merge_actual_text_spans(merge_text_objects(ops))
}
fn merge_text_objects(ops: &[Op]) -> Vec<Op> {
let mut out = Vec::with_capacity(ops.len());
let mut font = None;
let mut fill = None;
let mut i = 0;
while i < ops.len() {
let op = &ops[i];
if let Op::EndTextSection = op {
let mut j = i + 1;
while j < ops.len() && is_text_state(&ops[j]) {
j += 1;
}
if matches!(ops.get(j), Some(Op::StartTextSection)) && positions_first(&ops[j + 1..]) {
for state in &ops[i + 1..j] {
push_state(state, &mut out, &mut font, &mut fill);
}
i = j + 1;
continue;
}
}
match op {
Op::SetFont { .. } | Op::SetFillColor { .. } => push_state(op, &mut out, &mut font, &mut fill),
Op::RestoreGraphicsState | Op::LoadGraphicsState { .. } => {
font = None;
fill = None;
out.push(op.clone());
}
_ => out.push(op.clone()),
}
i += 1;
}
out
}
fn push_state(
op: &Op,
out: &mut Vec<Op>,
font: &mut Option<(crate::ops::PdfFontHandle, crate::Pt)>,
fill: &mut Option<crate::Color>,
) {
match op {
Op::SetFont { font: f, size } => {
let state = Some((f.clone(), *size));
if *font == state {
return;
}
*font = state;
}
Op::SetFillColor { col } => {
if fill.as_ref() == Some(col) {
return;
}
*fill = Some(col.clone());
}
_ => {}
}
out.push(op.clone());
}
fn merge_actual_text_spans(ops: Vec<Op>) -> Vec<Op> {
let mut out: Vec<Op> = Vec::with_capacity(ops.len());
let mut open: Vec<Option<(usize, Option<f32>)>> = Vec::new();
let mut previous: Option<(usize, usize, Option<f32>)> = None; for (k, op) in ops.iter().enumerate() {
match op {
Op::BeginMarkedContentWithProperties { .. } if actual_text(op).is_some() => {
let baseline = span_baseline(&ops[k + 1..]);
if let Some((bdc, emc, prev_baseline)) = previous.take() {
if baseline.is_some() && baseline == prev_baseline {
out.remove(emc);
append_actual_text(&mut out[bdc], &actual_text(op).unwrap()[2..]);
open.push(Some((bdc, baseline)));
continue;
}
}
open.push(Some((out.len(), baseline)));
out.push(op.clone());
}
Op::BeginMarkedContent { .. } | Op::BeginMarkedContentWithProperties { .. } => {
previous = None;
open.push(None);
out.push(op.clone());
}
Op::EndMarkedContent | Op::EndMarkedContentWithProperties => {
out.push(op.clone());
previous = match open.pop() {
Some(Some((bdc, baseline))) => Some((bdc, out.len() - 1, baseline)),
_ => None,
};
}
_ => {
if !is_text_state(op) {
previous = None;
}
out.push(op.clone());
}
}
}
out
}
fn append_actual_text(bdc: &mut Op, more: &[u8]) {
if let Op::BeginMarkedContentWithProperties { properties: DictItem::Dict { map }, .. } = bdc {
if let Some(DictItem::String { data, .. }) = map.get_mut("ActualText") {
data.extend_from_slice(more);
}
}
}