Skip to main content

Crate pdfrum_edit

Crate pdfrum_edit 

Source
Expand description

§pdfrum-edit

The crate that writes (ISO 32000-1 §7.5.8). A save either rewrites the whole file or appends a new body, cross-reference section and trailer to the bytes already there. Page import and reordering, N-up imposition, font subsetting, image embedding and re-encryption live here.

use std::sync::Arc;
use pdfrum_edit::{EditDoc, SaveOptions, save};
use pdfrum_parser::{LoadOptions, load};

let bytes = std::fs::read(concat!(env!("CARGO_MANIFEST_DIR"), "/tests/files/hello.pdf"))?;
let doc = load(Arc::from(bytes), &LoadOptions::default())?;
let mut out = Vec::new();
save(&EditDoc::new(&doc), &SaveOptions::default(), &mut out)?;
assert!(out.starts_with(b"%PDF"));

An untouched page is copied as stored; a touched one is regenerated, and regeneration is lossy. This is the single fact to know before editing. The content of a page you did not modify is written back byte for byte, so a save is not a re-encode of the document. A page whose graph you did change has its content stream rebuilt from that graph, and the rebuild does not preserve everything the original said: colour comes back as rg/RG, and shadings, text clipping modes and Type 3 glyph runs are dropped. Edit the pages you mean to change and nothing else.

SaveMode chooses between the two file shapes. An incremental save appends and leaves the original bytes intact, which is what keeps an existing digital signature verifiable and what a reader expects of a form fill; a full save rewrites and can drop what nothing references any more. An unencrypted save is byte-reproducible under IdSource::Fixed. An encrypted one draws its file key and AES vectors from the operating system: reproducible ciphertext is reproducible secrets, which is not what a seed is for.

Part of pdfrum. #![forbid(unsafe_code)].

MIT OR Apache-2.0

Structs§

AnnotBorder
Width and style for an annotation /BS dictionary.
AnnotMeta
Optional dictionary fields common to every annotation subtype.
AnnotWrite
An AnnotSpec plus optional AnnotMeta for writing.
AttachmentOptions
What an attachment carries besides its name and bytes.
AttachmentOptionsBuilder
Builds an AttachmentOptions a setting at a time.
AxisValue
One axis at one user-space value.
BookmarkSpec
One bookmark, as a caller describes it.
Canvas
One page’s drawing surface.
CaretSpec
A caret annotation (/Subtype /Caret).
CircleSpec
A circle / ellipse annotation (/Subtype /Circle).
Dash
A dash pattern — ISO 32000-1 §8.4.3.6’s dash array and phase, written as d.
EditDoc
A document plus the edits made to it.
EmbeddedFont
A font dictionary this session added, ready to name from a content stream.
EmbeddedImage
An image XObject this session added, ready to place on a page.
Encryption
How a document is to be encrypted on save (ISO 32000-2 §7.6.4.4).
EncryptionBuilder
Builds an Encryption one setting at a time.
Encryptor
Enciphers the strings and stream payloads of one indirect object.
FieldSpec
A form field to create.
FileId
The /ID array a save will write, and whether minting it invalidated the document’s encryption key.
FreeTextSpec
A free-text annotation (/Subtype /FreeText): text drawn on the page rather than held behind an icon.
GidMap
How the glyphs of a font were renumbered by subsetting.
GlyphFont
A face embedded for glyph runs, ready to draw with Canvas::glyphs.
GlyphRun
A shaped run, ready to draw with Canvas::glyphs.
Gradient
A colour ramp, in its own coordinate space.
GradientStop
One colour of a Gradient.
ImageBuilder
An image placement, ready to PageEdit::push.
ImportOptions
How an import behaves.
ImportOptionsBuilder
Builds an ImportOptions one setting at a time.
InkSpec
A freehand ink annotation (/Subtype /Ink).
IvSource
Where a save’s AES initialisation vectors come from.
LineSpec
A line annotation (/Subtype /Line).
LinkSpec
A link annotation (/Subtype /Link).
MarkupSpec
A text-markup annotation: Highlight, Underline, StrikeOut, or Squiggly.
MissingGlyph
A character an embedded font has no glyph for.
MiterLimit
The ratio of miter length to line width past which a LineJoin::Miter corner is drawn beveled instead — ISO 32000-1 §8.4.3.5’s M.
NUpOptions
How an N-up imposition behaves.
NUpOptionsBuilder
Builds an NUpOptions one setting at a time.
PageLabelRange
One labelling rule, and the page it starts at.
PageRange
A parsed page range: zero-based page indices, in the order named, with duplicates kept.
PageRewrite
Everything a save has to do to a page whose objects were edited.
PathBuilder
A filled or stroked path, ready to PageEdit::push.
Quad
One quadrilateral for a text-markup annotation (/QuadPoints).
Regenerated
One regenerated /Contents element.
ResourceTable
The resource dictionaries of one page, while its streams are regenerated.
RunGlyph
One glyph of a run: which glyph, where its origin sits, and which bytes of the run’s text it was shaped from.
SaveOptions
Everything a save may be asked to do differently.
SaveOptionsBuilder
Builds a SaveOptions one setting at a time.
Size
A 2D size.
SquareSpec
A square / area annotation (/Subtype /Square).
StampOptions
How a stamp is drawn.
StampOptionsBuilder
Builds a StampOptions a setting at a time.
Stroke
A stroke’s colour, width and pen shape, in canvas units.
Subsetted
A subset font program and the renumbering it performed.
SvgFontssvg-text
The font faces an ingested SVG’s <text> may be set in.
SvgFormsvg-import
Drawing compiled once into a Form XObject, placeable on any number of pages.
SvgIngestReportsvg-import
Everything one draw_svg could not carry into the page.
TextBuilder
A run of text, ready to PageEdit::push.
TextSpec
A sticky-note text annotation (/Subtype /Text).
UnknownFlattenMode
The error FlattenMode’s FromStr returns.
UnknownStampPosition
The error StampPosition’s FromStr returns.
UnsupportedItemsvg-import
One construct the walk could not carry, and where it was.
ViewerPreferences
The preferences a document can ask for.
WidgetAppearance
A widget’s appearance characteristics — its /MK dictionary.

