use lopdf::{Object, StringFormat};
use serde_derive::{Deserialize, Serialize};
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
pub struct Codepoint {
pub gid: u16,
pub offset: f32,
pub cid: Option<String>,
}
impl Codepoint {
pub fn new(gid: u16, offset: f32) -> Self {
Self { gid, offset, cid: None }
}
pub fn with_cid(gid: u16, offset: f32, cid: String) -> Self {
Self { gid, offset, cid: Some(cid) }
}
}
#[derive(Debug, Clone, PartialEq, PartialOrd, Deserialize, Serialize)]
#[serde(untagged)]
pub enum TextItem {
Text(String),
Offset(f32),
GlyphIds(Vec<Codepoint>),
}
impl From<String> for TextItem {
fn from(s: String) -> Self {
TextItem::Text(s)
}
}
impl From<&str> for TextItem {
fn from(s: &str) -> Self {
TextItem::Text(s.to_string())
}
}
impl From<f32> for TextItem {
fn from(n: f32) -> Self {
TextItem::Offset(n)
}
}
impl From<f64> for TextItem {
fn from(n: f64) -> Self {
TextItem::Offset(n as f32)
}
}
impl From<i32> for TextItem {
fn from(n: i32) -> Self {
TextItem::Offset(n as f32)
}
}
impl From<i64> for TextItem {
fn from(n: i64) -> Self {
TextItem::Offset(n as f32)
}
}
impl From<u8> for TextItem {
fn from(n: u8) -> Self {
TextItem::Offset(n as f32)
}
}
pub trait CMap {
fn map_bytes(&self, bytes: &[u8]) -> String;
}
pub fn win_ansi_char(b: u8) -> char {
match b {
0x20..=0x7E => b as char,
0xA0..=0xFF => b as char,
0x80 => '\u{20AC}', 0x82 => '\u{201A}', 0x83 => '\u{0192}', 0x84 => '\u{201E}', 0x85 => '\u{2026}', 0x86 => '\u{2020}', 0x87 => '\u{2021}', 0x88 => '\u{02C6}', 0x89 => '\u{2030}', 0x8A => '\u{0160}', 0x8B => '\u{2039}', 0x8C => '\u{0152}', 0x8E => '\u{017D}', 0x91 => '\u{2018}', 0x92 => '\u{2019}', 0x93 => '\u{201C}', 0x94 => '\u{201D}', 0x95 => '\u{2022}', 0x96 => '\u{2013}', 0x97 => '\u{2014}', 0x98 => '\u{02DC}', 0x99 => '\u{2122}', 0x9A => '\u{0161}', 0x9B => '\u{203A}', 0x9C => '\u{0153}', 0x9E => '\u{017E}', 0x9F => '\u{0178}', b'\t' | b'\n' | b'\r' => b as char,
_ => '\u{FFFD}',
}
}
pub fn decode_simple_font_bytes(bytes: &[u8], to_unicode: Option<&crate::cmap::ToUnicodeCMap>) -> String {
let mut out = String::with_capacity(bytes.len());
for &b in bytes {
if let Some(s) = to_unicode.and_then(|c| c.lookup_string(b as u32)) {
out.push_str(&s);
} else {
out.push(win_ansi_char(b));
}
}
out
}
pub fn decode_pdf_string(obj: &Object, to_unicode: Option<&impl CMap>) -> String {
if let Object::String(ref bytes, format) = obj {
match format {
StringFormat::Literal => {
if let Some(cmap) = to_unicode {
cmap.map_bytes(bytes)
} else {
String::from_utf8_lossy(bytes).into_owned()
}
}
StringFormat::Hexadecimal => {
if let Some(utf16_bytes) = bytes.strip_prefix(&[0xFE, 0xFF]) {
let utf16_iter = utf16_bytes.chunks_exact(2).filter_map(|pair| match *pair {
[hi, lo] => Some(u16::from_be_bytes([hi, lo])),
_ => None,
});
String::from_utf16(&utf16_iter.collect::<Vec<_>>()).unwrap_or_default()
} else {
if let Some(cmap) = to_unicode {
cmap.map_bytes(bytes)
} else {
String::from_utf8_lossy(bytes).into_owned()
}
}
}
}
} else {
String::new()
}
}
pub fn decode_tj_operands(operands: &[Object], to_unicode: Option<&impl CMap>) -> Vec<TextItem> {
let mut items = Vec::new();
for obj in operands {
match obj {
Object::String(_, _) => {
let s = decode_pdf_string(obj, to_unicode);
items.push(TextItem::Text(s));
}
Object::Integer(i) => {
items.push(TextItem::Offset(*i as f32));
}
Object::Real(r) => {
items.push(TextItem::Offset(*r));
}
_ => {
}
}
}
items
}
pub fn decode_tj_operands_as_glyph_ids(operands: &[Object]) -> Vec<TextItem> {
let mut items = Vec::new();
let mut current_glyphs = Vec::new();
for obj in operands {
match obj {
Object::String(bytes, _) => {
if bytes.len() >= 2 && bytes.len() % 2 == 0 {
for chunk in bytes.chunks_exact(2) {
if let [hi, lo] = *chunk {
let gid = u16::from_be_bytes([hi, lo]);
current_glyphs.push(Codepoint::new(gid, 0.0));
}
}
} else {
for &byte in bytes {
current_glyphs.push(Codepoint::new(byte as u16, 0.0));
}
}
}
Object::Integer(i) => {
if !current_glyphs.is_empty() {
items.push(TextItem::GlyphIds(std::mem::take(&mut current_glyphs)));
}
items.push(TextItem::Offset(*i as f32));
}
Object::Real(r) => {
if !current_glyphs.is_empty() {
items.push(TextItem::GlyphIds(std::mem::take(&mut current_glyphs)));
}
items.push(TextItem::Offset(*r));
}
_ => {
}
}
}
if !current_glyphs.is_empty() {
items.push(TextItem::GlyphIds(current_glyphs));
}
items
}
pub fn decode_tj_string_as_glyph_ids(bytes: &[u8]) -> Vec<TextItem> {
let mut glyphs = Vec::new();
if bytes.len() >= 2 && bytes.len().is_multiple_of(2) {
for chunk in bytes.chunks_exact(2) {
if let [hi, lo] = *chunk {
let gid = u16::from_be_bytes([hi, lo]);
glyphs.push(Codepoint::new(gid, 0.0));
}
}
} else {
for &byte in bytes {
glyphs.push(Codepoint::new(byte as u16, 0.0));
}
}
if glyphs.is_empty() {
vec![]
} else {
vec![TextItem::GlyphIds(glyphs)]
}
}
pub fn encode_pdf_string_literal(s: &str) -> String {
let mut result = String::with_capacity(s.len() + 2);
result.push('(');
for c in s.chars() {
match c {
'(' => result.push_str("\\("),
')' => result.push_str("\\)"),
'\\' => result.push_str("\\\\"),
'\n' => result.push_str("\\n"),
'\r' => result.push_str("\\r"),
'\t' => result.push_str("\\t"),
'\x08' => result.push_str("\\b"),
'\x0C' => result.push_str("\\f"),
_ => result.push(c),
}
}
result.push(')');
result
}
pub fn encode_pdf_string_hex(s: &str) -> String {
let mut utf16: Vec<u16> = Vec::new();
utf16.push(0xFEFF); utf16.extend(s.encode_utf16());
let mut bytes = Vec::with_capacity(utf16.len() * 2);
for code in utf16 {
bytes.extend_from_slice(&code.to_be_bytes());
}
let hex: String = bytes.iter().map(|b| format!("{:02X}", b)).collect();
format!("<{}>", hex)
}
pub fn encode_pdf_string_minimal(s: &str) -> String {
let literal = encode_pdf_string_literal(s);
let hex = encode_pdf_string_hex(s);
if literal.len() <= hex.len() {
literal
} else {
hex
}
}
pub fn encode_text_items(items: &[TextItem]) -> Vec<Object> {
let mut objs = Vec::new();
for item in items {
match item {
TextItem::Text(s) => {
let pdf_str = encode_pdf_string_minimal(s);
if let Some(inner) = pdf_str.strip_prefix('<').and_then(|t| t.strip_suffix('>')) {
let bytes: Vec<u8> = inner
.as_bytes()
.chunks_exact(2)
.filter_map(|pair| {
let digits = std::str::from_utf8(pair).ok()?;
u8::from_str_radix(digits, 16).ok()
})
.collect();
objs.push(Object::String(bytes, StringFormat::Hexadecimal));
} else {
objs.push(Object::String(s.as_bytes().to_vec(), StringFormat::Literal));
}
}
TextItem::Offset(n) => {
objs.push(Object::Real(*n));
}
TextItem::GlyphIds(glyphs) => {
for codepoint in glyphs {
let bytes = codepoint.gid.to_be_bytes().to_vec();
objs.push(Object::String(bytes, StringFormat::Hexadecimal));
if codepoint.offset != 0.0 {
objs.push(Object::Integer(codepoint.offset as i64));
}
}
}
}
}
objs
}
pub fn actual_text_span(text: &str) -> crate::Op {
let mut data = vec![0xFE, 0xFF];
for u in text.encode_utf16() {
data.extend_from_slice(&u.to_be_bytes());
}
let mut map = std::collections::BTreeMap::new();
map.insert(
"ActualText".to_string(),
crate::DictItem::String {
data,
literal: false,
},
);
crate::Op::BeginMarkedContentWithProperties {
tag: "Span".to_string(),
properties: crate::DictItem::Dict { map },
}
}
#[cfg(feature = "text_layout")]
#[derive(Debug, Clone, PartialEq)]
pub struct PlacedGlyph {
pub font: usize,
pub gid: u16,
pub x: f32,
pub y: f32,
pub text: String,
}
#[cfg(feature = "text_layout")]
pub fn show_placed_glyphs(
fonts: &[(crate::FontId, &crate::font::AzulParsedFont)],
size: crate::Pt,
glyphs: &[PlacedGlyph],
actual_text: Option<&str>,
) -> Vec<crate::Op> {
use crate::Op;
fn flush(ops: &mut Vec<Op>, items: &mut Vec<TextItem>, run: &mut Vec<Codepoint>) {
if !run.is_empty() {
items.push(TextItem::GlyphIds(std::mem::take(run)));
}
if !items.is_empty() {
ops.push(Op::ShowText {
items: std::mem::take(items),
});
}
}
let mut ops = Vec::new();
if fonts.is_empty() || size.0 <= 0.0 || glyphs.is_empty() {
return ops;
}
let span = actual_text.filter(|t| !t.is_empty());
if let Some(text) = span {
ops.push(actual_text_span(text));
}
let mut pen = 0.0f32;
let mut rise = 0.0f32;
let mut current: Option<usize> = None;
let mut items: Vec<TextItem> = Vec::new();
let mut run: Vec<Codepoint> = Vec::new();
for g in glyphs {
let font = if g.font < fonts.len() { g.font } else { 0 };
let Some((font_id, face)) = fonts.get(font) else {
continue;
};
if current != Some(font) {
flush(&mut ops, &mut items, &mut run);
ops.push(Op::SetFont {
font: crate::ops::PdfFontHandle::External(font_id.clone()),
size,
});
current = Some(font);
}
if (g.y - rise).abs() > 1e-5 {
flush(&mut ops, &mut items, &mut run);
ops.push(Op::SetLineOffset { multiplier: g.y });
rise = g.y;
}
let kern = (g.x - pen) / size.0 * 1000.0;
if kern.abs() > 1e-3 {
match run.last_mut() {
Some(last) => last.offset -= kern,
None => items.push(TextItem::Offset(-kern)),
}
}
run.push(Codepoint {
gid: g.gid,
offset: 0.0,
cid: Some(g.text.clone()),
});
pen = g.x + glyph_pdf_width(face, g.gid) as f32 / 1000.0 * size.0;
}
flush(&mut ops, &mut items, &mut run);
if rise != 0.0 {
ops.push(Op::SetLineOffset { multiplier: 0.0 });
}
if span.is_some() {
ops.push(Op::EndMarkedContent);
}
ops
}
#[cfg(feature = "text_layout")]
pub fn glyph_pdf_width(font: &crate::font::AzulParsedFont, gid: u16) -> i64 {
let units_per_em = f32::from(font.pdf_font_metrics.units_per_em);
if units_per_em <= 0.0 {
return 0;
}
font.get_or_decode_glyph(gid)
.map(|g| (f32::from(g.horz_advance) * 1000.0 / units_per_em) as i64)
.unwrap_or(0)
}