Repository navigation
chore(deps): update dependency pikepdf to v10 - #571
Open
renovate[bot] wants to merge 1 commit into
Open
renovate[bot] wants to merge 1 commit into
renovate[bot] wants to merge 1 commit into
Conversation
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #571 +/- ##
=======================================
Coverage 72.72% 72.72%
=======================================
Files 4 4
Lines 44 44
=======================================
Hits 32 32
Misses 12 12 ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
renovate
Bot
force-pushed
the
renovate/pikepdf-10.x
branch
6 times, most recently
from
November 13, 2026 13:56
84f2be2 to
c5ebc41
Compare
renovate
Bot
force-pushed
the
renovate/pikepdf-10.x
branch
7 times, most recently
from
November 20, 2026 08:30
a31b517 to
e31f756
Compare
renovate
Bot
force-pushed
the
renovate/pikepdf-10.x
branch
4 times, most recently
from
November 27, 2026 03:11
981701c to
ac34ad3
Compare
renovate
Bot
force-pushed
the
renovate/pikepdf-10.x
branch
2 times, most recently
from
December 1, 2026 13:35
a2a05ff to
edc0fbd
Compare
renovate
Bot
force-pushed
the
renovate/pikepdf-10.x
branch
from
December 1, 2026 22:15
edc0fbd to
7da7f90
Compare
This branch has not been deployed
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Note
This PR body was truncated due to platform limits.
This PR contains the following updates:
9.8.1→10.18.3Release Notes
pikepdf/pikepdf (pikepdf)
v10.18.3Compare Source
pikepdf.pdfa.checknow predicts the right stream filters withqpdf versions newer than 12.4.2. Those versions keep the compressed data of a
stream whose
/Filteris the one-element array[/FlateDecode]instead ofrecompressing it. qpdf 12.4.2 recompressed such streams, which removed any
predictor and could make scanned images larger. {issue}
qpdf/qpdf#1785v10.18.2Compare Source
Pdfat once,such as
Pdf.add_pages_from()and signature stamping. Two unrelated internalC++ classes had the same name, which broke the one-definition rule. The MSVC
linker then gave both classes the destructor of one of them. Free-threaded
(
cp314t) Windows wheels, which were left out of v10.18.0 because of thesecrashes, are provided again. {issue}
757it about 14% smaller. Source builds use it where the toolchain supports it.
To build without it, pass
-C cmake.define.PIKEPDF_LTO=OFF.v10.18.1Compare Source
Noneinto a page list, withpdf.pages.extend(), sliceassignment or
pdf.pages[i] = None, now raises the usual "only pikepdfpages"
TypeError. When pikepdf was built with nanobind older than 2.13, assome Linux distributions do, an iterator containing
Nonecould instead besilently discarded without inserting any pages, or a misleading "incompatible
function arguments" error was raised. {pr}
759it.
v10.18.0Compare Source
pikepdf.Pdf.add_pages_fromnow carries layers (optional content) withthe pages it copies. The optional content groups that the copied pages
depend on are listed in the destination's
/OCProperties, with the defaultvisibility, place in the layer list, lock, radio button groups and automatic
states that the source's default configuration gave them. Previously the
groups were copied but not listed, so viewers ignored them: the layer list
was empty and content hidden in the source was shown. {issue}
118pikepdf.Pdf.add_pages_fromnow carries bookmarks. Outline items ofthe source that lead to a copied page are appended to the destination's
outline, keeping their hierarchy, titles and style; items that lead to pages
that were not copied are dropped. {issue}
281add_pages_fromget: the destination may gain an/OCPropertiesandoutline items it did not gain before. Pass
layers='ignore'oroutlines='ignore'for the previous behaviour, for example if you buildthe merged outline yourself. {class}
pikepdf.PageCopyResultreportslayers_added,outline_items_addedandoutline_items_dropped.pikepdf.Pdf.check_pdf_syntaxnow performs the same checks asqpdf --checkand reports the same problems. It checks the linearizationdata and hint tables of linearized files, which previously required a
separate call to {meth}
pikepdf.Pdf.check_linearization, and checks theinteractive form, embedded files, page labels and outlines. A document with
no pages is reported as
ERROR: file does not contain any pages, and a pagewhose content stream cannot be read is reported as
ERROR: page N: ...along with the other problems found, where it previously raised
{class}
pikepdf.PdfError. {issue}515pikepdf.Dictionaryor {class}pikepdf.Arraythatrefers to another
Pdfinto aPdfnow raises{exc}
pikepdf.ForeignObjectError, naming the key or index where theforeign object was found, and leaves the target unchanged. This covers an
indirect object of another
Pdfheld anywhere in the value, such aspdf3.Root.X = Dictionary(P=pdf1.Root.Y), and a direct dictionary or arraythat another
Pdfalready contains. Previously the value was accepted:the first kind made the
Pdfimpossible to save, failing part way throughwriting, and the second left two documents sharing one object. It applies
to every way of inserting a value, including {meth}
pikepdf.Pdf.make_indirect,{meth}
pikepdf.Page.add_resource, adding a page built from a dictionary,name and number trees, and stream dictionaries. Use
{meth}
pikepdf.Pdf.copy_foreignto bring the foreign object over first.ValueError, bothwhen opening a PDF and when encrypting one. Previously the password was
silently cut short at the NUL, so a wrong password could open a file, and an
encrypted file could be written with a shorter password than requested.
PDF passwords may not contain NUL. {issue}
756Pdfon GIL-enabledbuilds, which could cause an object to be read as
None. The per-Pdflockis now in force on every build, and {meth}
pikepdf.Pdf.lockworks onGIL-enabled builds too. {commit}
7c761d23Pdfin several steps, such as{meth}
pikepdf.Page.add_overlay, {meth}pikepdf.Pdf.add_pages_fromandthe {mod}
pikepdf.sanitizefunctions, now hold its lock until they finish.The thread safety section of the architecture notes now says which calls are
atomic. {commit}
0872a6e8, {commit}b10671c3Pdfand then need the other'sno longer deadlock; one of them gets a {exc}
RuntimeErrorinstead. What acallback such as a {class}
pikepdf.TokenFiltermay do is now documented:see {ref}
callback-restrictions. {commit}11ef776bexceptcan catch,when reading, saving or checking a PDF in which a JBIG2 image's
/JBIG2Globalsstream is itself JBIG2-encoded and leads back to the image,directly or through other streams. Such an image is now reported as
unfilterable, as JBIG2-encoded globals without a cycle already were:
reading it raises {exc}
~pikepdf.exceptions.PdfError, extracting it raises{exc}
~pikepdf.exceptions.UnsupportedImageTypeError, and saving writes itunchanged with a warning. {issue}
753/JBIG2Globalsare now read only when the image is beingJBIG2-decoded, rather than every time qpdf checks whether the image can be
decoded, which included every save.
as
/S /Z, now warns and keeps the label prefix, as an invalid non-namestyle already did. Previously it raised
KeyError.label style, such as
/S /R /St 0or a Roman numeral above 5000, now warnsand writes the number in decimal digits. Previously it raised
ValueError./CalGrayor/CalRGBcolour space array lacksits parameter dictionary now decodes it as the corresponding device space,
without an ICC profile, as a missing
/WhitePointalready did. Previouslyit raised
IndexError./N, or givesone that is not an integer, now takes its mode and default
/Decodefromthe profile's colour space. Previously its mode raised
KeyError.pikepdf.form.SignatureField.stamp_overlaystamping theoverlay twice when the signature widget names its page with
/P.Pdfreturned by {meth}pikepdf.Job.create_pdfnot being set uplike other
Pdfobjects: setting itsconversion_moderaised{class}
pikepdf.PdfError, and on free-threaded Python none of its methodswere protected by a lock.
Matrix.__array__(copy=False)now raisesValueError, as numpy expects ofan object that cannot share its memory. The check for this was written in a
way that never fired.
progressargument to {meth}pikepdf.Pdf.savethat is not callable isnow rejected with
TypeErrorbefore anything is written. Previously theerror was raised part of the way through writing the file.
{meth}
pikepdf.AcroForm.get_fields_with_qualified_nameor{meth}
pikepdf.AcroForm.fix_copied_annotationsreturned a field.pikepdf.NameTreeor {class}pikepdf.NumberTreenow iterates over the keys it had when the iteration began. Previously the
tree was read as the iteration went on, so changing it meanwhile gave
undefined results.
Pdfin a{class}
pikepdf.NameTreeor {class}pikepdf.NumberTreenow raises{class}
pikepdf.ForeignObjectErrorat once, as it does for a dictionary oran array. Previously the error was not raised until the
Pdfwas saved.x in treeis nowFalsefor anxthat cannot be a key of a{class}
pikepdf.NameTree, such as anint, and forNonein a{class}
pikepdf.NumberTree. Previously these raisedTypeError.pikepdf.NameTree,which said that names are
bytes. Names are, and have always been,str:qpdf reads each name as a PDF text string and compares names by that text.
failed with
cannot locate symbol "_Py_TrueStruct"since v10.6.0. Theextension module is now linked against libpython when the build interpreter
is an Android Python, as that platform requires. Android is not a tested
platform. {issue}
752Free-threaded Python fixes
Many crashes and data races that occurred when several threads used the same
Pdfat once have been fixed. The test suite now runs under ThreadSanitizerin continuous integration, which is how most of them were found
({commit}
4831f6fc).Pdfnow takes thatPdf's lock,and the lock of any other
Pdfamong its arguments, enforced at compiletime. Many bindings previously did not, notably most methods of
{class}
pikepdf.NameTree, {class}pikepdf.NumberTree, attachments,annotations and {class}
pikepdf.AcroForm. {commit}3c5b2bc4pikepdf.Pagemethods, contentstream parsing, adding pages from one
Pdfto another, and dropping thelast reference to a
Pdfwhile another thread used one of its objects.{commit}
04999fafpikepdf.Dictionaryor {class}pikepdf.Arraythat belongs to noPdfis now protected by a lock shared by all such objects. Threads thateach build objects of their own contend for it, so add a
DictionaryorArrayto itsPdfas soon as it is created rather than building largestructures before adding them. {commit}
5e11a240, {commit}b10671c3opened a
Pdf's metadata for the first time at once. {commit}d52a9a11Pdfare no longer slowed to acrawl when every CPU is busy. {commit}
a3e2b882Free-threaded wheels are not provided for Windows in this release. They crash
in the test suite, for reasons that have not yet been found, so free-threaded
Python on Windows is not supported for now. Linux and macOS free-threaded
wheels are provided as before. {issue}
757v10.17.0Compare Source
pikepdf.ObjectSet, which records the objects that a walk ofa PDF's object graph has already visited. Objects in a PDF are shared and
may refer back to their ancestors, so a search that only limits its depth
can take exponential time on quite ordinary files.
ObjectSet.add()reportswhether an object is new, and tells apart direct objects and objects of
different
Pdf, which asetofobjgencannot. See{ref}
walking-object-graphs.pikepdf.Object.is_same_object_as, which tests whether tworeferences lead to the same object. Neither
is,==nor comparingobjgenanswers this reliably.pikepdf.Pdf.content_scopesand{meth}
pikepdf.Page.content_scopes, which iterate over every content streamthat pages can draw, each with the resource dictionary it uses: the page
itself, form XObjects, annotation appearance streams, tiling patterns,
Type 3 glyph procedures and soft masks, however they are nested or shared.
This is the way to find every font, image or colour space a document uses.
Each {class}
pikepdf.ContentScopeis reported once for the document;pages=selects pages andkinds=selects what is reported.pikepdf.Page.get_resources, which returns the resources of apage or form XObject for reading. Unlike {attr}
pikepdf.Page.resources, itfinds resources inherited from the page tree, does not create an empty
dictionary when there are none, and returns
Noneinstead of raising when/Resourcesis malformed.==taking exponential time when theobjects being compared share children, such as the same file opened twice.
Each pair of objects is now compared once.
pikepdf.Pdf.add_pages_fromhanging on a page with an actionwhose
/Nextactions are shared or form a loop.pikepdf.Pdf.open_outlinereading only the first item at eachlevel of an outline whose items are direct objects. Such items are now made
indirect when the outline is saved, as the PDF specification requires.
{exc}
~pikepdf.exceptions.DataDecodingErrorwith the reason, whether thestream's data was read from a file or set from memory. Previously a stream
read from a file raised a {exc}
~pikepdf.exceptions.PdfErrorthat said only"read_bytes called on unfilterable stream", and the reason was available
only from {meth}
pikepdf.Pdf.get_warnings.DataDecodingErroris aPdfError, so existing handlers are unaffected. {issue}182{meth}
pikepdf.PdfImage.as_pil_image, {meth}pikepdf.PdfImage.extract_toand {meth}
pikepdf.PdfImage.read_bytesunchanged, with its own type,message and traceback. Previously, for an image read from a file, it was
replaced by a generic
DataDecodingErrororPdfError. {issue}182~pikepdf.exceptions.QpdfRuntimeError, raised for errors fromqpdf that pikepdf has no more specific exception for. These were previously
raised as a bare
RuntimeError, whichexcept pikepdf.PikepdfErrordid notcatch. The new exception derives from both
{exc}
~pikepdf.exceptions.PikepdfErrorandRuntimeError, so handlerswritten for
RuntimeErrorstill work. {issue}240/is now supported. The PDF 1.7 and 2.0 specificationsdefine a lone slash as a valid name made of zero characters, but
pikepdf.Name('/')raisedValueError, and dictionaries refused/as akey. This broke {meth}
pikepdf.Pdf.add_pages_fromon fileswith an empty-named destination such as
/Dests << / 3 0 R >>. Such namescan now be created, used as dictionary keys, and migrated during page
copying.
bool(Name('/'))isFalse, like an empty {class}pikepdf.String.Name(''), which lacks the leading slash, is still rejected. PDF/A does notforbid empty names, and the PDF/A validator accepts them. Thanks to
@sjudd for the report and @DSeaStar for the analysis. {issue}
745AcroFormField.get_inheritable_field_value_as_name()now returns a{class}
pikepdf.Name, as documented, instead of astr. When the value ismissing or not a name, it returns the empty name
Name('/'), which is falsy,instead of
''. Comparisons such as== '/Tx'are unaffected. {issue}748whose
readinto()reports more bytes than were requested. This now raisesValueError, as writing to such a stream already did. Non-blocking streams,whose
readinto()returnsNone, now raiseValueErrorinstead of hanging.Thanks to @Nayana-Naik73. {issue}
747PyPy now reads Python file objects through
readinto(), like CPython,instead of copying the result of
read().pikepdf.openreads directly from the file descriptor when given afilename, instead of calling the
seek()andreadinto()methods of aPython file object for every read. Opening and reading a large file with
many objects is about four to five times faster, matching the speed of
memory mapping (
access_mode=AccessMode.mmap). Streams passed to{func}
pikepdf.open, including plain file objects, are read through theirmethods as before.
pikepdf.TokenFilterwith worked examples that shortennumbers and convert RGB colors to grayscale, and explained when to use a
token filter instead of {func}
pikepdf.parse_content_stream. The APIreference no longer says that the parser should not be used to edit content
streams. The
TokenFilter.handle_tokendocumentation now says correctly thatexceptions it raises propagate to the caller. {issue}
62v10.16.0Compare Source
744of qpdf, since it is the first release with Windows ARM64 binaries.
pikepdf.sanitize.remove_javascript,{func}
pikepdf.sanitize.remove_external_access,{func}
pikepdf.sanitize.remove_multimediaand the matching{class}
pikepdf.sanitize.Sanitizersteps missed actions attached to formfield dictionaries. Actions survived on a field stored separately from its
widget annotation, on a hidden field with no widget (such as a calculation
helper), on nested fields under
/Kids, and on widgets that appear on nopage. The sanitizer now walks the whole
/AcroFormfield tree. Thanks toStjorn for the report.
/Nextchain untouched past itsdepth limit of 50, so a targeted action (for example a
/JavaScriptaction)buried deeper survived, and the step that preserves benign downstream actions
could promote it to a shallower position. The chain is now severed at the
limit, which also drops any benign actions past it. Thanks to @Nayana-Naik73.
{issue}
746/Nextchain that is not anaction dictionary, such as a nested array, instead of passing it through
unexamined. It raised
AttributeErrororValueErroron some such values(for example
/Next [42]), and now runs in explicit conversion moderegardless of the caller's settings, so malformed values of the wrong type
are skipped rather than crashing it.
v10.15.0Compare Source
PDF/A-3 attachments
Pdf.attachmentsnow lists its file specificationin the document catalog's
/AF(associated files) array, and deleting orreplacing an attachment removes its entry. Together with the
/AFRelationshippikepdf already writes, a file attached to a PDF/A-3document now keeps it conformant. qpdf maintains only the
/EmbeddedFilesname tree, so this was previously left to the user. {issue}
463/EmbeddedFilesname tree and the catalog's/AFarray are checked againstclause 6.8 of ISO 19005-3 (MIME type,
/Fand/UF,/AFRelationship,and that every embedded file is an associated file). Embedded files anywhere
else, such as in file attachment annotations, are still reported as
unsupported; they remain violations in PDF/A-1b and unsupported in PDF/A-2b.
{func}
pikepdf.pdfa.preparegives PDF/A-3 embedded files a missing MIME type(
application/octet-stream) and/AFRelationship(/Unspecified), andlists unassociated ones in the catalog's
/AFarray; new{class}
pikepdf.pdfa.PrepareResultfields count these repairs. See{ref}
pdfa-attachments.PDF/A named destinations
/Destsname treeand in the catalog's
/Destsdictionary, instead of reporting them asunsupported. Named destinations are common: pdfTeX (hyperref), Acrobat
Distiller and JasperReports write them. It also checks named appearance
streams (
/Names /AP) as Form XObjects./AlternatePresentationsis now reported as a violation of PDF/A-2 andPDF/A-3 (clause 6.10), and document-level JavaScript (
/Names /JavaScript)as a violation of the rule forbidding JavaScript actions; both were
reported as unsupported. {func}
pikepdf.pdfa.prepareremoves them.pikepdf.pdfa.preparegives the encoding of a non-symbolic TrueTypefont that has
/Differencesbut no/BaseEncodingthe base encoding/WinAnsiEncoding, as PDF/A-2 and PDF/A-3 require, when no glyph thedocument draws would change. Older producers such as OpenPDF write such
encodings. New {class}
pikepdf.pdfa.PrepareResultfields report theserepairs.
PDF/A developer extensions
(
/Extensions << /ADBE ... >>) that Acrobat writes in the document catalog,instead of reporting every such file as unsupported. qpdf rewrites this
entry to match the written version and extension level, and removes it for
PDF/A-1, and the validator checks the entry as it will be written. Other
developer extensions remain unsupported.
pikepdf.pdfa.resolve_save_kwargsaccepts an extension level inmin_versionorforce_versionfor PDF/A-2 and PDF/A-3, such as('1.7', 8).Metadata
pikepdf.models.PdfMetadata.copy_propertiescopies named XMPproperties from other metadata with their whole value: every language of a
language alternative, array order, structures and qualifiers, which
assigning a value read from the source would lose. Properties are read from
every
rdf:Descriptionwhatever itsrdf:about, and the structure of knownproperties is checked as for assignment. This is useful to restore metadata
another tool dropped while rewriting a document.
PDF/A annotations
pikepdf.pdfa.repair_annotation_flags, the step of{func}
pikepdf.pdfa.preparethat removes hidden annotations and sets thePrint flag on the rest, is now public, with its result
{class}
pikepdf.pdfa.AnnotationRepairResult. Running it before handing a fileto another PDF/A converter such as Ghostscript keeps hyperlinks that producers
wrote without the Print flag, which Ghostscript's PDF/A mode deletes.
Fixes
/DL(decoded length)as unsupported on content streams, images, metadata streams and output
intent profiles, so a file whose producer writes it could not be converted.
It is now accepted on every stream.
/Differencesonly from the Adobe Glyph List for New Fonts, so it rejectedvalid PDF/A-2 and PDF/A-3 files that used other names from the full Adobe
Glyph List, such as
afii10017for Cyrillic text. It now accepts every namein the full list, as ISO 19005 requires and veraPDF checks. Names outside the
list, such as
uni0410orA.sc, are still rejected.Pdfopened or created withconversion_mode='explicit'returned plainintfor some numbers that qpdf writes itself, such as/Pages /Countafter adding or removing a page,
/Rotateafter {meth}pikepdf.Page.rotate,or the
/BBoxof {meth}pikepdf.Page.as_form_xobject. These values nowfollow the document's conversion mode like any other.
IntegerandRealnow support the rest ofthe Python number protocol, with the same results as the
intorDecimalthat implicit mode produces:
round(),math.trunc(),math.floor(),math.ceil(),divmod(), and format specs such asf'{x:.2f}'.int()of aRealnow truncates, asint()of aDecimaldoes, insteadof raising
TypeError; for exampleint(page.Rotate)now works on a/Rotate 90.0.Matrixnow accept apikepdf.Object, such as a/Matrixarray, and a list of objects, as the runtime always has.v10.14.0Compare Source
Several improvements to explicit conversion mode and
NamePath, prompted bythe OCRmyPDF project's migration to these APIs
(
pikepdf.explicit_conversion(), theas_*safe accessors, andNamePath)in a production codebase that reads untrusted, often malformed, PDFs.
Python support
2026. Python 3.11 through 3.14 are supported, and wheels are no longer built
for CPython 3.10. pip will keep installing pikepdf 10.13 on Python 3.10.
tomllib,enum.StrEnum,typing.Self,datetime.UTCand the broader ISO 8601 support indatetime.fromisoformat. The compatibility shims for Python 3.10 are gone.existing
cp314-abi3wheel; free-threaded CPython 3.15 gets its owncp315twheel, since the stable ABI does not cover free-threaded builds.Platform support
deprecating the macos-14 runner. Binary wheels now require macOS 15 or newer.
the platform is end of life. Intel Mac users can build from source, or keep
using pikepdf 10.13.
Conversion mode
pikepdf.Pdf.openand {meth}pikepdf.Pdf.newnow accept akeyword-only
conversion_modeargument ('implicit'or'explicit'), andthe mode can be read or changed afterward through the new
{attr}
pikepdf.Pdf.conversion_modeproperty. APdf's mode travels withit across threads and does not affect any other document, which makes it
the right scope for a library embedded inside a host application. Setting
the property to
Nonereverts to inheriting the context-manager/globalmode.
pikepdf.implicit_conversion, a thread-local context managersymmetric with {func}
pikepdf.explicit_conversion, so implicit mode can beforced from inside code that runs under explicit mode.
Pdfmode, then the global default set by
{func}
pikepdf.set_object_conversion_mode. An object with no owningPdf(e.g. a bare
pikepdf.Dictionary(...)you have not yet attached to adocument) resolves through the context-manager/global scopes; once it is
inserted into a
Pdfit follows that document's mode.pikepdf.Object.get_raw, which behaves like{meth}
~pikepdf.Object.get(key,Name, orNamePath, plus adefault)but never unboxes the result: it always returns a
pikepdf.Objectregardless of the current conversion mode. A null stored inside an array
comes back as a
Null-typed object rather thanNone; in a dictionary,qpdf treats a key whose value is null as absent, so
get_rawreturns thedefault for it, exactly as
getdoes.~pikepdf.Object.get_int,{meth}
~pikepdf.Object.get_bool, {meth}~pikepdf.Object.get_float,{meth}
~pikepdf.Object.get_decimal, {meth}~pikepdf.Object.get_dict, and{meth}
~pikepdf.Object.get_list, each(key_or_path, default=None). Thesecompose
get_rawwith the matchingas_*accessor, so reading an optionalvalue of uncertain type is a mode-independent one-liner instead of a
hand-written
with pikepdf.explicit_conversion(): ...wrapper.coerce=Trueto {meth}~pikepdf.Object.as_int,{meth}
~pikepdf.Object.as_bool, {meth}~pikepdf.Object.as_float, and{meth}
~pikepdf.Object.as_decimal, and to the correspondingget_*getters, for reading values that real-world PDFs encode with a "nearby"
type:
as_int(coerce=True)accepts aReal(truncated toward zero) and anumeric
String;as_bool(coerce=True)accepts a nonzeroIntegerorReal(fixing the common/Marked 1case that previously required afallback to
as_int() != 0);as_float/as_decimalwithcoerce=Trueaccept an
Integerand a numericString, including exponent notationsuch as
"1e-5".pikepdf.Integerandpikepdf.Realnow support the ordering comparisons<,<=,>and>=against Pythonint,float,bool,Decimal,and each other, so
box[0] < box[2],sorted(),min()andmax()workon explicit-mode values.
Realcompares by its exact decimal value.pikepdf.Integerandpikepdf.Realnow works between twoobjects (
Real('2.5') + Integer(3)) and withDecimalandbooloperands, and
**is supported. Results are the native Python type thatimplicit mode would have produced:
intforIntegerwithint/Integer,Decimalwhenever aRealorDecimalis involved, andfloatwith afloatoperand. In explicit mode,box[2] - box[0] > 100therefore workswithout unboxing, while raising
TypeErrorif the PDF stored a non-number.The result is never a pikepdf object: a number computed from a document is
not in the document, and returning an object would let one unmigrated read
propagate into code far from the cause.
pikepdf.unbox, which returns the native Python value of anInteger,BooleanorRealand passes any other value throughunchanged. Unlike the
as_*accessors it does not require knowing whichnumeric type a value has, and it accepts values read in either mode, so it
is the one-token migration for a read that feeds
isinstance,is True,Decimal(),json.dumpsor a function documented to return a native type.pikepdf.as_int,{func}
~pikepdf.as_bool, {func}~pikepdf.as_float,{func}
~pikepdf.as_decimal, {func}~pikepdf.as_dict,{func}
~pikepdf.as_list, {func}~pikepdf.as_strand{func}
~pikepdf.as_bytes, each(value, default=None), with keyword-onlycoercefor the numeric and boolean ones. They are the value-side twins ofthe
get_*typed getters, for an array element, content stream operand orother value already in hand: a pikepdf object converts exactly as its
as_*method does, and a native value is accepted only if it is the typeimplicit mode would have produced for that PDF type, so the result is the
same in either conversion mode.
pikepdf.as_int(True)gives the default,because a Boolean is not an Integer.
~pikepdf.Object.as_strand {meth}~pikepdf.Object.as_bytes,which return a
String's decoded text or raw bytes, and raiseTypeError(or return a supplied default) for any other type, unlike
str()andbytes(), which accept almost anything. Added the matching typed getters{meth}
~pikepdf.Object.get_strand {meth}~pikepdf.Object.get_bytes./topics/objectsfor the full description of scopes andprecedence, plus a "Migrating to explicit mode" checklist.
/topics/type_safety, explaining whyexplicit mode exists and setting out the deprecation schedule: v11 warns
on implicit conversions, v12 makes explicit mode the default, and v13
removes implicit mode. New code that reads values of uncertain type should
prefer the mode-independent getters described above.
NamePath
path in objnow tests whether the path can be traversed to a value, anddel obj[path]deletes the final component after traversing to itsparent, both for name and array-index components.
NamePathis now iterable, yielding its individual components (strfornames,
intfor indices) in order, e.g.list(NamePath.A.B[0])gives['/A', '/B', 0].NamePathinstances now compare and hash by their component sequence, soNamePath.A.B == NamePath.A.BisTrueand aNamePathcan be used as adict key or stored in a
set.isinstance(path, pikepdf.NamePath)now works, andpikepdf.NamePathcanbe used directly in type annotations (e.g.
def f(key: pikepdf.Name | pikepdf.NamePath)) without importing a privatename.
Metadata and PDF/A
OCRmyPDF tested its PDF/A output against veraPDF, and found files that
pikepdf's metadata handling made invalid.
dc:titleanddc:descriptionare nowread from their
x-defaultitem, as the XMP specification defines, ratherthan from the first item. Acrobat writes
x-defaultlast when a documenthas several languages, so
/Titleand/Subjectwere synced from the wronglanguage, and PDF/A-1 validators rejected the result.
x-defaultitem and keeps the other languages, instead of replacing all ofthem with the new value. An item that held the same text as the old default
is updated too, as Adobe's XMP toolkit does. Assigning several values to a
language alternative that pikepdf does not know joins them into one
x-defaultitem, instead of writing severalx-defaultitems.rdf:Description, not onlythose with
rdf:about="". Properties in Descriptions withrdf:about="uuid:..."(written by Distiller and older Acrobat) or with nordf:aboutcould not be read or deleted, and setting one added a duplicate,which made veraPDF reject the whole packet. Setting a property now removes
any other occurrences of it, and deleting it removes all of them.
rdf:Descriptiongets the same
rdf:aboutvalue, as the XMP specification requires, andempty Descriptions are removed. The value is kept if the non-empty values
agree, and made empty if they conflict.
pikepdf.models.PdfMetadata.recoveredandXmpDocument.recovered, which areTrueif the XMP was not well-formed andhad to be repaired or replaced as it was read.
pikepdf.PdfInlineImage.read_raw_bytes, which returns thestill-encoded data of an inline image exactly as it appears in the content
stream.
pikepdf.Pdf.savenow corrects/Countin each node of the pagetree to the number of pages beneath it. qpdf repairs a damaged page tree but
left
/Countas it was, so a wrong/Countin the input was writtenunchanged, and veraPDF could not validate the file at all.
PDF/A validation and repair
pikepdf.pdfamodule, which prepares, checks and savesPDF/A-1b, PDF/A-2b and PDF/A-3b documents. See {ref}
pdfa.pikepdf.pdfa.preparerepairs a document in memory: it installs aPDF/A output intent (sRGB by default, or a supplied ICC profile), removes
image interpolation and hidden annotations, adds
/CIDSetfor PDF/A-1,and rewrites the XMP metadata with a PDF/A declaration. It returns a
{class}
~pikepdf.pdfa.PrepareResultdescribing what changed:{meth}
~pikepdf.pdfa.PrepareResult.describegives a sentence per change,{meth}
~pikepdf.pdfa.PrepareResult.messagesthe same sentences with asuggested log level, and
PrepareResult.xmp_problemwhy an XMP packetcould not be read. XMP properties are kept from every
rdf:Descriptionwhen all share one
rdf:about, including the non-emptyuuid:...valuethat Acrobat and pikepdf's own metadata editor write.
pikepdf.pdfa.checkpredicts the verdict for the file that would bewritten, without writing it, by modelling what qpdf's writer changes
(stream filters, trailer, version, encryption and which objects are
written).
pikepdf.pdfa.saveprepares the document, writes it to a temporaryfile, reopens and validates the bytes written, and only then moves the file
into place. If the written file does not pass, it raises
{class}
~pikepdf.pdfa.PdfaErrorwith the report (whosepreparedrecordsthe repairs made), and the destination is left untouched.
pikepdf.pdfa.resolve_save_kwargsreturns the complete{meth}
pikepdf.Pdf.savesettings for a flavour. Settings that PDF/Aforbids or that would change the bytes after the check (such as
encryption,normalize_contentandfix_metadata_version) are pinned,and a conflicting value raises
ValueError.knows to conform. A {class}
~pikepdf.pdfa.Reporthas a verdict of'pass','fail'(at least one violation) or'not_checked'(only constructs thevalidator does not check, which may be valid PDF/A).
saveaccepts only'pass'. Each {class}~pikepdf.pdfa.Findingnames a rule: a veraPDF rule idsuch as
ISO_19005_2:6.2.8-3, or apikepdf:id for local policies andunsupported constructs. The validator is not a certification; veraPDF
remains the reference.
prepareandchecked against veraPDF 1.30 for each of PDF/A-1b, 2b and 3b, the validator
approved no file that veraPDF rejects. For PDF/A-2b it approved 1,363 files,
rejected 887 and left 656 not checked; veraPDF accepted 28 of the rejected
files (the validator is conservative by design). The prediction from
checkmatched the validation of the written file in every case.
read in implicit or explicit conversion mode: they work in explicit mode
internally, whatever mode the caller uses.
pikepdf.pdfaneeds jsonschema, referencing and fontTools, available asthe optional extra
pip install 'pikepdf[pdfa]'.import pikepdfdoes notimport them;
import pikepdf.pdfaraisesImportErrornaming the extra ifthey are missing.
profiles (CC BY 4.0, veraPDF Consortium); see
third-party-licenses/README.md.pikepdf._io.atomic_write_verified, which writes afile to a temporary location, calls a verification function on it, and moves
it into place only if verification succeeds.
pikepdf.pdfa.saveuses it.qpdf limits
pikepdf.settings.get_qpdf_limitsand{func}
pikepdf.settings.set_qpdf_limits, which read and change qpdf'sprocess-wide limits for hardening against malicious or damaged PDFs: parser
nesting depth, error count and container size, the number of stream filters,
memory for decoding Flate, DCT, PNG, TIFF and RunLength data, and whether
corrupt JPEG data is an error. Previously only some of these limits were
reachable, through {meth}
pikepdf.JobBuilder.limits.set_qpdf_limitsreturns the previous values so they can be restored.
pikepdf.settings.disable_qpdf_default_limits, which liftsqpdf's optional default limits for the rest of the process, and
{func}
pikepdf.settings.qpdf_limit_errors, which counts how many times anylimit has been exceeded.
Behavior changes
12.4.1. Changes inherited from qpdf 12.4:
pikepdf.parse_content_stream,{meth}
pikepdf.Page.parse_contents) now stops after 15 syntax errors,issuing a warning. Instructions after that point are dropped, so parsing
and rewriting a badly damaged content stream can lose content. Use
pikepdf.settings.set_qpdf_limits(parser_max_errors=0)to parse as muchas possible.
{class}
pikepdf.PdfErrorwhen the pages are accessed./Rotatevalues outside[0, 360), such as-90, are now normalizedwhen a page is converted to a form XObject, overlaid or rotation-flattened.
prognamekeyword argument of {class}pikepdf.Jobis deprecated andignored, and passing it issues a
DeprecationWarning. It was passed toqpdf's
QPDFJob::initializeFromArgvas the name of an environment variable,not the program name, and qpdf 12.4 no longer uses it. The program name is
taken from the first item of
args, as it always was.PdfImagemetadata such as.width,.heightor.colorspacewhose value has the wrong PDF type (for examplea
/Widthwritten as a string or name) now raisesTypeError, with amessage naming the key and the value found, instead of
NotImplementedError: Metadata access for Width. The exception is also aNotImplementedError, so existing handlers keep working.pikepdf.Stringno longer compares equal tobytes:pikepdf.String('abc') == b'abc'is nowFalse. It stillcompares equal to the
strit decodes to. AStringcompared equal toboth a
strand abytesthat are unequal to each other, and so could nothash like both of them; for non-ASCII text it hashed like neither, so
{pikepdf.String('héllo'): 1}['héllo']raisedKeyError. AStringnowhashes like its
str. To compare the raw data, usebytes(s) == b'...'or{meth}
~pikepdf.Object.as_bytes.pikepdf.Nameno longer compares equal tobytes:pikepdf.Name('/Foo') == b'/Foo'is nowFalse. It still compares equal tothe
strof its UTF-8 bytes, soobj.Type == '/Page'works as before, andit now hashes like that
str, so{pikepdf.Name('/héllo'): 1}['/héllo']no longer raises
KeyError. As PDF 2.0 (ISO 32000-2, 7.3.5) requires,names are compared byte for byte, with no Unicode normalization. Use
bytes(name) == b'...'to compare the raw bytes.pikepdf.Realcombined with anint,Integer, orDecimal, or negated with unary-/+/abs(), now yields aDecimal(previously a
float, orTypeErrorforintoperands other than/).A
Realwith afloatoperand still yields afloat. Division of anIntegerorRealby zero now raisesZeroDivisionError, as for Pythonnumbers, instead of
ValueError.pikepdf.Matrixnow raisesTypeError, notValueError, for apikepdf.Objectthat is not a matrix or anObjectListwith a non-numeric element, matching what a native argument ofthe wrong type raises, so an
except TypeErroraroundMatrix(*operands)behaves the same in either conversion mode. Size errors (
must have 6 elements) remainValueError.bool()on apikepdf.Integerorpikepdf.Realisnow by value (
bool(pikepdf.Integer(0))isFalse), instead of raisingNotImplementedError: code is unreachable.~pikepdf.Object.as_dictand{meth}
~pikepdf.Object.as_listnow accept adefaultargument and raiseTypeErroron a type mismatch, instead of raisingpikepdf.PdfErrorwithno way to supply a default.
Pdfthey are inserted into, so
pdf.Root.X = 42followed bypdf.Root.get_raw('/X').is_owned_by(pdf)isTrue, matching objects parsedfrom a file. Scalars (
Name,String,Integer, ...) are adopted as a copy,so a handle held in a constant can still be inserted into several documents.
A
DictionaryorArrayis adopted in place and keeps its aliasing with thedocument; inserting the same container into a second
Pdfnow raisesForeignObjectError, as it already did for containers parsed from a file.Construct a new object, or use {meth}
pikepdf.Pdf.copy_foreign. Adoption isnot permanent: removing the object from the document -- deleting or
replacing the dictionary key or array element that held it, or destroying
the document -- releases the claim, so the object can then be inserted into
another
Pdf. If the same object was reachable under two keys, removingeither one releases it; its value is unaffected and still readable through
the remaining reference.
The direct children of an object produced by
{meth}
pikepdf.Pdf.copy_foreign, {meth}pikepdf.Object.with_same_owner_as,{meth}
pikepdf.Pdf.make_indirect, or by appending/inserting a page intoPdf.pages, and values inserted throughNameTree/NumberTree__setitem__, now report the destination document as their owner and followits
conversion_mode.pikepdf.Object.with_same_owner_asand{meth}
pikepdf.Pdf.make_indirectnow raiseForeignObjectErrorfor adirect object that already belongs to a different
Pdf, instead of silentlyretagging an object that the other document still references. Remove it from
that document first, or make it indirect there and use
{meth}
pikepdf.Pdf.copy_foreign.~pikepdf.Object.as_intwithcoerce=Truenowreturns a supplied default for a value that does not fit in a 64-bit PDF
integer, instead of raising
OverflowError. Called without a default itstill raises
OverflowError.repr()of apikepdf.Objectnow honors theeffective conversion mode of the object being displayed (context manager,
then its owning
Pdf, then the global setting), rather than only theglobal setting.
pikepdf.set_object_conversion_modenow raisesValueErrorfor a value other than'implicit'or'explicit', insteadof silently accepting it.
Performance
pikepdf.Pdf.savewrites directly to the file descriptor when savingto a filename or to a plain binary file object from {func}
open, instead ofcalling the stream's
write()method for every chunk of output. Saving a large document is about twice as fast. Other streams, suchas
BytesIO, pipes and subclasses of theioclasses, are written throughwrite()as before.isinstance()checks against {class}pikepdf.Dictionary,{class}
pikepdf.Stream, {class}pikepdf.Integerand the other objectclasses are about five times faster.
pikepdf.unboxis now implemented in C++ and is about 40 timesfaster. {func}
pikepdf.as_int, {func}pikepdf.as_floatand{func}
pikepdf.as_decimalanswer for a nativeintorDecimalwithoutconstructing a PDF object, and converting a Real to a
Decimalno longerimports the
decimalmodule each time.Fixes
pikepdf.models.metadata.decode_pdf_datenow accepts every PDF dateform the specification allows, in which all f
Configuration
📅 Schedule: (UTC)
🚦 Automerge: Enabled.
♻ Rebasing: Whenever PR is behind base branch, or you tick the rebase/retry checkbox.
🔕 Ignore: Close this PR and you won't be reminded about this update again.
This PR was generated by Mend Renovate. View the repository job log.