Enums§

AnnotGoToView
Destination view for a AnnotLinkAction::GoTo action.
AnnotLinkAction
Write-side link action, aligned with pdfrum_doc::ActionKind values we support on annotations.
AnnotLinkHighlight
Link annotation highlight mode (/H, ISO 32000-1 table 173).
AnnotRemoteDest
Remote destination for AnnotLinkAction::GoToR.
AnnotSpec
What kind of annotation to create and attach to a page.
BlendMode
A separable or non-separable blend mode, ISO 32000-1 tables 136-137.
BookmarkTarget
Where a bookmark sends the reader.
ContentsShape
Where a regenerated element lands in the page’s /Contents.
Duplex
How a document asks to be printed on both sides (/Duplex).
Error
A failure that stops the editor producing output.
FieldKindSpec
Which kind of control a created field is.
Fill
Which points a fill considers inside.
FlattenMode
Which annotations flattening draws.
Flattened
What flattening a page did.
FontEncoding
How character codes in a content stream select glyphs of an embedded font.
FontInstance
The instance of a variable face a glyph run is drawn at.
GradientKind
Where a Gradient runs.
IdSource
Where the bytes of a fresh /ID element come from.
LineCap
How the open ends of a stroked subpath are drawn — ISO 32000-1 §8.4.3.3’s line cap style, written as J.
LineEndingStyle
Line ending style written in /LE (ISO 32000-1 table 166 / §12.5.6.7).
LineJoin
How two segments meet at a corner — ISO 32000-1 §8.4.3.4’s line join style, written as j.
MarkupKind
Which text-markup subtype a MarkupSpec writes.
PageBox
One of the five page boxes (ISO 32000-1 §14.11.2).
PageLabelStyle
How the numeric part of a label is written.
Paint
How a shape is painted.
PixelFormat
How the bytes handed to crate::EditDoc::embed_image are laid out.
Relationship
What an associated file is to the thing it is associated with (/AFRelationship, ISO 32000-2 table 404).
SaveMode
How a document is written back out.
StampPosition
Where a stamp sits on the page, as the page is displayed.
StandardFont
One of the fourteen standard fonts.
SvgFitsvg-import
How the SVG’s own coordinate box is placed in the destination rectangle.
Unsupportedsvg-import
A construct in the source SVG that PDF drawing cannot carry.

Constants§

DEFAULT_DA
Default /DA for AnnotSpec::FreeText: black Helvetica 12 pt.
DEFAULT_FIELD_DA
The default /DA a created field takes when the caller names none: black Helvetica, auto-sized.

Traits§

BorderStyleName
The /BS /S name a AnnotBorderStyle is written as.

Functions§

