use serde_derive::{Deserialize, Serialize};
pub use crate::text::TextItem;
use crate::{
color::Color,
font::ParsedFont,
form_walk::{form_in, scope_of, FormWalk},
xobject::FormXObject,
graphics::{
Line, LineCapStyle, LineDashPattern, LineJoinStyle, Point, Polygon, Rect, TextRenderingMode,
},
matrix::{CurTransMat, TextMatrix},
units::{Mm, Pt},
BuiltinFont, DictItem, ExtendedGraphicsStateId, PatternId, ShadingId, FontId, LayerInternalId, LinkAnnotation,
PdfResources, PdfToSvgOptions, PdfWarnMsg, RenderingIntent, XObjectId, XObjectTransform,
};
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub enum PdfFontHandle {
Builtin(BuiltinFont),
External(FontId),
}
impl PdfFontHandle {
pub fn get_resource_name(&self) -> String {
match self {
PdfFontHandle::Builtin(bf) => bf.get_pdf_id().to_string(),
PdfFontHandle::External(fid) => fid.0.clone(),
}
}
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct PdfPage {
pub media_box: Rect,
pub trim_box: Rect,
pub crop_box: Rect,
pub ops: Vec<Op>,
}
impl PdfPage {
pub fn new(width: Mm, height: Mm, ops: Vec<Op>) -> Self {
Self {
media_box: Rect::from_wh(width.into(), height.into()),
trim_box: Rect::from_wh(width.into(), height.into()),
crop_box: Rect::from_wh(width.into(), height.into()),
ops,
}
}
pub(crate) fn get_media_box(&self) -> lopdf::Object {
self.media_box.to_array().into()
}
pub(crate) fn get_trim_box(&self) -> lopdf::Object {
self.trim_box.to_array().into()
}
pub(crate) fn get_crop_box(&self) -> lopdf::Object {
self.crop_box.to_array().into()
}
pub fn to_svg(
&self,
resources: &PdfResources,
opts: &PdfToSvgOptions,
warnings: &mut Vec<PdfWarnMsg>,
) -> String {
crate::render::render_to_svg(self, resources, opts, warnings)
}
pub async fn to_svg_async(
&self,
resources: &PdfResources,
opts: &PdfToSvgOptions,
warnings: &mut Vec<PdfWarnMsg>,
) -> String {
crate::render::render_to_svg_async(self, resources, opts, warnings).await
}
pub fn get_xobject_ids(&self) -> Vec<XObjectId> {
self.ops
.iter()
.filter_map(|s| match s {
Op::UseXobject { id, .. } => Some(id.clone()),
_ => None,
})
.collect()
}
pub fn get_external_font_ids(&self) -> Vec<FontId> {
let mut ids = Vec::new();
for op in &self.ops {
if let Op::SetFont {
font: PdfFontHandle::External(id),
..
} = op
{
if !ids.contains(id) {
ids.push(id.clone());
}
}
}
ids
}
pub fn get_layers(&self) -> Vec<LayerInternalId> {
self.ops
.iter()
.filter_map(|s| match s {
Op::BeginLayer { layer_id } => Some(layer_id.clone()),
_ => None,
})
.collect()
}
pub fn extract_text(&self, resources: &PdfResources) -> Vec<String> {
let mut extraction = TextExtraction::new();
extraction.run(&self.ops, resources, &mut FormWalk::new());
extraction.finish()
}
fn glyph_id_to_char(font: &ParsedFont, gid: u16) -> Option<char> {
for codepoint in 0..0x10000u32 {
if let Some(mapped_gid) = font.lookup_glyph_index(codepoint) {
if mapped_gid == gid {
return char::from_u32(codepoint);
}
}
}
None
}
}
struct TextExtraction<'a> {
text_chunks: Vec<String>,
current_chunk: String,
in_text_section: bool,
cur_text_cursor: Point,
cur_text_matrix_y: Option<f32>,
current_font: Option<&'a ParsedFont>,
cur_font_size: f32,
pen_x: Option<f32>,
}
impl<'a> TextExtraction<'a> {
fn new() -> Self {
TextExtraction {
text_chunks: Vec::new(),
current_chunk: String::new(),
in_text_section: false,
cur_text_cursor: Point {
x: Pt(0.0),
y: Pt(0.0),
},
cur_text_matrix_y: None,
current_font: None,
cur_font_size: 12.0,
pen_x: None,
}
}
fn run(&mut self, ops: &[Op], scope: &'a PdfResources, walk: &mut FormWalk) {
for op in ops {
match op {
Op::StartTextSection => {
self.in_text_section = true;
}
Op::EndTextSection => {
self.in_text_section = false;
if !self.current_chunk.is_empty() {
self.text_chunks.push(self.current_chunk.trim().to_string());
self.current_chunk = String::new();
}
}
Op::SetFont { font, size } => {
self.cur_font_size = size.0;
match font {
crate::ops::PdfFontHandle::External(font_id) => {
self.current_font =
scope.fonts.map.get(font_id).map(|pf| &pf.parsed_font);
}
crate::ops::PdfFontHandle::Builtin(_) => {
self.current_font = None;
}
}
}
Op::SetTextMatrix { matrix } => {
let m = matrix.as_array();
let (new_x, new_y) = (m[4], m[5]);
match self.cur_text_matrix_y {
Some(prev_y) if (prev_y - new_y).abs() > 0.5 => {
self.current_chunk.push_str("\r\n");
}
Some(_) => {
let gap_threshold = (self.cur_font_size * 0.15).max(0.1);
let is_gap = match self.pen_x {
Some(px) => new_x - px > gap_threshold,
None => false,
};
if is_gap
&& !self.current_chunk.is_empty()
&& !self.current_chunk.ends_with(char::is_whitespace)
{
self.current_chunk.push(' ');
}
}
None => {}
}
self.cur_text_matrix_y = Some(new_y);
self.pen_x = Some(new_x);
}
Op::SetTextCursor { pos } => {
if (self.cur_text_cursor.y.0.abs() - pos.y.0.abs()).abs() > 3.0 {
self.current_chunk.push_str("\r\n");
}
self.cur_text_cursor = *pos;
self.pen_x = None;
}
Op::ShowText { items } if self.in_text_section => {
for item in items {
match item {
TextItem::Offset(o) => {
if *o < -100.0 {
self.current_chunk.push(' ');
}
if let Some(px) = self.pen_x.as_mut() {
*px -= o / 1000.0 * self.cur_font_size;
}
}
TextItem::Text(t) => {
self.current_chunk.push_str(t);
if let Some(px) = self.pen_x.as_mut() {
let mut adv_em = 0.0f32;
for c in t.chars() {
adv_em += self
.current_font
.and_then(|f| {
f.lookup_glyph_index(c as u32)
.map(|gid| glyph_advance_em(f, gid))
})
.unwrap_or(0.5);
}
*px += adv_em * self.cur_font_size;
}
}
TextItem::GlyphIds(glyphs) => {
for codepoint in glyphs {
if let Some(cid) = codepoint.cid.as_ref() {
self.current_chunk.push_str(cid);
} else if let Some(c) = self.current_font.and_then(|font| {
PdfPage::glyph_id_to_char(font, codepoint.gid)
}) {
self.current_chunk.push(c);
} else {
self.current_chunk.push('\u{FFFD}');
}
if let Some(px) = self.pen_x.as_mut() {
let adv_em = self
.current_font
.map(|f| glyph_advance_em(f, codepoint.gid))
.unwrap_or(0.5);
*px += adv_em * self.cur_font_size
- codepoint.offset / 1000.0 * self.cur_font_size;
}
}
}
}
}
}
Op::AddLineBreak if self.in_text_section => {
self.current_chunk.push_str("\r\n");
self.pen_x = None;
}
Op::MoveTextCursorAndSetLeading { .. } if self.in_text_section => {
self.current_chunk.push_str("\r\n");
self.pen_x = None;
}
Op::MoveToNextLineShowText { text } if self.in_text_section => {
self.current_chunk.push_str("\r\n");
self.current_chunk.push_str(text);
self.current_chunk.push(' ');
}
Op::SetSpacingMoveAndShowText { text, .. } if self.in_text_section => {
self.current_chunk.push_str("\r\n");
self.current_chunk.push_str(text);
self.current_chunk.push(' ');
}
Op::UseXobject { id, .. } => {
if let Some(form) = form_in(scope, id) {
if walk.enter(form).is_ok() {
self.run_form(form, scope, walk);
walk.leave();
}
}
}
_ => {}
}
}
}
fn run_form(&mut self, form: &'a FormXObject, outer: &'a PdfResources, walk: &mut FormWalk) {
let saved = (
self.in_text_section,
self.cur_text_cursor,
self.cur_text_matrix_y,
self.current_font,
self.cur_font_size,
self.pen_x,
);
self.in_text_section = false;
self.run(&form.ops, scope_of(form, outer), walk);
(
self.in_text_section,
self.cur_text_cursor,
self.cur_text_matrix_y,
self.current_font,
self.cur_font_size,
self.pen_x,
) = saved;
}
fn finish(mut self) -> Vec<String> {
if !self.current_chunk.is_empty() {
self.text_chunks.push(self.current_chunk.trim().to_string());
}
self.text_chunks.retain(|chunk| !chunk.is_empty());
self.text_chunks
}
}
#[cfg(feature = "text_layout")]
pub(crate) fn glyph_advance_em(font: &ParsedFont, gid: u16) -> f32 {
let upm = font.font_metrics.units_per_em as f32;
if upm <= 0.0 {
return 0.5;
}
let adv = font.get_horizontal_advance(gid) as f32;
if adv <= 0.0 {
0.5
} else {
adv / upm
}
}
#[cfg(not(feature = "text_layout"))]
pub(crate) fn glyph_advance_em(font: &ParsedFont, gid: u16) -> f32 {
let upm = font.units_per_em as f32;
if upm <= 0.0 {
return 0.5;
}
match font.get_glyph_width(gid) {
Some(w) if w > 0 => w as f32 / upm,
_ => 0.5,
}
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LayerIntent {
View,
Design,
}
impl LayerIntent {
pub fn to_string(&self) -> &'static str {
match self {
LayerIntent::View => "View",
LayerIntent::Design => "Design",
}
}
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case")]
pub enum LayerSubtype {
Artwork,
}
impl LayerSubtype {
pub fn to_string(&self) -> &'static str {
match self {
LayerSubtype::Artwork => "Artwork",
}
}
}
#[derive(Debug, PartialEq, Clone, Serialize, Deserialize)]
#[serde(rename_all = "camelCase")]
pub struct Layer {
pub name: String,
pub creator: String,
pub intent: LayerIntent,
pub usage: LayerSubtype,
}
impl Layer {
pub fn new(name: &str) -> Self {
Self {
name: name.to_string(),
creator: "Adobe Illustrator 14.0".to_string(),
intent: LayerIntent::Design,
usage: LayerSubtype::Artwork,
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(rename_all = "kebab-case", tag = "type", content = "data")]
pub enum Op {
Marker {
id: String,
},
SetColorSpaceStroke {
id: String,
},
SetColorSpaceFill {
id: String,
},
BeginLayer {
layer_id: LayerInternalId,
},
EndLayer,
SaveGraphicsState,
RestoreGraphicsState,
LoadGraphicsState {
gs: ExtendedGraphicsStateId,
},
StartTextSection,
EndTextSection,
SetFont {
font: PdfFontHandle,
size: Pt,
},
ShowText {
items: Vec<TextItem>,
},
AddLineBreak,
SetLineHeight {
lh: Pt,
},
SetWordSpacing {
pt: Pt,
},
SetTextCursor {
pos: Point,
},
SetFillColor {
col: Color,
},
SetOutlineColor {
col: Color,
},
SetOutlineThickness {
pt: Pt,
},
SetLineDashPattern {
dash: LineDashPattern,
},
SetLineJoinStyle {
join: LineJoinStyle,
},
SetLineCapStyle {
cap: LineCapStyle,
},
SetMiterLimit {
limit: Pt,
},
SetTextRenderingMode {
mode: TextRenderingMode,
},
SetCharacterSpacing {
multiplier: f32,
},
SetLineOffset {
multiplier: f32,
},
DrawLine {
line: Line,
},
DrawRectangle {
rectangle: Rect,
},
DrawPolygon {
polygon: Polygon,
},
SetTransformationMatrix {
matrix: CurTransMat,
},
SetTextMatrix {
matrix: TextMatrix,
},
LinkAnnotation {
link: LinkAnnotation,
},
UseXobject {
id: XObjectId,
transform: XObjectTransform,
},
MoveTextCursorAndSetLeading {
tx: f32,
ty: f32,
},
SetRenderingIntent {
intent: RenderingIntent,
},
SetHorizontalScaling {
percent: f32,
},
BeginInlineImage,
BeginInlineImageData,
EndInlineImage,
BeginMarkedContent {
tag: String,
},
BeginMarkedContentWithProperties {
tag: String,
properties: DictItem,
},
BeginOptionalContent {
layer_id: LayerInternalId,
},
DefineMarkedContentPoint {
tag: String,
properties: Vec<DictItem>,
},
EndMarkedContent,
EndMarkedContentWithProperties,
EndOptionalContent,
BeginCompatibilitySection,
EndCompatibilitySection,
MoveToNextLineShowText {
text: String,
},
SetSpacingMoveAndShowText {
word_spacing: f32,
char_spacing: f32,
text: String,
},
PaintShading {
id: ShadingId,
},
SetFillPattern {
id: PatternId,
#[serde(default)]
color: Option<Color>,
},
SetOutlinePattern {
id: PatternId,
#[serde(default)]
color: Option<Color>,
},
Unknown {
key: String,
value: Vec<DictItem>,
},
}