use std::{
borrow::Cow,
collections::{BTreeMap, BTreeSet},
io::Write,
};
use lopdf::{
content::Operation as LoOp,
Dictionary as LoDictionary,
Object::{Array, Dictionary, Integer, Name, Null, Real, Reference, String as LoString},
Stream as LoStream,
StringFormat::{Hexadecimal, Literal},
};
use serde_derive::{Deserialize, Serialize};
mod form_xobject;
mod pattern;
mod standards;
use form_xobject::{write_xobjects, SaveScope};
use pattern::{pattern_color_space_dict, write_patterns};
use crate::{
color::IccProfile,
font::ParsedFont,
form_walk::inheriting_streams,
Actions, BuiltinFont, Color, ColorArray, Destination, FontId, IccProfileType,
ImageOptimizationOptions, Line, LinkAnnotation, Op, PaintMode, PdfDocument,
PdfDocumentInfo, PdfResources, PdfWarnMsg, Polygon, TextItem, XObject,
XObjectId,
};
#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, PartialOrd)]
pub struct PdfSaveOptions {
#[serde(default = "default_optimize")]
pub optimize: bool,
#[serde(default = "default_subset_fonts")]
pub subset_fonts: bool,
#[serde(default = "default_secure")]
pub secure: bool,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub image_optimization: Option<ImageOptimizationOptions>,
}
const fn default_optimize() -> bool {
true
}
const fn default_subset_fonts() -> bool {
true
}
const fn default_secure() -> bool {
true
}
impl Default for PdfSaveOptions {
fn default() -> Self {
Self {
optimize: default_optimize(),
subset_fonts: default_subset_fonts(),
secure: default_secure(),
image_optimization: Some(ImageOptimizationOptions::default()),
}
}
}
pub fn init_doc_and_resources(
pdf: &PdfDocument,
opts: &PdfSaveOptions,
) -> (lopdf::Document, lopdf::Dictionary) {
let mut warnings = Vec::new();
let streams = document_streams(pdf);
let fonts = fonts_to_save(
&pdf.resources.fonts.map,
&streams,
pdf.metadata.info.conformance.must_embed_fonts(),
);
let (font_infos, _) =
prepare_fonts_for_streams(&fonts, &streams, opts.subset_fonts, &mut warnings);
write_document_xobjects(pdf, opts, &font_infos, &mut warnings)
}
fn document_streams(pdf: &PdfDocument) -> Vec<&[Op]> {
let mut streams: Vec<&[Op]> = pdf.pages.iter().map(|page| page.ops.as_slice()).collect();
streams.extend(inheriting_streams(&pdf.resources));
streams
}
fn write_document_xobjects(
pdf: &PdfDocument,
opts: &PdfSaveOptions,
font_infos: &BTreeMap<FontId, RuntimeFontInfo>,
warnings: &mut Vec<PdfWarnMsg>,
) -> (lopdf::Document, lopdf::Dictionary) {
let mut doc = lopdf::Document::with_version("1.3");
doc.reference_table.cross_reference_type = lopdf::xref::XrefType::CrossReferenceTable;
let scope = SaveScope {
font_infos,
xobjects: &pdf.resources.xobjects.map,
depth: 0,
must_embed_fonts: pdf.metadata.info.conformance.must_embed_fonts(),
};
let global_xobject_dict =
write_xobjects(&mut doc, &pdf.resources.xobjects.map, &scope, opts, warnings);
(doc, global_xobject_dict)
}
pub fn serialize_pdf<W: Write>(
pdf: &PdfDocument,
opts: &PdfSaveOptions,
mut writer: &mut W,
warnings: &mut Vec<PdfWarnMsg>,
) {
let mut doc = to_lopdf_doc(pdf, opts, warnings);
if opts.optimize {
crate::optimize::drop_redundant_actual_text(&mut doc);
doc.compress();
}
let _ = doc.save_to(&mut writer);
}
pub fn to_lopdf_doc(
pdf: &PdfDocument,
opts: &PdfSaveOptions,
warnings: &mut Vec<PdfWarnMsg>,
) -> lopdf::Document {
let streams = document_streams(pdf);
let fonts = fonts_to_save(
&pdf.resources.fonts.map,
&streams,
pdf.metadata.info.conformance.must_embed_fonts(),
);
let (font_infos, subset_fonts) =
prepare_fonts_for_streams(&fonts, &streams, opts.subset_fonts, warnings);
#[cfg(feature = "text_layout")]
for (font_id, font_info) in &font_infos {
warnings.extend(crate::variable_font::unresolved_variation_warning(font_id, &font_info.parsed_font));
}
let (mut doc, global_xobject_dict) =
write_document_xobjects(pdf, opts, &font_infos, warnings);
let pages_id = doc.new_object_id();
let mut catalog = LoDictionary::from_iter(vec![
("Type", "Catalog".into()),
("PageLayout", "OneColumn".into()),
("PageMode", "UseNone".into()),
("Pages", Reference(pages_id)),
]);
let layer_ids = if !pdf.resources.layers.map.is_empty() {
let map = pdf
.resources
.layers
.map
.iter()
.map(|(id, layer)| {
let usage_ocg_dict = LoDictionary::from_iter(vec![
("Type", Name("OCG".into())),
(
"CreatorInfo",
Dictionary(LoDictionary::from_iter(vec![
("Creator", LoString(layer.creator.clone().into(), Literal)),
("Subtype", Name(layer.usage.to_string().into())),
])),
),
]);
let usage_ocg_dict_ref = doc.add_object(Dictionary(usage_ocg_dict));
let intent_arr = Array(vec![Name("View".into()), Name("Design".into())]);
let intent_arr_ref = doc.add_object(intent_arr);
let pdf_id = doc.add_object(Dictionary(LoDictionary::from_iter(vec![
("Type", Name("OCG".into())),
("Name", LoString(layer.name.to_string().into(), Literal)),
("Intent", Reference(intent_arr_ref)),
("Usage", Reference(usage_ocg_dict_ref)),
])));
(id.clone(), pdf_id)
})
.collect::<BTreeMap<_, _>>();
let flattened_ocg_list = map.values().map(|s| Reference(*s)).collect::<Vec<_>>();
catalog.set(
"OCProperties",
Dictionary(LoDictionary::from_iter(vec![
("OCGs", Array(flattened_ocg_list.clone())),
(
"D",
Dictionary(LoDictionary::from_iter(vec![
("Order", Array(flattened_ocg_list.clone())),
("RBGroups", Array(vec![])),
("ON", Array(flattened_ocg_list)),
])),
),
])),
);
Some(map)
} else {
None
};
let global_font_dict = write_font_dict(
&mut doc,
&subset_fonts,
used_builtin_fonts(&streams),
pdf.metadata.info.conformance.must_embed_fonts(),
warnings,
);
let global_font_dict_id = doc.add_object(global_font_dict);
let global_xobject_dict_id = doc.add_object(global_xobject_dict);
let global_extgstate_dict_id = doc.add_object(extgstate_dict(&pdf.resources));
let global_shading_dict_id = doc.add_object(shading_dict(&pdf.resources));
let global_pattern_dict = write_patterns(
&mut doc,
&pdf.resources.patterns.map,
&SaveScope {
font_infos: &font_infos,
xobjects: &pdf.resources.xobjects.map,
depth: 0,
must_embed_fonts: pdf.metadata.info.conformance.must_embed_fonts(),
},
opts,
warnings,
);
let global_pattern_dict_id =
(!global_pattern_dict.is_empty()).then(|| doc.add_object(global_pattern_dict));
let global_color_space_dict = pattern_color_space_dict(&streams);
let global_color_space_dict_id =
(!global_color_space_dict.is_empty()).then(|| doc.add_object(global_color_space_dict));
let page_ids_reserved = pdf
.pages
.iter()
.map(|_| doc.new_object_id())
.collect::<Vec<_>>();
let page_ids = pdf
.pages
.iter()
.zip(page_ids_reserved.iter())
.map(|(page, page_id)| {
let mut page_resources = LoDictionary::new();
if let Some(ref layer_ids) = layer_ids {
let page_layers = page
.ops
.iter()
.filter_map(|op| {
if let Op::BeginLayer { layer_id } = op {
layer_ids
.get(layer_id)
.map(|ocg_obj_id| (layer_id.0.clone(), *ocg_obj_id))
} else {
None
}
})
.collect::<Vec<_>>();
if !page_layers.is_empty() {
page_resources.set(
"Properties",
LoDictionary::from_iter(
page_layers
.iter()
.map(|(name, ocg_obj_id)| (name.as_str(), Reference(*ocg_obj_id))),
),
);
}
}
let mut links = Vec::new();
for op in &page.ops {
if let Op::LinkAnnotation { link } = op {
let mut annot = link_annotation_to_dict(link, &page_ids_reserved);
if pdf.metadata.info.conformance.is_pdfa() {
annot.set("F", Integer(4));
}
links.push(Dictionary(annot))
}
}
page_resources.set("Font", Reference(global_font_dict_id));
page_resources.set("XObject", Reference(global_xobject_dict_id));
page_resources.set("ExtGState", Reference(global_extgstate_dict_id));
page_resources.set("Shading", Reference(global_shading_dict_id));
if let Some(id) = global_pattern_dict_id {
page_resources.set("Pattern", Reference(id));
}
if let Some(id) = global_color_space_dict_id {
page_resources.set("ColorSpace", Reference(id));
}
let merged_ops;
let ops = if opts.optimize {
merged_ops = crate::text_merge::merge_text_runs(&page.ops);
&merged_ops
} else {
&page.ops
};
let layer_stream = translate_operations(
ops,
&font_infos,
&pdf.resources.xobjects.map,
opts.secure,
warnings,
); let merged_layer_stream =
LoStream::new(LoDictionary::new(), layer_stream);
let page_obj = LoDictionary::from_iter(vec![
("Type", "Page".into()),
("MediaBox", page.get_media_box()),
("TrimBox", page.get_trim_box()),
("CropBox", page.get_crop_box()),
("Parent", Reference(pages_id)),
("Resources", Reference(doc.add_object(page_resources))),
("Contents", Reference(doc.add_object(merged_layer_stream))),
("Annots", Array(links)),
]);
doc.set_object(*page_id, page_obj);
*page_id
})
.collect::<Vec<_>>();
if !pdf.bookmarks.map.is_empty() {
let bookmarks_id = doc.new_object_id();
let mut bookmarks_sorted = pdf.bookmarks.map.iter().collect::<Vec<_>>();
bookmarks_sorted.sort_by(|(id, v), (id2, v2)| (v.page, id).cmp(&(v2.page, id2)));
let bookmarks_sorted = bookmarks_sorted
.into_iter()
.filter_map(|(k, v)| {
let page_obj_id = page_ids.get(v.page.saturating_sub(1)).cloned()?;
Some((k, &v.name, page_obj_id))
})
.collect::<Vec<_>>();
let bookmark_ids = bookmarks_sorted
.iter()
.map(|(id, name, page_id)| {
let newid = doc.new_object_id();
(id, name, page_id, newid)
})
.collect::<Vec<_>>();
let first = bookmark_ids.first().map(|s| s.3);
let last = bookmark_ids.last().map(|s| s.3);
for (i, (_id, name, pageid, self_id)) in bookmark_ids.iter().enumerate() {
let prev = i
.checked_sub(1)
.and_then(|prev| bookmark_ids.get(prev))
.map(|s| s.3);
let next = bookmark_ids.get(i + 1).map(|s| s.3);
let dest = Array(vec![Reference(*(*pageid)), "XYZ".into(), Null, Null, Null]);
let mut dict = LoDictionary::from_iter(vec![
("Parent", Reference(bookmarks_id)),
("Title", encode_text_to_utf16be(name)),
("Dest", dest),
]);
if let Some(prev) = prev {
dict.set("Prev", Reference(prev));
}
if let Some(next) = next {
dict.set("Next", Reference(next));
}
doc.set_object(*self_id, dict);
}
if let (Some(first), Some(last)) = (first, last) {
let bookmarks_list = LoDictionary::from_iter(vec![
("Type", "Outlines".into()),
("Count", Integer(bookmark_ids.len() as i64)),
("First", Reference(first)),
("Last", Reference(last)),
]);
doc.set_object(bookmarks_id, bookmarks_list);
catalog.set("Outlines", Reference(bookmarks_id));
catalog.set("PageMode", LoString("UseOutlines".into(), Literal));
}
}
doc.set_object(
pages_id,
LoDictionary::from_iter(vec![
("Type", "Pages".into()),
("Count", Integer(page_ids.len() as i64)),
(
"Kids",
Array(page_ids.iter().map(|q| Reference(*q)).collect::<Vec<_>>()),
),
]),
);
standards::apply(pdf, &mut doc, &mut catalog, warnings);
let catalog_id = doc.add_object(catalog);
let document_info_id = doc.add_object(Dictionary(docinfo_to_dict(&pdf.metadata.info)));
let instance_id = crate::utils::random_character_string_32();
let document_id = crate::utils::random_character_string_32();
doc.trailer.set("Root", Reference(catalog_id));
doc.trailer.set("Info", Reference(document_info_id));
doc.trailer.set(
"ID",
Array(vec![
LoString(document_id.as_bytes().to_vec(), Literal),
LoString(instance_id.as_bytes().to_vec(), Literal),
]),
);
doc
}
pub fn serialize_pdf_into_bytes(
pdf: &PdfDocument,
opts: &PdfSaveOptions,
warnings: &mut Vec<PdfWarnMsg>,
) -> Vec<u8> {
let mut bytes = Vec::new();
let mut writer = std::io::BufWriter::new(&mut bytes);
serialize_pdf(pdf, opts, &mut writer, warnings);
std::mem::drop(writer);
bytes
}
fn used_builtin_fonts(streams: &[&[Op]]) -> BTreeSet<BuiltinFont> {
streams
.iter()
.flat_map(|ops| ops.iter())
.filter_map(|op| match op {
Op::SetFont { font: crate::ops::PdfFontHandle::Builtin(font), .. } => Some(*font),
_ => None,
})
.collect()
}
fn fonts_to_save<'a>(
fonts: &'a BTreeMap<FontId, crate::font::PdfFont>,
streams: &[&[Op]],
must_embed_fonts: bool,
) -> Cow<'a, BTreeMap<FontId, crate::font::PdfFont>> {
#[cfg(feature = "include_base_fonts")]
if must_embed_fonts {
let missing: Vec<(FontId, BuiltinFont)> = used_builtin_fonts(streams)
.into_iter()
.map(|font| (FontId(font.get_pdf_id().to_string()), font))
.filter(|(id, _)| !fonts.contains_key(id))
.collect();
if !missing.is_empty() {
let mut fonts = fonts.clone();
for (id, font) in missing {
if let Some(bundled) = crate::font::bundled_font(font) {
fonts.insert(id, crate::font::PdfFont::new(bundled));
}
}
return Cow::Owned(fonts);
}
}
#[cfg(not(feature = "include_base_fonts"))]
let _ = (streams, must_embed_fonts);
Cow::Borrowed(fonts)
}
fn pattern_color_ops(
space_op: &str,
color_op: &str,
id: &crate::PatternId,
color: Option<&Color>,
warnings: &mut Vec<PdfWarnMsg>,
) -> Vec<LoOp> {
let mut operands: Vec<lopdf::Object> = Vec::new();
let space = match color {
None => "Pattern",
Some(color) => {
if color.is_out_of_range() {
warnings.push(PdfWarnMsg::error(
0,
0,
format!("PDF color {color:?} is out of range, must be normalized to 0.0 - 1.0"),
));
}
operands.extend(color.into_vec().into_iter().map(Real));
pattern::pattern_space(color).0
}
};
operands.push(Name(id.0.as_bytes().to_vec()));
vec![
LoOp::new(space_op, vec![Name(space.as_bytes().to_vec())]),
LoOp::new(color_op, operands),
]
}
fn extgstate_dict(resources: &PdfResources) -> LoDictionary {
let mut dict = LoDictionary::new();
for (k, v) in resources.extgstates.map.iter() {
dict.set(k.0.clone(), crate::graphics::extgstate_to_dict(v));
}
dict
}
fn shading_dict(resources: &PdfResources) -> LoDictionary {
let mut dict = LoDictionary::new();
for (k, v) in resources.shadings.map.iter() {
dict.set(k.0.clone(), v.to_dict());
}
dict
}
fn write_font_dict(
doc: &mut lopdf::Document,
subset_fonts: &BTreeMap<FontId, RuntimeSubsetInfo>,
builtin_fonts: BTreeSet<BuiltinFont>,
must_embed_fonts: bool,
warnings: &mut Vec<PdfWarnMsg>,
) -> LoDictionary {
let mut font_dict = LoDictionary::new();
for (font_id, subset_info) in subset_fonts.iter() {
let dict = add_subset_font_to_pdf(doc, font_id, subset_info);
let dict_id = doc.add_object(dict);
font_dict.set(font_id.0.clone(), Reference(dict_id));
}
for internal_font in builtin_fonts {
if font_dict.has(internal_font.get_pdf_id().as_bytes()) {
continue;
}
if must_embed_fonts {
warnings.push(PdfWarnMsg::warning(
0,
0,
format!(
"standard font {} is not embedded: printpdf has no font program for the 14 \
standard fonts, only their metrics, and the conformance standard requires \
every font to be embedded. Embed a font with \
PdfDocument::replace_builtin_font, turn on the feature include_base_fonts, \
or use a font of your own.",
internal_font.get_id()
),
));
}
let dict_id = doc.add_object(builtin_font_to_dict(&internal_font));
font_dict.set(internal_font.get_pdf_id(), Reference(dict_id));
}
font_dict
}
fn builtin_font_to_dict(font: &BuiltinFont) -> LoDictionary {
LoDictionary::from_iter(vec![
("Type", Name("Font".into())),
("Subtype", Name("Type1".into())),
("BaseFont", Name(font.get_id().into())),
("Encoding", Name("WinAnsiEncoding".into())),
])
}
struct PendingGlyphRun {
matrix: [f32; 6],
font_res: String,
font_size: f32,
pen: f64,
array: Vec<lopdf::Object>,
}
#[derive(Clone, Copy)]
enum RunFont<'a> {
Embedded(&'a RuntimeFontInfo),
Standard(BuiltinFont),
}
fn flush_glyph_run(run: &mut Option<PendingGlyphRun>, content: &mut Vec<LoOp>) {
if let Some(r) = run.take() {
content.push(LoOp::new("Tm", r.matrix.iter().copied().map(Real).collect()));
content.push(LoOp::new("TJ", vec![Array(r.array)]));
}
}
fn flush_pending_tm(tm: &mut Option<[f32; 6]>, content: &mut Vec<LoOp>) {
if let Some(m) = tm.take() {
content.push(LoOp::new("Tm", m.iter().copied().map(Real).collect()));
}
}
pub(crate) fn translate_operations(
ops: &[Op],
font_infos: &BTreeMap<FontId, RuntimeFontInfo>,
xobjects: &BTreeMap<XObjectId, XObject>,
secure: bool,
warnings: &mut Vec<PdfWarnMsg>,
) -> Vec<u8> {
let mut content = Vec::new();
let mut current_font_resource: Option<String> = None;
let mut current_builtin: Option<BuiltinFont> = None;
let mut current_font_size: f32 = 0.0;
let mut current_char_spacing: f32 = 0.0;
let mut current_horiz_scaling: f32 = 100.0;
let mut pending_tm: Option<[f32; 6]> = None;
let mut glyph_run: Option<PendingGlyphRun> = None;
let mut in_text_section = false;
let mut warned_outside_text_section = false;
let warn_outside = |op_idx: usize,
op_name: &str,
warned: &mut bool,
warnings: &mut Vec<PdfWarnMsg>| {
if !*warned {
warnings.push(PdfWarnMsg::error(
0,
op_idx,
format!(
"{op_name} outside of a text section: most PDF viewers will not \
display this text. Wrap text operations in \
Op::StartTextSection .. Op::EndTextSection (reported once per \
content stream)"
),
));
*warned = true;
}
};
for (op_idx, op) in ops.iter().enumerate() {
let consumed = 'merge: {
match op {
Op::SetTextMatrix { matrix } if in_text_section => {
let m = matrix.as_array();
if !(m[0] == 1.0 && m[1] == 0.0 && m[2] == 0.0 && m[3] == 1.0) {
break 'merge false;
}
flush_pending_tm(&mut pending_tm, &mut content);
pending_tm = Some(m);
true
}
Op::ShowText { items }
if in_text_section && (pending_tm.is_some() || glyph_run.is_some()) =>
{
let run_font = match resolve_current_font(¤t_font_resource, font_infos) {
(_, Some(fi)) => RunFont::Embedded(fi),
(Some(builtin), None) => RunFont::Standard(builtin),
(None, None) => break 'merge false,
};
let fs = current_font_size;
let glyphs_only = !items.is_empty()
&& items
.iter()
.all(|i| matches!(i, TextItem::GlyphIds(_) | TextItem::Offset(_)));
if !glyphs_only
|| fs <= 0.0
|| current_char_spacing != 0.0
|| current_horiz_scaling != 100.0
{
break 'merge false;
}
let font_res = current_font_resource.clone().unwrap_or_default();
match pending_tm.take() {
Some(m) => {
let extending = glyph_run.as_mut().filter(|r| {
r.matrix[5] == m[5]
&& r.font_res == font_res
&& r.font_size == fs
});
if let Some(r) = extending {
let dx_em = (m[4] as f64 - r.matrix[4] as f64) * 1000.0
/ fs as f64;
let kern = (r.pen - dx_em).round();
if kern != 0.0 {
r.array.push(Integer(kern as i64));
r.pen -= kern;
}
} else {
flush_glyph_run(&mut glyph_run, &mut content);
glyph_run = Some(PendingGlyphRun {
matrix: m,
font_res,
font_size: fs,
pen: 0.0,
array: Vec::new(),
});
}
}
None => {
let compatible = glyph_run
.as_ref()
.is_some_and(|r| r.font_res == font_res && r.font_size == fs);
if !compatible {
break 'merge false;
}
}
}
let Some(r) = glyph_run.as_mut() else {
break 'merge false;
};
for item in items {
match item {
TextItem::Offset(o) => {
r.array.push(Real(*o));
r.pen -= *o as f64;
}
TextItem::GlyphIds(glyphs) => {
for cp in glyphs {
let (code, width) = match run_font {
RunFont::Embedded(fi) => {
let gid = glyph_in_font(cp.gid, current_builtin, fi);
(
remap_gid(Some(fi), gid).to_be_bytes().to_vec(),
get_scaled_glyph_width(&fi.parsed_font, gid),
)
}
RunFont::Standard(builtin) => {
let code = builtin.code_of_glyph(cp.gid);
(
vec![code],
i64::from(builtin.code_width(code).unwrap_or(0)),
)
}
};
match r.array.last_mut() {
Some(LoString(bytes, Hexadecimal)) => bytes.extend_from_slice(&code),
_ => r.array.push(LoString(code, Hexadecimal)),
}
r.pen += width as f64;
if cp.offset != 0.0 {
r.array.push(Real(cp.offset));
r.pen -= cp.offset as f64;
}
}
}
TextItem::Text(_) => {}
}
}
true
}
_ => false,
}
};
if !consumed {
flush_glyph_run(&mut glyph_run, &mut content);
flush_pending_tm(&mut pending_tm, &mut content);
} else {
continue;
}
match op {
Op::SetRenderingIntent { intent } => {
content.push(LoOp::new("ri", vec![Name(intent.get_id().into())]));
}
Op::SetColorSpaceFill { id } => {
content.push(LoOp::new("cs", vec![Name(id.clone().into())]));
}
Op::SetColorSpaceStroke { id } => {
content.push(LoOp::new("CS", vec![Name(id.clone().into())]));
}
Op::SetHorizontalScaling { percent } => {
current_horiz_scaling = *percent;
content.push(LoOp::new("Tz", vec![Real(*percent)]));
}
Op::AddLineBreak => {
content.push(LoOp::new("T*", vec![]));
}
Op::Marker { id } => {
content.push(LoOp::new("MP", vec![Name(id.clone().into())]));
}
Op::BeginLayer { layer_id } => {
content.push(LoOp::new(
"BDC",
vec![Name("OC".into()), Name(layer_id.0.clone().into())],
));
}
Op::EndLayer => {
content.push(LoOp::new("EMC", vec![]));
}
Op::SaveGraphicsState => {
content.push(LoOp::new("q", vec![]));
}
Op::RestoreGraphicsState => {
content.push(LoOp::new("Q", vec![]));
}
Op::LoadGraphicsState { gs } => {
content.push(LoOp::new("gs", vec![Name(gs.0.as_bytes().to_vec())]));
}
Op::SetFillPattern { id, color } => {
content.append(&mut pattern_color_ops("cs", "scn", id, color.as_ref(), warnings));
}
Op::SetOutlinePattern { id, color } => {
content.append(&mut pattern_color_ops("CS", "SCN", id, color.as_ref(), warnings));
}
Op::PaintShading { id } => {
content.push(LoOp::new("sh", vec![Name(id.0.as_bytes().to_vec())]));
}
Op::StartTextSection => {
in_text_section = true;
content.push(LoOp::new("BT", vec![]));
}
Op::EndTextSection => {
in_text_section = false;
content.push(LoOp::new("ET", vec![]));
}
Op::SetFont { font, size } => {
let font_resource_name = font.get_resource_name();
current_font_resource = Some(font_resource_name.clone());
current_builtin = match font {
crate::ops::PdfFontHandle::Builtin(builtin) => Some(*builtin),
crate::ops::PdfFontHandle::External(_) => None,
};
current_font_size = size.0;
content.push(LoOp::new(
"Tf",
vec![lopdf::Object::Name(font_resource_name.as_bytes().to_vec()), size.0.into()],
));
}
Op::ShowText { items } => {
if !in_text_section {
warn_outside(op_idx, "Op::ShowText", &mut warned_outside_text_section, warnings);
}
let (builtin_font, font_info) =
resolve_current_font(¤t_font_resource, font_infos);
encode_text_items_to_pdf(
items,
font_info,
builtin_font.as_ref(),
current_builtin,
&mut content,
);
}
Op::SetLineHeight { lh } => {
content.push(LoOp::new("TL", vec![Real(lh.0)]));
}
Op::SetWordSpacing { pt } => {
content.push(LoOp::new("Tw", vec![Real(pt.0)]));
}
Op::SetTextCursor { pos } => {
content.push(LoOp::new("Td", vec![pos.x.0.into(), pos.y.0.into()]));
}
Op::SetFillColor { col } => {
let ci = match &col {
Color::Rgb(_) => "rg",
Color::Cmyk(_) | Color::SpotColor(_) => "k",
Color::Greyscale(_) => "g",
};
if col.is_out_of_range() {
warnings.push(PdfWarnMsg::error(
0,
0,
format!(
"PDF color {col:?} is out of range, must be normalized to 0.0 - 1.0"
),
));
}
let cvec = col.into_vec().into_iter().map(Real).collect();
content.push(LoOp::new(ci, cvec));
}
Op::SetOutlineColor { col } => {
let ci = match &col {
Color::Rgb(_) => "RG",
Color::Cmyk(_) | Color::SpotColor(_) => "K",
Color::Greyscale(_) => "G",
};
if col.is_out_of_range() {
warnings.push(PdfWarnMsg::error(
0,
0,
format!(
"PDF color {col:?} is out of range, must be normalized to 0.0 - 1.0"
),
));
}
let cvec = col.into_vec().into_iter().map(Real).collect();
content.push(LoOp::new(ci, cvec));
}
Op::SetOutlineThickness { pt } => {
content.push(LoOp::new("w", vec![Real(pt.0)]));
}
Op::SetLineDashPattern { dash } => {
let dash_array_floats = dash.pattern.iter().copied().map(Real).collect();
content.push(LoOp::new(
"d",
vec![Array(dash_array_floats), Real(dash.offset)],
));
}
Op::SetLineJoinStyle { join } => {
content.push(LoOp::new("j", vec![Integer(join.id())]));
}
Op::SetMiterLimit { limit } => {
content.push(LoOp::new("M", vec![Real(limit.0)]));
}
Op::SetLineCapStyle { cap } => {
content.push(LoOp::new("J", vec![Integer(cap.id())]));
}
Op::SetTextRenderingMode { mode } => {
content.push(LoOp::new("Tr", vec![Integer(mode.id())]));
}
Op::SetCharacterSpacing { multiplier } => {
current_char_spacing = *multiplier;
content.push(LoOp::new("Tc", vec![Real(*multiplier)]));
}
Op::SetLineOffset { multiplier } => {
content.push(LoOp::new("Ts", vec![Real(*multiplier)]));
}
Op::DrawLine { line } => {
content.append(&mut line_to_stream_ops(line));
}
Op::DrawPolygon { polygon } => {
content.append(&mut polygon_to_stream_ops(polygon));
}
Op::DrawRectangle { rectangle } => {
content.append(&mut rectangle_to_stream_ops(rectangle));
}
Op::SetTransformationMatrix { matrix } => {
content.push(LoOp::new(
"cm",
matrix.as_array().iter().copied().map(Real).collect(),
));
}
Op::SetTextMatrix { matrix } => {
content.push(LoOp::new(
"Tm",
matrix.as_array().iter().copied().map(Real).collect(),
));
}
Op::LinkAnnotation { link: _ } => {}
Op::UseXobject { id, transform } => {
use crate::matrix::CurTransMat;
let mut t = CurTransMat::Identity;
let wh = if transform.no_auto_scale {
None
} else {
xobjects.get(id).and_then(|xobj| xobj.get_width_height())
};
for q in transform.get_ctms(wh) {
t = CurTransMat::Raw(CurTransMat::combine_matrix(t.as_array(), q.as_array()));
}
content.push(LoOp::new("q", vec![]));
content.push(LoOp::new(
"cm",
t.as_array().into_iter().map(Real).collect(),
));
content.push(LoOp::new("Do", vec![Name(id.0.as_bytes().to_vec())]));
content.push(LoOp::new("Q", vec![]));
}
Op::BeginInlineImage => {
content.push(LoOp::new("BI", vec![]));
}
Op::BeginInlineImageData => {
content.push(LoOp::new("ID", vec![]));
}
Op::EndInlineImage => {
content.push(LoOp::new("EI", vec![]));
}
Op::BeginMarkedContent { tag } => {
content.push(LoOp::new("BMC", vec![Name(tag.clone().into())]));
}
Op::BeginMarkedContentWithProperties { tag, properties } => {
content.push(LoOp::new(
"BDC",
vec![Name(tag.clone().into()), properties.to_lopdf()]
));
}
Op::BeginOptionalContent { layer_id } => {
content.push(LoOp::new(
"BDC",
vec![Name("OC".into()), Name(layer_id.0.clone().into())],
));
}
Op::DefineMarkedContentPoint { tag, properties } => {
let props = Array(properties.iter().map(|item| item.to_lopdf()).collect());
content.push(LoOp::new("DP", vec![Name(tag.clone().into()), props]));
}
Op::EndMarkedContent | Op::EndMarkedContentWithProperties | Op::EndOptionalContent => {
content.push(LoOp::new("EMC", vec![]));
}
Op::BeginCompatibilitySection => {
content.push(LoOp::new("BX", vec![]));
}
Op::EndCompatibilitySection => {
content.push(LoOp::new("EX", vec![]));
}
Op::MoveToNextLineShowText { text } => {
if !in_text_section {
warn_outside(
op_idx,
"Op::MoveToNextLineShowText",
&mut warned_outside_text_section,
warnings,
);
}
let (builtin_font, font_info) =
resolve_current_font(¤t_font_resource, font_infos);
content.push(LoOp::new(
"'",
vec![encode_text_for_font(text, font_info, builtin_font.as_ref())],
));
}
Op::SetSpacingMoveAndShowText {
word_spacing,
char_spacing,
text,
} => {
if !in_text_section {
warn_outside(
op_idx,
"Op::SetSpacingMoveAndShowText",
&mut warned_outside_text_section,
warnings,
);
}
let (builtin_font, font_info) =
resolve_current_font(¤t_font_resource, font_infos);
current_char_spacing = *char_spacing;
content.push(LoOp::new(
"\"",
vec![
Real(*word_spacing),
Real(*char_spacing),
encode_text_for_font(text, font_info, builtin_font.as_ref()),
],
));
}
Op::MoveTextCursorAndSetLeading { tx, ty } => {
content.push(LoOp::new("TD", vec![Real(*tx), Real(*ty)]));
}
Op::Unknown { key, value } => {
if !secure {
content.push(LoOp::new(
key.as_str(),
value.iter().map(|s| s.to_lopdf()).collect(),
));
}
}
}
}
flush_glyph_run(&mut glyph_run, &mut content);
flush_pending_tm(&mut pending_tm, &mut content);
lopdf::content::Content {
operations: content,
}
.encode()
.unwrap_or_default()
}
fn resolve_current_font<'a>(
current_font_resource: &Option<String>,
font_infos: &'a BTreeMap<FontId, RuntimeFontInfo>,
) -> (Option<BuiltinFont>, Option<&'a RuntimeFontInfo>) {
let info = current_font_resource
.as_ref()
.and_then(|r| font_infos.get(&FontId(r.clone())));
let builtin = if info.is_none() {
current_font_resource
.as_ref()
.and_then(|r| BuiltinFont::from_id(r))
} else {
None
};
(builtin, info)
}
fn glyph_in_font(gid: u16, builtin: Option<BuiltinFont>, font_info: &RuntimeFontInfo) -> u16 {
replacement_glyph(gid, builtin, &font_info.parsed_font)
}
fn replacement_glyph(gid: u16, builtin: Option<BuiltinFont>, font: &ParsedFont) -> u16 {
match builtin {
Some(builtin) => font
.lookup_glyph_index(u32::from(builtin.char_of_glyph(gid)))
.unwrap_or(0),
None => gid,
}
}
fn remap_gid(font_info: Option<&RuntimeFontInfo>, gid: u16) -> u16 {
match font_info.and_then(|fi| fi.gid_remap.as_ref()) {
Some(map) => map.get(&gid).copied().unwrap_or(0),
None => gid,
}
}
fn encode_text_items_to_pdf(
items: &[TextItem],
font_info: Option<&RuntimeFontInfo>,
builtin_font: Option<&BuiltinFont>,
selected_builtin: Option<BuiltinFont>,
content: &mut Vec<LoOp>,
) {
if items.is_empty() {
return;
}
let mut tj_array = Vec::new();
for item in items {
match item {
TextItem::Text(text) => {
tj_array.push(encode_text_for_font(text, font_info, builtin_font));
}
TextItem::Offset(offset) => {
tj_array.push(Real(*offset));
}
TextItem::GlyphIds(glyphs) => {
for codepoint in glyphs {
let bytes = match (font_info, builtin_font) {
(Some(fi), _) => {
let gid = glyph_in_font(codepoint.gid, selected_builtin, fi);
remap_gid(Some(fi), gid).to_be_bytes().to_vec()
}
(None, Some(builtin)) => vec![builtin.code_of_glyph(codepoint.gid)],
(None, None) => codepoint.gid.to_be_bytes().to_vec(),
};
tj_array.push(LoString(bytes, Hexadecimal));
if codepoint.offset != 0.0 {
tj_array.push(Real(codepoint.offset));
}
}
}
}
}
if tj_array.len() == 1 && !items.iter().any(|i| matches!(i, TextItem::Offset(_) | TextItem::GlyphIds(_))) {
content.push(LoOp::new("Tj", vec![tj_array.swap_remove(0)]));
} else {
content.push(LoOp::new("TJ", vec![Array(tj_array)]));
}
}
fn needs_hex_encoding(bytes: &[u8]) -> bool {
bytes.iter().any(|&b| {
!(32..=126).contains(&b) || b == b'(' || b == b')' || b == b'\\' || b == b'%'
})
}
fn encode_win_ansi(text: &str) -> Vec<u8> {
text.chars()
.map(|c| win_ansi_byte(c).unwrap_or(b'?'))
.collect()
}
fn win_ansi_byte(c: char) -> Option<u8> {
match c as u32 {
cp @ 0x20..=0x7E => return Some(cp as u8),
cp @ 0xA0..=0xFF => return Some(cp as u8),
_ => {}
}
Some(match c {
'\u{20AC}' => 0x80, '\u{201A}' => 0x82, '\u{0192}' => 0x83, '\u{201E}' => 0x84, '\u{2026}' => 0x85, '\u{2020}' => 0x86, '\u{2021}' => 0x87, '\u{02C6}' => 0x88, '\u{2030}' => 0x89, '\u{0160}' => 0x8A, '\u{2039}' => 0x8B, '\u{0152}' => 0x8C, '\u{017D}' => 0x8E, '\u{2018}' => 0x91, '\u{2019}' => 0x92, '\u{201C}' => 0x93, '\u{201D}' => 0x94, '\u{2022}' => 0x95, '\u{2013}' => 0x96, '\u{2014}' => 0x97, '\u{02DC}' => 0x98, '\u{2122}' => 0x99, '\u{0161}' => 0x9A, '\u{203A}' => 0x9B, '\u{0153}' => 0x9C, '\u{017E}' => 0x9E, '\u{0178}' => 0x9F, _ => return None,
})
}
fn encode_text_for_font(
text: &str,
font_info: Option<&RuntimeFontInfo>,
builtin_font: Option<&BuiltinFont>,
) -> lopdf::Object {
if let Some(font_info) = font_info {
let bytes: Vec<u8> = text
.chars()
.flat_map(|c| {
let orig = font_info.parsed_font.lookup_glyph_index(c as u32).unwrap_or(0);
remap_gid(Some(font_info), orig).to_be_bytes()
})
.collect();
return LoString(bytes, Hexadecimal);
}
let _ = builtin_font;
let bytes = encode_win_ansi(text);
let format = if needs_hex_encoding(&bytes) {
Hexadecimal
} else {
Literal
};
LoString(bytes, format)
}
#[derive(Debug, Clone)]
pub(crate) struct RuntimeFontInfo {
pub parsed_font: ParsedFont,
pub gid_remap: Option<BTreeMap<u16, u16>>,
}
#[derive(Debug, Clone)]
pub(crate) struct RuntimeSubsetInfo {
pub original_font: ParsedFont,
pub subset_font_bytes: Vec<u8>,
pub cid_to_unicode_map: String,
pub widths_list: Vec<lopdf::Object>,
pub ascent: i64,
pub descent: i64,
pub gid_remap: BTreeMap<u16, u16>,
pub was_subset: bool,
}
fn collect_used_glyphs(
streams: &[&[Op]],
fonts: &BTreeMap<FontId, crate::font::PdfFont>,
) -> BTreeMap<FontId, BTreeMap<u16, String>> {
let mut used_glyphs: BTreeMap<FontId, BTreeMap<u16, String>> = BTreeMap::new();
for ops in streams {
let mut current_font_id: Option<FontId> = None;
let mut current_builtin: Option<BuiltinFont> = None;
for op in ops.iter() {
match op {
Op::SetFont { font, .. } => {
match font {
crate::ops::PdfFontHandle::External(font_id) => {
current_font_id = Some(font_id.clone());
current_builtin = None;
}
crate::ops::PdfFontHandle::Builtin(builtin) => {
current_font_id = Some(FontId(builtin.get_pdf_id().to_string()));
current_builtin = Some(*builtin);
}
}
}
Op::ShowText { items } => {
if let Some(ref font_id) = current_font_id {
if let Some(pdf_font) = fonts.get(font_id) {
let font_glyphs = used_glyphs.entry(font_id.clone()).or_default();
for item in items {
match item {
TextItem::Text(text) => {
for c in text.chars() {
if let Some(glyph_id) = pdf_font.parsed_font.lookup_glyph_index(c as u32) {
font_glyphs.insert(glyph_id, c.to_string());
}
}
}
TextItem::GlyphIds(glyphs) => {
for codepoint in glyphs {
let gid = replacement_glyph(
codepoint.gid,
current_builtin,
&pdf_font.parsed_font,
);
let character = if let Some(ref cid) = codepoint.cid {
cid.clone()
} else {
pdf_font.parsed_font.get_glyph_primary_char(gid)
.map(|c| c.to_string())
.unwrap_or_else(|| "\u{FFFD}".to_string())
};
if !character.is_empty() || !font_glyphs.contains_key(&gid) {
font_glyphs.insert(gid, character);
}
}
}
TextItem::Offset(_) => {
}
}
}
}
}
}
Op::MoveToNextLineShowText { text }
| Op::SetSpacingMoveAndShowText { text, .. } => {
if let Some(ref font_id) = current_font_id {
if let Some(pdf_font) = fonts.get(font_id) {
let font_glyphs = used_glyphs
.entry(font_id.clone())
.or_default();
for c in text.chars() {
if let Some(glyph_id) =
pdf_font.parsed_font.lookup_glyph_index(c as u32)
{
font_glyphs.insert(glyph_id, c.to_string());
}
}
}
}
}
_ => {
}
}
}
}
used_glyphs
}
const DEFAULT_CHARACTER_WIDTH: i64 = 1000;
fn line_to_stream_ops(line: &Line) -> Vec<LoOp> {
pub const OP_PATH_CONST_MOVE_TO: &str = "m";
pub const OP_PATH_CONST_LINE_TO: &str = "l";
pub const OP_PATH_CONST_4BEZIER: &str = "c";
pub const OP_PATH_PAINT_STROKE: &str = "S";
pub const OP_PATH_CLOSE: &str = "h";
let mut operations = Vec::new();
let Some((first, mut rest)) = line.points.split_first() else {
return operations;
};
operations.push(LoOp::new(
OP_PATH_CONST_MOVE_TO,
vec![first.p.x.into(), first.p.y.into()],
));
while let Some((current, tail)) = rest.split_first() {
match tail {
[control2, end_point, after @ ..] if current.bezier && control2.bezier => {
operations.push(LoOp::new(
OP_PATH_CONST_4BEZIER,
vec![
current.p.x.into(),
current.p.y.into(),
control2.p.x.into(),
control2.p.y.into(),
end_point.p.x.into(),
end_point.p.y.into(),
],
));
rest = after;
}
_ => {
operations.push(LoOp::new(
OP_PATH_CONST_LINE_TO,
vec![current.p.x.into(), current.p.y.into()],
));
rest = tail;
}
}
}
if line.is_closed {
operations.push(LoOp::new(OP_PATH_CLOSE, vec![]));
operations.push(LoOp::new(OP_PATH_PAINT_STROKE, vec![]));
} else {
operations.push(LoOp::new(OP_PATH_PAINT_STROKE, vec![]));
}
operations
}
fn polygon_to_stream_ops(poly: &Polygon) -> Vec<LoOp> {
pub const OP_PATH_CONST_MOVE_TO: &str = "m";
pub const OP_PATH_CONST_LINE_TO: &str = "l";
pub const OP_PATH_CONST_4BEZIER: &str = "c";
pub const OP_PATH_PAINT_END: &str = "n";
let mut operations = Vec::new();
if poly.rings.is_empty() {
return operations;
}
for ring in &poly.rings {
let Some((first, mut rest)) = ring.points.split_first() else {
continue;
};
operations.push(LoOp::new(
OP_PATH_CONST_MOVE_TO,
vec![first.p.x.into(), first.p.y.into()],
));
while let Some((current, tail)) = rest.split_first() {
match tail {
[control2, end_point, after @ ..] if current.bezier && control2.bezier => {
operations.push(LoOp::new(
OP_PATH_CONST_4BEZIER,
vec![
current.p.x.into(),
current.p.y.into(),
control2.p.x.into(),
control2.p.y.into(),
end_point.p.x.into(),
end_point.p.y.into(),
],
));
rest = after;
}
_ => {
operations.push(LoOp::new(
OP_PATH_CONST_LINE_TO,
vec![current.p.x.into(), current.p.y.into()],
));
rest = tail;
}
}
}
}
operations.push(LoOp::new("h", vec![]));
match poly.mode {
PaintMode::Clip => {
operations.push(LoOp::new(poly.winding_order.get_clip_op(), vec![]));
operations.push(LoOp::new(OP_PATH_PAINT_END, vec![]));
}
PaintMode::Fill => {
operations.push(LoOp::new(poly.winding_order.get_fill_op(), vec![]));
}
PaintMode::Stroke => {
operations.push(LoOp::new("S", vec![]));
}
PaintMode::FillStroke => {
operations.push(LoOp::new(
poly.winding_order.get_fill_stroke_close_op(),
vec![],
));
}
}
operations
}
fn rectangle_to_stream_ops(rectangle: &crate::Rect) -> Vec<LoOp> {
use crate::graphics::{PaintMode, WindingOrder};
let mut operations = Vec::new();
operations.push(LoOp::new(
"re",
vec![
rectangle.x.into(),
rectangle.y.into(),
rectangle.width.into(),
rectangle.height.into()
],
));
let winding = rectangle.winding_order.unwrap_or(WindingOrder::NonZero);
match rectangle.mode {
Some(PaintMode::Clip) => {
operations.push(LoOp::new(winding.get_clip_op(), vec![]));
operations.push(LoOp::new("n", vec![]));
}
Some(PaintMode::Fill) => {
operations.push(LoOp::new(winding.get_fill_op(), vec![]));
}
Some(PaintMode::Stroke) => {
operations.push(LoOp::new("S", vec![]));
}
Some(PaintMode::FillStroke) => {
operations.push(LoOp::new(winding.get_fill_stroke_op(), vec![]));
}
None => {
match rectangle.winding_order {
Some(WindingOrder::NonZero) => operations.push(LoOp::new("W", vec![])),
Some(WindingOrder::EvenOdd) => operations.push(LoOp::new("W*", vec![])),
None => {}
}
operations.push(LoOp::new("n", vec![]));
}
}
operations
}
pub(crate) fn prepare_fonts_for_streams(
fonts: &BTreeMap<FontId, crate::font::PdfFont>,
streams: &[&[Op]],
_do_subset: bool,
warnings: &mut Vec<PdfWarnMsg>,
) -> (BTreeMap<FontId, RuntimeFontInfo>, BTreeMap<FontId, RuntimeSubsetInfo>) {
let mut font_infos = BTreeMap::new();
let mut subset_infos = BTreeMap::new();
let used_glyphs = collect_used_glyphs(streams, fonts);
for (font_id, pdf_font) in fonts {
let glyph_usage = used_glyphs.get(font_id).cloned().unwrap_or_default();
if glyph_usage.is_empty() {
continue; }
font_infos.insert(font_id.clone(), RuntimeFontInfo {
parsed_font: pdf_font.parsed_font.clone(),
gid_remap: None,
});
#[cfg(feature = "text_layout")]
let subset_info = if _do_subset &&
pdf_font.meta.requires_subsetting &&
pdf_font.meta.embedding_mode == crate::font::FontEmbeddingMode::Subset {
match create_subset_runtime_info(font_id, pdf_font, &glyph_usage, warnings) {
Some(info) => info,
None => create_full_font_runtime_info(font_id, pdf_font, &glyph_usage, warnings),
}
} else {
create_full_font_runtime_info(font_id, pdf_font, &glyph_usage, warnings)
};
#[cfg(not(feature = "text_layout"))]
let subset_info = create_full_font_runtime_info(font_id, pdf_font, &glyph_usage, warnings);
if !subset_info.gid_remap.is_empty() {
if let Some(fi) = font_infos.get_mut(font_id) {
fi.gid_remap = Some(subset_info.gid_remap.clone());
}
}
subset_infos.insert(font_id.clone(), subset_info);
}
(font_infos, subset_infos)
}
#[cfg(feature = "text_layout")]
fn create_subset_runtime_info(
font_id: &FontId,
pdf_font: &crate::font::PdfFont,
glyph_usage: &BTreeMap<u16, String>,
warnings: &mut Vec<PdfWarnMsg>,
) -> Option<RuntimeSubsetInfo> {
let subset_result = crate::font::subset_font(&pdf_font.parsed_font, glyph_usage);
match subset_result {
Ok(subset) => {
let mut font_warnings = Vec::new();
if let Some(subset_font) = ParsedFont::from_bytes(&subset.bytes, 0, &mut font_warnings) {
let subset_gid_to_code =
crate::font::cff_charset_gid_to_cid_map(&subset.bytes, 0);
let mut gid_remap: BTreeMap<u16, u16> = BTreeMap::new();
let mut coded_glyphs: Vec<(u16, u16, String)> = Vec::new();
for (orig_gid, (new_gid, ch)) in subset.glyph_mapping.iter() {
let code = subset_gid_to_code
.as_ref()
.and_then(|m| m.get(new_gid).copied())
.unwrap_or(*new_gid);
gid_remap.insert(*orig_gid, code);
coded_glyphs.push((code, *new_gid, ch.clone()));
}
coded_glyphs.sort_by_key(|a| a.0);
let coded_unicode: Vec<(u16, String)> = coded_glyphs
.iter()
.map(|(code, _, ch)| (*code, ch.clone()))
.collect();
let cid_to_unicode_map = crate::font::generate_cmap_string(
&subset_font,
font_id,
&coded_unicode
);
let width_entries: Vec<(u16, u16)> = coded_glyphs
.iter()
.map(|(code, new_gid, _)| (*code, *new_gid))
.collect();
let widths =
crate::font::get_normalized_widths_codes(&subset_font, &width_entries);
Some(RuntimeSubsetInfo {
original_font: pdf_font.parsed_font.clone(),
subset_font_bytes: subset.bytes,
cid_to_unicode_map,
widths_list: widths,
ascent: subset_font.font_metrics.ascent as i64,
descent: subset_font.font_metrics.descent as i64,
gid_remap,
was_subset: true,
})
} else {
warnings.push(PdfWarnMsg::error(0, 0,
format!("Failed to parse subset font for {}", font_id.0)));
None
}
}
Err(e) => {
warnings.push(PdfWarnMsg::error(0, 0,
format!("Failed to subset font {}: {}", font_id.0, e)));
None
}
}
}
fn create_full_font_runtime_info(
font_id: &FontId,
pdf_font: &crate::font::PdfFont,
glyph_usage: &BTreeMap<u16, String>,
warnings: &mut Vec<PdfWarnMsg>,
) -> RuntimeSubsetInfo {
#[cfg(feature = "text_layout")]
let font_bytes = pdf_font
.parsed_font
.source_bytes()
.map(|fb| fb.as_slice().to_vec())
.unwrap_or_default();
#[cfg(not(feature = "text_layout"))]
let font_bytes = pdf_font.parsed_font.original_bytes.clone();
if font_bytes.is_empty() {
warnings.push(PdfWarnMsg::error(
0,
0,
format!(
"font {} has no source bytes and will NOT be embedded; construct it with \
printpdf::ParsedFont::from_bytes so the sfnt bytes are retained",
font_id.0
),
));
}
#[cfg(feature = "text_layout")]
let font_index = pdf_font.parsed_font.original_index;
#[cfg(not(feature = "text_layout"))]
let font_index = pdf_font.parsed_font.font_index as usize;
let font_bytes = if font_bytes.get(..4) == Some(b"ttcf".as_slice()) {
match crate::font::extract_collection_face(&font_bytes, font_index) {
Some(face) => face,
None => {
warnings.push(PdfWarnMsg::error(
0,
0,
format!(
"font {}: cannot extract face {} from font collection; embedding \
the whole collection, which most PDF readers reject",
font_id.0, font_index
),
));
font_bytes
}
}
} else {
font_bytes
};
let gid_to_code = crate::font::cff_charset_gid_to_cid_map(&font_bytes, 0);
let coded_glyphs: Vec<(u16, u16, String)> = {
let mut v: Vec<(u16, u16, String)> = glyph_usage
.iter()
.map(|(gid, s)| {
let code = gid_to_code
.as_ref()
.and_then(|m| m.get(gid).copied())
.unwrap_or(*gid);
(code, *gid, s.clone())
})
.collect();
v.sort_by_key(|a| a.0);
v
};
let coded_unicode: Vec<(u16, String)> = coded_glyphs
.iter()
.map(|(code, _, s)| (*code, s.clone()))
.collect();
let cid_to_unicode_map = crate::font::generate_cmap_string(
&pdf_font.parsed_font,
font_id,
&coded_unicode
);
let width_entries: Vec<(u16, u16)> = coded_glyphs
.iter()
.map(|(code, gid, _)| (*code, *gid))
.collect();
let widths = get_normalized_widths(&pdf_font.parsed_font, &width_entries);
RuntimeSubsetInfo {
original_font: pdf_font.parsed_font.clone(),
subset_font_bytes: font_bytes,
cid_to_unicode_map,
widths_list: widths,
ascent: pdf_font.parsed_font.font_metrics.ascent as i64,
descent: pdf_font.parsed_font.font_metrics.descent as i64,
gid_remap: gid_to_code.unwrap_or_default(),
was_subset: false,
}
}
pub(crate) fn get_scaled_glyph_width(font: &crate::font::ParsedFont, gid: u16) -> i64 {
#[cfg(feature = "text_layout")]
return crate::text::glyph_pdf_width(font, gid);
#[cfg(not(feature = "text_layout"))]
{
let raw_width = font.get_glyph_width(gid);
let units_per_em = font.pdf_font_metrics.units_per_em as f32;
raw_width
.map(|w| (w as f32 * 1000.0 / units_per_em) as i64)
.unwrap_or(0)
}
}
fn get_normalized_widths(
font: &crate::font::ParsedFont,
entries: &[(u16, u16)],
) -> Vec<lopdf::Object> {
let mut widths_list = Vec::new();
let mut current_low_code = 0u16;
let mut current_high_code = 0u16;
let mut current_width_vec: Vec<i64> = Vec::new();
for &(code, gid) in entries {
let glyph_width = get_scaled_glyph_width(font, gid);
if current_width_vec.is_empty() {
current_low_code = code;
current_high_code = code;
current_width_vec.push(glyph_width);
} else if current_high_code.checked_add(1) == Some(code) {
current_high_code = code;
current_width_vec.push(glyph_width);
} else {
widths_list.push(lopdf::Object::Integer(current_low_code as i64));
widths_list.push(lopdf::Object::Array(
current_width_vec.iter().map(|w| lopdf::Object::Integer(*w)).collect(),
));
current_low_code = code;
current_high_code = code;
current_width_vec = vec![glyph_width];
}
}
if !current_width_vec.is_empty() {
widths_list.push(lopdf::Object::Integer(current_low_code as i64));
widths_list.push(lopdf::Object::Array(
current_width_vec.iter().map(|w| lopdf::Object::Integer(*w)).collect(),
));
}
widths_list
}
fn font_program_stream(
mut dictionary: LoDictionary,
program: Vec<u8>,
requires_length1: bool,
) -> LoStream {
if requires_length1 {
dictionary.set("Length1", Integer(program.len() as i64));
}
LoStream::new(dictionary, program).with_compression(true)
}
fn subset_tag(id: &str) -> String {
if let Some(head) = id.get(0..6).filter(|head| head.bytes().all(|b| b.is_ascii_uppercase())) {
return head.to_string();
}
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in id.bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
(0..6)
.map(|_| {
let letter = char::from(b'A' + (hash % 26) as u8);
hash /= 26;
letter
})
.collect()
}
fn add_subset_font_to_pdf(
doc: &mut lopdf::Document,
font_id: &FontId,
subset_info: &RuntimeSubsetInfo,
) -> LoDictionary {
let font_name = subset_info.original_font
.font_name
.clone()
.unwrap_or(font_id.0.clone());
let face_name = if subset_info.was_subset {
format!("{}+{}", subset_tag(&font_id.0), font_name)
} else {
font_name.clone()
};
let program = &subset_info.subset_font_bytes;
let has_font_program = !program.is_empty();
let bare_cid_keyed_cff = crate::font::extract_cid_keyed_cff(program, 0);
let is_otto = program.starts_with(b"OTTO");
let (sub_type, font_tuple) = if let Some(cff_table) = bare_cid_keyed_cff {
let font_tuple = has_font_program.then(|| {
let font_stream = font_program_stream(
LoDictionary::from_iter(vec![("Subtype", Name("CIDFontType0C".into()))]),
cff_table,
false,
);
("FontFile3", Reference(doc.add_object(font_stream)))
});
("CIDFontType0", font_tuple)
} else if is_otto {
let font_tuple = has_font_program.then(|| {
let font_stream = font_program_stream(
LoDictionary::from_iter(vec![("Subtype", Name("OpenType".into()))]),
program.clone(),
false,
);
("FontFile3", Reference(doc.add_object(font_stream)))
});
("CIDFontType0", font_tuple)
} else {
let font_tuple = has_font_program.then(|| {
let font_stream = font_program_stream(LoDictionary::new(), program.clone(), true);
("FontFile2", Reference(doc.add_object(font_stream)))
});
("CIDFontType2", font_tuple)
};
let upm = subset_info.original_font.pdf_font_metrics.units_per_em;
let font_scale = if upm == 0 { 1.0 } else { 1000.0 / upm as f32 };
let scale_i64 = |v: i64| (v as f32 * font_scale).round() as i64;
let scale_i16 = |v: i16| (v as f32 * font_scale).round() as i64;
let ascent_scaled = scale_i64(subset_info.ascent);
let descent_scaled = scale_i64(subset_info.descent);
let bbox_x_min = scale_i16(subset_info.original_font.pdf_font_metrics.x_min);
let bbox_y_min = scale_i16(subset_info.original_font.pdf_font_metrics.y_min);
let bbox_x_max = scale_i16(subset_info.original_font.pdf_font_metrics.x_max);
let bbox_y_max = scale_i16(subset_info.original_font.pdf_font_metrics.y_max);
#[cfg(feature = "text_layout")]
let cap_height = subset_info
.original_font
.font_metrics
.cap_height
.map(|c| (c * font_scale).round() as i64)
.unwrap_or(ascent_scaled);
#[cfg(not(feature = "text_layout"))]
let cap_height = ascent_scaled;
let m = &subset_info.original_font.pdf_font_metrics;
let italic_angle = if m.caret_slope_rise == 0 {
0
} else {
(-(m.caret_slope_run as f32).atan2(m.caret_slope_rise as f32).to_degrees()).round() as i64
};
const FLAG_NONSYMBOLIC: i64 = 1 << 5; const FLAG_ITALIC: i64 = 1 << 6;
let flags = FLAG_NONSYMBOLIC | if italic_angle != 0 { FLAG_ITALIC } else { 0 };
let stem_v = if m.us_weight_class == 0 {
80
} else {
50 + ((m.us_weight_class as f32 / 65.0).powi(2)).round() as i64
};
LoDictionary::from_iter(vec![
("Type", Name("Font".into())),
("Subtype", Name("Type0".into())),
("BaseFont", Name(face_name.clone().into_bytes())),
("Encoding", Name("Identity-H".into())),
(
"ToUnicode",
Reference(doc.add_object(LoStream::new(
LoDictionary::new(),
subset_info.cid_to_unicode_map.as_bytes().to_vec(),
))),
),
(
"DescendantFonts",
Array(vec![Dictionary(LoDictionary::from_iter(
vec![
("Type", Name("Font".into())),
("BaseFont", Name(face_name.clone().into_bytes())),
("Subtype", Name(sub_type.into())),
(
"CIDSystemInfo",
Dictionary(LoDictionary::from_iter(vec![
("Registry", LoString("Adobe".into(), Literal)),
("Ordering", LoString("Identity".into(), Literal)),
("Supplement", Integer(0)),
])),
),
("W", Array(subset_info.widths_list.clone())),
("DW", Integer(DEFAULT_CHARACTER_WIDTH)),
(
"FontDescriptor",
Reference(doc.add_object(LoDictionary::from_iter(
[
("Type", Name("FontDescriptor".into())),
("FontName", Name(face_name.clone().into_bytes())),
("Ascent", Integer(ascent_scaled)),
("Descent", Integer(descent_scaled)),
("CapHeight", Integer(cap_height)),
("ItalicAngle", Integer(italic_angle)),
("Flags", Integer(flags)),
("StemV", Integer(stem_v)),
(
"FontBBox",
Array(vec![
Integer(bbox_x_min),
Integer(bbox_y_min),
Integer(bbox_x_max),
Integer(bbox_y_max),
]),
),
]
.into_iter()
.chain(font_tuple),
))),
),
]
.into_iter()
.chain(
(sub_type == "CIDFontType2")
.then(|| ("CIDToGIDMap", Name("Identity".into()))),
),
))]),
),
])
}
fn docinfo_to_dict(m: &PdfDocumentInfo) -> LoDictionary {
let trapping = if m.trapped { "True" } else { "False" };
let gts_pdfx_version = m.conformance.get_identifier_string();
let info_mod_date = crate::utils::to_pdf_time_stamp_metadata(&m.modification_date);
let info_create_date = crate::utils::to_pdf_time_stamp_metadata(&m.creation_date);
let creation_date = LoString(info_create_date.into_bytes(), Literal);
let identifier = LoString(m.identifier.as_bytes().to_vec(), Literal);
let mut dict = LoDictionary::from_iter(vec![
("Trapped", trapping.into()),
("CreationDate", creation_date),
("ModDate", LoString(info_mod_date.into_bytes(), Literal)),
("Title", encode_text_to_utf16be(&m.document_title)),
("Author", encode_text_to_utf16be(&m.author)),
("Creator", encode_text_to_utf16be(&m.creator)),
("Producer", encode_text_to_utf16be(&m.producer)),
("Subject", encode_text_to_utf16be(&m.subject)),
("Identifier", identifier),
("Keywords", encode_text_to_utf16be(&m.keywords.join(","))),
]);
if !m.conformance.is_pdfa() {
dict.set("GTS_PDFXVersion", LoString(gts_pdfx_version.into(), Literal));
}
dict
}
fn icc_to_stream(val: &IccProfile) -> LoStream {
use lopdf::{Dictionary as LoDictionary, Object::*, Stream as LoStream};
let (num_icc_fields, alternate) = match val.icc_type {
IccProfileType::Cmyk => (4, "DeviceCMYK"),
IccProfileType::Rgb => (3, "DeviceRGB"),
IccProfileType::Greyscale => (1, "DeviceGray"),
};
let mut stream_dict = LoDictionary::from_iter(vec![
("N", Integer(num_icc_fields)),
("Length", Integer(val.icc.len() as i64)),
]);
if val.has_alternate {
stream_dict.set("Alternate", Name(alternate.into()));
}
if val.has_range {
stream_dict.set(
"Range",
Array(vec![
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0),
Real(0.0),
Real(1.0),
]),
);
}
LoStream::new(stream_dict, val.icc.clone())
}
fn link_annotation_to_dict(la: &LinkAnnotation, page_ids: &[lopdf::ObjectId]) -> LoDictionary {
let ll = la.rect.lower_left();
let ur = la.rect.upper_right();
let mut dict: LoDictionary = LoDictionary::new();
dict.set("Type", Name("Annot".into()));
dict.set("Subtype", Name("Link".into()));
dict.set(
"Rect",
Array(vec![Real(ll.x.0), Real(ll.y.0), Real(ur.x.0), Real(ur.y.0)]),
);
dict.set("A", Dictionary(actions_to_dict(&la.actions, page_ids)));
dict.set(
"Border",
Array(la.border.to_array().into_iter().map(Real).collect()),
);
dict.set(
"C",
Array(
color_array_to_f32(&la.color)
.into_iter()
.map(Real)
.collect(),
),
);
dict.set("H", Name(la.highlighting.get_id().into()));
dict
}
fn actions_to_dict(a: &Actions, page_ids: &[lopdf::ObjectId]) -> LoDictionary {
let mut dict = LoDictionary::new();
dict.set("S", Name(a.get_action_type_id().into()));
match a {
Actions::Goto(destination) => {
dict.set("D", destination_to_obj(destination, page_ids));
}
Actions::Uri(uri) => {
dict.set("URI", LoString(uri.clone().into_bytes(), Literal));
}
}
dict
}
fn destination_to_obj(d: &Destination, page_ids: &[lopdf::ObjectId]) -> lopdf::Object {
match d {
Destination::Xyz {
page,
left,
top,
zoom,
} => Array(vec![
page_ids
.get(page.saturating_sub(1))
.copied()
.map(Reference)
.unwrap_or(Null),
Name("XYZ".into()),
left.map(Real).unwrap_or(Null),
top.map(Real).unwrap_or(Null),
zoom.map(Real).unwrap_or(Null),
]),
}
}
fn color_array_to_f32(c: &ColorArray) -> Vec<f32> {
match c {
ColorArray::Transparent => Vec::new(),
ColorArray::Gray(arr) => arr.to_vec(),
ColorArray::Rgb(arr) => arr.to_vec(),
ColorArray::Cmyk(arr) => arr.to_vec(),
}
}
fn encode_text_to_utf16be(text: &str) -> lopdf::Object {
if text.is_empty() {
return lopdf::Object::string_literal("");
}
let mut bytes = vec![0xFE, 0xFF];
for c in text.encode_utf16() {
bytes.push((c >> 8) as u8);
bytes.push((c & 0xFF) as u8);
}
lopdf::Object::String(bytes, Hexadecimal)
}
#[cfg(test)]
mod tests {
use super::*;
use crate::graphics::{PaintMode, WindingOrder};
use crate::units::Pt;
#[test]
fn subset_tags_are_six_uppercase_letters() {
let random = FontId::new();
assert_eq!(super::subset_tag(&random.0), random.0[..6]);
for id in ["F5", "F13", "F12345678901234567890", "", "abcdefgh"] {
let tag = super::subset_tag(id);
assert_eq!(tag.len(), 6, "{id}");
assert!(tag.bytes().all(|b| b.is_ascii_uppercase()), "{id}: {tag}");
assert_eq!(tag, super::subset_tag(id), "{id}");
}
assert_ne!(super::subset_tag("F5"), super::subset_tag("F6"));
}
fn rect_with(mode: Option<PaintMode>, winding: Option<WindingOrder>) -> crate::Rect {
crate::Rect {
x: Pt(0.0),
y: Pt(0.0),
width: Pt(10.0),
height: Pt(10.0),
mode,
winding_order: winding,
}
}
fn operators(ops: &[LoOp]) -> Vec<String> {
ops.iter().map(|o| o.operator.clone()).collect()
}
#[test]
fn rectangle_honors_paint_mode() {
let ops = rectangle_to_stream_ops(&rect_with(Some(PaintMode::Fill), None));
assert_eq!(operators(&ops), vec!["re", "f"]);
let ops = rectangle_to_stream_ops(&rect_with(Some(PaintMode::Stroke), None));
assert_eq!(operators(&ops), vec!["re", "S"]);
let ops = rectangle_to_stream_ops(&rect_with(Some(PaintMode::FillStroke), None));
assert_eq!(operators(&ops), vec!["re", "B"]);
let ops = rectangle_to_stream_ops(&rect_with(Some(PaintMode::Fill), Some(WindingOrder::EvenOdd)));
assert_eq!(operators(&ops), vec!["re", "f*"]);
let ops = rectangle_to_stream_ops(&rect_with(Some(PaintMode::Clip), None));
assert_eq!(operators(&ops), vec!["re", "W", "n"]);
let ops = rectangle_to_stream_ops(&rect_with(None, None));
assert_eq!(operators(&ops), vec!["re", "n"]);
}
}
#[cfg(test)]
mod win_ansi_tests {
use super::encode_win_ansi as encode;
#[test]
fn ascii_is_unchanged() {
assert_eq!(encode("Hello, World!"), b"Hello, World!".to_vec());
}
#[test]
fn win_ansi_char_is_the_inverse_of_win_ansi_byte() {
for code in 0u8..=255 {
let c = crate::text::win_ansi_char(code);
if c != '\u{FFFD}' && !c.is_control() {
assert_eq!(super::win_ansi_byte(c), Some(code), "code {code:#04x}");
}
}
for code in [0x7F, 0x81, 0x8D, 0x8F, 0x90, 0x9D, 0x00, 0x1F] {
assert_eq!(crate::text::win_ansi_char(code), '\u{FFFD}');
}
}
#[test]
fn accented_names_become_single_winansi_bytes() {
assert_eq!(encode("é"), vec![0xE9]);
assert_eq!(encode("ü"), vec![0xFC]);
assert_eq!(encode("ñ"), vec![0xF1]);
assert_eq!(encode("ç"), vec![0xE7]);
assert_eq!(encode("José"), vec![b'J', b'o', b's', 0xE9]);
assert_eq!(encode("Grüße"), vec![b'G', b'r', 0xFC, 0xDF, b'e']);
}
#[test]
fn typographic_punctuation_becomes_single_winansi_bytes() {
assert_eq!(encode("“"), vec![0x93]); assert_eq!(encode("”"), vec![0x94]); assert_eq!(encode("’"), vec![0x92]); assert_eq!(encode("–"), vec![0x96]); assert_eq!(encode("—"), vec![0x97]); assert_eq!(encode("…"), vec![0x85]); assert_eq!(encode("•"), vec![0x95]); assert_eq!(encode("€"), vec![0x80]); assert_eq!(encode("™"), vec![0x99]); assert_eq!(encode("×"), vec![0xD7]); assert_eq!(encode("·"), vec![0xB7]); }
#[test]
fn does_not_emit_utf8_for_non_ascii() {
assert_ne!(encode("é"), vec![0xC3, 0xA9]);
assert_ne!(encode("–"), vec![0xE2, 0x80, 0x93]);
}
#[test]
fn unrepresentable_characters_do_not_corrupt_the_stream() {
assert_eq!(encode("世"), vec![b'?']);
assert_eq!(encode("a世b"), vec![b'a', b'?', b'b']);
}
#[test]
fn every_encoded_character_is_exactly_one_byte() {
for text in ["Hello", "José", "Grüße", "€ — …", "世界"] {
assert_eq!(
encode(text).len(),
text.chars().count(),
"WinAnsi is a single-byte encoding; {text:?} must not change length"
);
}
}
}