add_annotation
Adds an annotation described by spec to page, returning the new annotation’s object reference.
add_attachment
Adds an embedded file named name, sorted into the /EmbeddedFiles name tree by name — creating the tree when the document has none — and returns its index among the attachments.
add_blank_page
Add an empty page of width by height points at index at (past the end appends), and return its reference.
add_form_field
Creates a form field and its widget, and returns the field’s reference.
add_form_font
Registers a face in the form’s /DR /Font under name, so a /DA may name it.
apply_rewrite
Apply a page’s regenerated content to edit.
associate_file_with_document
Associates the attachment at index with the document, by adding it to the catalog’s /AF.
associate_file_with_page
Associates the attachment at index with one page, by adding it to that page’s /AF.
blank_document
A document of blank pages, one per entry of pages, each width by height points and in that order.
build_graph
The object graph of dict’s page for editing, read through r: the base document for a page as it was opened, or an editing session’s overlay for the page as that session’s edits leave it — so a stream an earlier edit appended is a clean stream of the graph, and the names it uses are kept.
clear_open_action
Removes the catalog’s /OpenAction, so the document opens at page one with whatever view the reader prefers.
delete_annotation
Removes annot from page’s /Annots and drops the annotation object.
delete_annotation_at
Removes the annotation at index in page’s /Annots (0-based).
delete_attachment
Removes attachment index from the name tree; Ok(false) when there is no such attachment.
delete_named_destination
Removes a named destination, answering whether it was there.
delete_pages
Delete the pages range names, by the base document’s numbering.
document_associated_files
The attachments the catalog’s /AF names, by index into attachments’s ordering, each with the relationship its specification states.
ensure_named_destination
Like set_named_destination, but leaves an existing name untouched.
flatten
Bakes the page’s annotation appearances into its content and removes the annotations, the reference implementation’s way: one form XObject FFT<n> (the first such name free in the page’s /XObject resources), its box the crop box, drawing each appearance stream through the matrix that lands its box on the annotation’s rectangle; the page’s own content wrapped in q … Q with the form’s Do after it; /MediaBox and /CropBox normalized and written; the retired widgets pruned from the interactive form, which goes when it empties. A widget another page also lists keeps the form.
flatten_document
Flattens every page, the way a caller who wants “no annotations left” means it.
import_pages
Import pages from src into dest.
n_page_to_one
Impose pages from src onto sheets in dest.
named_destinations
Every name the document’s /Names /Dests carries, sorted.
page_associated_files
As document_associated_files, for one page’s /AF.
pdf_date
time as a PDF date string (ISO 32000-1 §7.9.4): D:YYYYMMDDHHmmSSZ00'00', always in UTC, which is the one zone every reader agrees on.
pdf_date_to_iso8601
A PDF date string (D:YYYYMMDDHHmmSSOHH'mm') as XMP’s ISO 8601.
regenerate
Rewrite the dirty content streams of page, or None when none is dirty.
remove_attachment
Removes every attachment named name from the name tree; Ok(false) when there is none. The objects go with the next full save’s garbage collection.
reorder_pages
Reorders the document’s pages to the sequence order names.
save
Write doc to out.
set_attachment_description
Sets the file specification’s /Desc; Ok(false) when there is no such attachment.
set_attachment_file
Replaces attachment index’s embedded file with a new stream carrying /Type /EmbeddedFile, /DL <len> and /Params << /Size <len> /CheckSum <md5> >>, linked as /EF << /F <ref> >> on the file specification; a MIME type or date the old stream had is not carried over. Ok(false) when there is no such attachment.
set_attachment_file_with
Replaces attachment index’s embedded file, carrying the MIME type and date options names.
set_attachment_name
Renames attachment index, answering whether there was one to rename.
set_attachment_param
Sets a /Params text entry on attachment index’s embedded file — CreationDate, ModDate, any key — creating /Params when missing; a CheckSum given as <HEX…> is stored as that hex string. Ok(false) when the attachment has no embedded file.
set_info_entry
Set or remove one text entry of the document’s /Info dictionary.
set_info_name
Sets or removes an /Info entry whose value is a name.
set_named_destination
Upserts name into the catalog /Names /Dests name tree so named destinations (and AnnotLinkAction::Named links) resolve after save.
set_need_appearances
Sets or clears /AcroForm /NeedAppearances.
set_open_action
Sets the catalog’s /OpenAction to a destination on page.
set_outline
Replaces the document’s outline with items.
set_page_box
Set one of a page’s boxes.
set_page_labels
Sets the document’s page labels, replacing whatever it had.
set_page_rotation
Set a page’s /Rotate. degrees is normalized to a multiple of 90; a value that is not one is rounded to the nearest.
set_page_rotation_to
Sets a page’s /Rotate from the read side’s own Rotation.
set_viewer_preferences
Sets the catalog’s /ViewerPreferences.
set_widget_appearance
Sets a widget annotation’s /MK appearance characteristics.
set_xmp_metadata
Sets or removes the document’s XMP metadata stream (/Metadata).
shared_objects
The object numbers more than one object in doc points at.
string_width
The advance of codes in the font font names, in thousandths of an em.
subset
Subset a font program to gids.
to_pdfa
Run the conversion, returning what it did and the bytes when it converted.
update_annotation
Replaces an existing annotation object in place, regenerating /AP when the subtype has an appearance generator.
update_annotation_at
Resolves index in page’s /Annots array (0-based) to an ObjRef, then calls update_annotation.
write_float
Append one number: 10.5, .29, -7, 0.
write_matrix
Append a matrix as a b c d e f — single spaces, no brackets, no trailing space. This is the operand list of cm and Tm.
write_point
Append a point as x y.
write_rect
Append a rectangle as left bottom width height — not the x0 y0 x1 y1 an array-valued /MediaBox uses. This is the operand list of re, so the last two numbers are extents and may be negative.

Type Aliases§

AnnotBorderStyle
Border style written as /BS /S (ISO 32000-1 table 166).
ShareCounts
How many objects still reference each object number.