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§
- Annot
Border - Width and style for an annotation
/BSdictionary. - Annot
Meta - Optional dictionary fields common to every annotation subtype.
- Annot
Write - An
AnnotSpecplus optionalAnnotMetafor writing. - Attachment
Options - What an attachment carries besides its name and bytes.
- Attachment
Options Builder - Builds an
AttachmentOptionsa setting at a time. - Axis
Value - One axis at one user-space value.
- Bookmark
Spec - One bookmark, as a caller describes it.
- Canvas
- One page’s drawing surface.
- Caret
Spec - A caret annotation (
/Subtype /Caret). - Circle
Spec - 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.
- Embedded
Font - A font dictionary this session added, ready to name from a content stream.
- Embedded
Image - An image
XObjectthis 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).
- Encryption
Builder - Builds an
Encryptionone setting at a time. - Encryptor
- Enciphers the strings and stream payloads of one indirect object.
- Field
Spec - A form field to create.
- FileId
- The
/IDarray a save will write, and whether minting it invalidated the document’s encryption key. - Free
Text Spec - 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.
- Glyph
Font - A face embedded for glyph runs, ready to draw with
Canvas::glyphs. - Glyph
Run - A shaped run, ready to draw with
Canvas::glyphs. - Gradient
- A colour ramp, in its own coordinate space.
- Gradient
Stop - One colour of a
Gradient. - Image
Builder - An image placement, ready to
PageEdit::push. - Import
Options - How an import behaves.
- Import
Options Builder - Builds an
ImportOptionsone setting at a time. - InkSpec
- A freehand ink annotation (
/Subtype /Ink). - IvSource
- Where a save’s AES initialisation vectors come from.
- Line
Spec - A line annotation (
/Subtype /Line). - Link
Spec - A link annotation (
/Subtype /Link). - Markup
Spec - A text-markup annotation: Highlight, Underline,
StrikeOut, or Squiggly. - Missing
Glyph - A character an embedded font has no glyph for.
- Miter
Limit - The ratio of miter length to line width past which a
LineJoin::Mitercorner is drawn beveled instead — ISO 32000-1 §8.4.3.5’sM. - NUpOptions
- How an N-up imposition behaves.
- NUpOptions
Builder - Builds an
NUpOptionsone setting at a time. - Page
Label Range - One labelling rule, and the page it starts at.
- Page
Range - A parsed page range: zero-based page indices, in the order named, with duplicates kept.
- Page
Rewrite - Everything a save has to do to a page whose objects were edited.
- Path
Builder - A filled or stroked path, ready to
PageEdit::push. - Quad
- One quadrilateral for a text-markup annotation (
/QuadPoints). - Regenerated
- One regenerated
/Contentselement. - Resource
Table - 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.
- Save
Options - Everything a save may be asked to do differently.
- Save
Options Builder - Builds a
SaveOptionsone setting at a time. - Size
- A 2D size.
- Square
Spec - A square / area annotation (
/Subtype /Square). - Stamp
Options - How a stamp is drawn.
- Stamp
Options Builder - Builds a
StampOptionsa 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.
- SvgFonts
svg-text - The font faces an ingested SVG’s
<text>may be set in. - SvgForm
svg-import - Drawing compiled once into a Form
XObject, placeable on any number of pages. - SvgIngest
Report svg-import - Everything one
draw_svgcould not carry into the page. - Text
Builder - A run of text, ready to
PageEdit::push. - Text
Spec - A sticky-note text annotation (
/Subtype /Text). - Unknown
Flatten Mode - The error
FlattenMode’sFromStrreturns. - Unknown
Stamp Position - The error
StampPosition’sFromStrreturns. - Unsupported
Item svg-import - One construct the walk could not carry, and where it was.
- Viewer
Preferences - The preferences a document can ask for.
- Widget
Appearance - A widget’s appearance characteristics — its
/MKdictionary.
Enums§
- Annot
GoTo View - Destination view for a
AnnotLinkAction::GoToaction. - Annot
Link Action - Write-side link action, aligned with
pdfrum_doc::ActionKindvalues we support on annotations. - Annot
Link Highlight - Link annotation highlight mode (
/H, ISO 32000-1 table 173). - Annot
Remote Dest - Remote destination for
AnnotLinkAction::GoToR. - Annot
Spec - What kind of annotation to create and attach to a page.
- Blend
Mode - A separable or non-separable blend mode, ISO 32000-1 tables 136-137.
- Bookmark
Target - Where a bookmark sends the reader.
- Contents
Shape - 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.
- Field
Kind Spec - Which kind of control a created field is.
- Fill
- Which points a fill considers inside.
- Flatten
Mode - Which annotations flattening draws.
- Flattened
- What flattening a page did.
- Font
Encoding - How character codes in a content stream select glyphs of an embedded font.
- Font
Instance - The instance of a variable face a glyph run is drawn at.
- Gradient
Kind - Where a
Gradientruns. - IdSource
- Where the bytes of a fresh
/IDelement 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. - Line
Ending Style - Line ending style written in
/LE(ISO 32000-1 table 166 / §12.5.6.7). - Line
Join - How two segments meet at a corner — ISO 32000-1 §8.4.3.4’s line join
style, written as
j. - Markup
Kind - Which text-markup subtype a
MarkupSpecwrites. - PageBox
- One of the five page boxes (ISO 32000-1 §14.11.2).
- Page
Label Style - How the numeric part of a label is written.
- Paint
- How a shape is painted.
- Pixel
Format - How the bytes handed to
crate::EditDoc::embed_imageare laid out. - Relationship
- What an associated file is to the thing it is associated with
(
/AFRelationship, ISO 32000-2 table 404). - Save
Mode - How a document is written back out.
- Stamp
Position - Where a stamp sits on the page, as the page is displayed.
- Standard
Font - One of the fourteen standard fonts.
- SvgFit
svg-import - How the SVG’s own coordinate box is placed in the destination rectangle.
- Unsupported
svg-import - A construct in the source SVG that PDF drawing cannot carry.
Constants§
- DEFAULT_
DA - Default
/DAforAnnotSpec::FreeText: black Helvetica 12 pt. - DEFAULT_
FIELD_ DA - The default
/DAa created field takes when the caller names none: black Helvetica, auto-sized.
Traits§
- Border
Style Name - The
/BS /Sname aAnnotBorderStyleis written as.
Functions§
- add_
annotation - Adds an annotation described by
spectopage, returning the new annotation’s object reference. - add_
attachment - Adds an embedded file named
name, sorted into the/EmbeddedFilesname 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
widthbyheightpoints at indexat(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 /Fontundername, so a/DAmay name it. - apply_
rewrite - Apply a page’s regenerated content to
edit. - associate_
file_ with_ document - Associates the attachment at
indexwith the document, by adding it to the catalog’s/AF. - associate_
file_ with_ page - Associates the attachment at
indexwith one page, by adding it to that page’s/AF. - blank_
document - A document of blank pages, one per entry of
pages, eachwidthbyheightpoints and in that order. - build_
graph - The object graph of
dict’s page for editing, read throughr: 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
annotfrompage’s/Annotsand drops the annotation object. - delete_
annotation_ at - Removes the annotation at
indexinpage’s/Annots(0-based). - delete_
attachment - Removes attachment
indexfrom 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
rangenames, by the base document’s numbering. - document_
associated_ files - The attachments the catalog’s
/AFnames, by index intoattachments’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
XObjectFFT<n>(the first such name free in the page’s/XObjectresources), 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 inq … Qwith the form’sDoafter it;/MediaBoxand/CropBoxnormalized 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
pagesfromsrcintodest. - n_
page_ to_ one - Impose
pagesfromsrconto sheets indest. - named_
destinations - Every name the document’s
/Names /Destscarries, sorted. - page_
associated_ files - As
document_associated_files, for one page’s/AF. - pdf_
date timeas 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, orNonewhen none is dirty. - remove_
attachment - Removes every attachment named
namefrom 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
ordernames. - save
- Write
doctoout. - 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 dateoptionsnames. - set_
attachment_ name - Renames attachment
index, answering whether there was one to rename. - set_
attachment_ param - Sets a
/Paramstext entry on attachmentindex’s embedded file —CreationDate,ModDate, any key — creating/Paramswhen missing; aCheckSumgiven 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
/Infodictionary. - set_
info_ name - Sets or removes an
/Infoentry whose value is a name. - set_
named_ destination - Upserts
nameinto the catalog/Names /Destsname tree so named destinations (andAnnotLinkAction::Namedlinks) resolve after save. - set_
need_ appearances - Sets or clears
/AcroForm /NeedAppearances. - set_
open_ action - Sets the catalog’s
/OpenActionto a destination onpage. - 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.degreesis 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
/Rotatefrom the read side’s ownRotation. - set_
viewer_ preferences - Sets the catalog’s
/ViewerPreferences. - set_
widget_ appearance - Sets a widget annotation’s
/MKappearance characteristics. - set_
xmp_ metadata - Sets or removes the document’s XMP metadata stream (
/Metadata). - shared_
objects - The object numbers more than one object in
docpoints at. - string_
width - The advance of
codesin the fontfontnames, 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
/APwhen the subtype has an appearance generator. - update_
annotation_ at - Resolves
indexinpage’s/Annotsarray (0-based) to anObjRef, then callsupdate_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 ofcmandTm. - write_
point - Append a point as
x y. - write_
rect - Append a rectangle as
left bottom width height— not thex0 y0 x1 y1an array-valued/MediaBoxuses. This is the operand list ofre, so the last two numbers are extents and may be negative.
Type Aliases§
- Annot
Border Style - Border style written as
/BS /S(ISO 32000-1 table 166). - Share
Counts - How many objects still reference each object number.