nwo
stringlengths
10
28
sha
stringlengths
40
40
path
stringlengths
11
97
identifier
stringlengths
1
64
parameters
stringlengths
2
2.24k
return_statement
stringlengths
0
2.17k
docstring
stringlengths
0
5.45k
docstring_summary
stringlengths
0
3.83k
func_begin
int64
1
13.4k
func_end
int64
2
13.4k
function
stringlengths
28
56.4k
url
stringlengths
106
209
project
int64
1
48
executed_lines
list
executed_lines_pc
float64
0
153
missing_lines
list
missing_lines_pc
float64
0
100
covered
bool
2 classes
filecoverage
float64
2.53
100
function_lines
int64
2
1.46k
mccabe
int64
1
253
coverage
float64
0
100
docstring_lines
int64
0
112
function_nodoc
stringlengths
9
56.4k
id
int64
0
29.8k
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getDocumentInfo
(self)
return self.metadata
.. deprecated:: 1.28.0 Use the attribute :py:attr:`metadata` instead.
.. deprecated:: 1.28.0
384
391
def getDocumentInfo(self) -> Optional[DocumentInformation]: # deprecated """ .. deprecated:: 1.28.0 Use the attribute :py:attr:`metadata` instead. """ deprecation_with_replacement("getDocumentInfo", "metadata", "3.0.0") return self.metadata
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L384-L391
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getDocumentInfo(self) -> Optional[DocumentInformation]: # deprecated deprecation_with_replacement("getDocumentInfo", "metadata", "3.0.0") return self.metadata
24,354
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.documentInfo
(self)
return self.metadata
.. deprecated:: 1.28.0 Use the attribute :py:attr:`metadata` instead.
.. deprecated:: 1.28.0
394
401
def documentInfo(self) -> Optional[DocumentInformation]: # deprecated """ .. deprecated:: 1.28.0 Use the attribute :py:attr:`metadata` instead. """ deprecation_with_replacement("documentInfo", "metadata", "3.0.0") return self.metadata
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L394-L401
39
[]
0
[]
0
false
91.582229
8
1
100
3
def documentInfo(self) -> Optional[DocumentInformation]: # deprecated deprecation_with_replacement("documentInfo", "metadata", "3.0.0") return self.metadata
24,355
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.xmp_metadata
(self)
XMP (Extensible Metadata Platform) data.
XMP (Extensible Metadata Platform) data.
404
410
def xmp_metadata(self) -> Optional[XmpInformation]: """XMP (Extensible Metadata Platform) data.""" try: self._override_encryption = True return self.trailer[TK.ROOT].xmp_metadata # type: ignore finally: self._override_encryption = False
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L404-L410
39
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
91.582229
7
1
100
1
def xmp_metadata(self) -> Optional[XmpInformation]: try: self._override_encryption = True return self.trailer[TK.ROOT].xmp_metadata # type: ignore finally: self._override_encryption = False
24,356
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getXmpMetadata
(self)
return self.xmp_metadata
.. deprecated:: 1.28.0 Use the attribute :py:attr:`xmp_metadata` instead.
.. deprecated:: 1.28.0
412
419
def getXmpMetadata(self) -> Optional[XmpInformation]: # deprecated """ .. deprecated:: 1.28.0 Use the attribute :py:attr:`xmp_metadata` instead. """ deprecation_with_replacement("getXmpMetadata", "xmp_metadata", "3.0.0") return self.xmp_metadata
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L412-L419
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getXmpMetadata(self) -> Optional[XmpInformation]: # deprecated deprecation_with_replacement("getXmpMetadata", "xmp_metadata", "3.0.0") return self.xmp_metadata
24,357
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.xmpMetadata
(self)
return self.xmp_metadata
.. deprecated:: 1.28.0 Use the attribute :py:attr:`xmp_metadata` instead.
.. deprecated:: 1.28.0
422
429
def xmpMetadata(self) -> Optional[XmpInformation]: # deprecated """ .. deprecated:: 1.28.0 Use the attribute :py:attr:`xmp_metadata` instead. """ deprecation_with_replacement("xmpMetadata", "xmp_metadata", "3.0.0") return self.xmp_metadata
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L422-L429
39
[]
0
[]
0
false
91.582229
8
1
100
3
def xmpMetadata(self) -> Optional[XmpInformation]: # deprecated deprecation_with_replacement("xmpMetadata", "xmp_metadata", "3.0.0") return self.xmp_metadata
24,358
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_num_pages
(self)
Calculate the number of pages in this PDF file. Args: Returns: The number of pages of the parsed PDF file Raises: PdfReadError: if file is encrypted and restrictions prevent this action.
Calculate the number of pages in this PDF file.
431
452
def _get_num_pages(self) -> int: """ Calculate the number of pages in this PDF file. Args: Returns: The number of pages of the parsed PDF file Raises: PdfReadError: if file is encrypted and restrictions prevent this action. """ # Flattened pages will not work on an Encrypted PDF; # the PDF file's page count is used in this case. Otherwise, # the original method (flattened page count) is used. if self.is_encrypted: return self.trailer[TK.ROOT]["/Pages"]["/Count"] # type: ignore else: if self.flattened_pages is None: self._flatten() return len(self.flattened_pages)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L431-L452
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
91.582229
22
3
100
10
def _get_num_pages(self) -> int: # Flattened pages will not work on an Encrypted PDF; # the PDF file's page count is used in this case. Otherwise, # the original method (flattened page count) is used. if self.is_encrypted: return self.trailer[TK.ROOT]["/Pages"]["/Count"] # type: ignore else: if self.flattened_pages is None: self._flatten() return len(self.flattened_pages)
24,359
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getNumPages
(self)
return self._get_num_pages()
.. deprecated:: 1.28.0 Use :code:`len(reader.pages)` instead.
.. deprecated:: 1.28.0
454
461
def getNumPages(self) -> int: # deprecated """ .. deprecated:: 1.28.0 Use :code:`len(reader.pages)` instead. """ deprecation_with_replacement("reader.getNumPages", "len(reader.pages)", "3.0.0") return self._get_num_pages()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L454-L461
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getNumPages(self) -> int: # deprecated deprecation_with_replacement("reader.getNumPages", "len(reader.pages)", "3.0.0") return self._get_num_pages()
24,360
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.numPages
(self)
return self._get_num_pages()
.. deprecated:: 1.28.0 Use :code:`len(reader.pages)` instead.
.. deprecated:: 1.28.0
464
471
def numPages(self) -> int: # deprecated """ .. deprecated:: 1.28.0 Use :code:`len(reader.pages)` instead. """ deprecation_with_replacement("reader.numPages", "len(reader.pages)", "3.0.0") return self._get_num_pages()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L464-L471
39
[]
0
[]
0
false
91.582229
8
1
100
3
def numPages(self) -> int: # deprecated deprecation_with_replacement("reader.numPages", "len(reader.pages)", "3.0.0") return self._get_num_pages()
24,361
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getPage
(self, pageNumber: int)
return self._get_page(pageNumber)
.. deprecated:: 1.28.0 Use :code:`reader.pages[page_number]` instead.
.. deprecated:: 1.28.0
473
482
def getPage(self, pageNumber: int) -> PageObject: # deprecated """ .. deprecated:: 1.28.0 Use :code:`reader.pages[page_number]` instead. """ deprecation_with_replacement( "reader.getPage(pageNumber)", "reader.pages[page_number]", "3.0.0" ) return self._get_page(pageNumber)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L473-L482
39
[]
0
[]
0
false
91.582229
10
1
100
3
def getPage(self, pageNumber: int) -> PageObject: # deprecated deprecation_with_replacement( "reader.getPage(pageNumber)", "reader.pages[page_number]", "3.0.0" ) return self._get_page(pageNumber)
24,362
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_page
(self, page_number: int)
return self.flattened_pages[page_number]
Retrieve a page by number from this PDF file. Args: page_number: The page number to retrieve (pages begin at zero) Returns: A :class:`PageObject<pypdf._page.PageObject>` instance.
Retrieve a page by number from this PDF file.
484
500
def _get_page(self, page_number: int) -> PageObject: """ Retrieve a page by number from this PDF file. Args: page_number: The page number to retrieve (pages begin at zero) Returns: A :class:`PageObject<pypdf._page.PageObject>` instance. """ # ensure that we're not trying to access an encrypted PDF # assert not self.trailer.has_key(TK.ENCRYPT) if self.flattened_pages is None: self._flatten() assert self.flattened_pages is not None, "hint for mypy" return self.flattened_pages[page_number]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L484-L500
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16 ]
100
[]
0
true
91.582229
17
3
100
8
def _get_page(self, page_number: int) -> PageObject: # ensure that we're not trying to access an encrypted PDF # assert not self.trailer.has_key(TK.ENCRYPT) if self.flattened_pages is None: self._flatten() assert self.flattened_pages is not None, "hint for mypy" return self.flattened_pages[page_number]
24,363
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.namedDestinations
(self)
return self.named_destinations
.. deprecated:: 1.28.0 Use :py:attr:`named_destinations` instead.
.. deprecated:: 1.28.0
503
510
def namedDestinations(self) -> Dict[str, Any]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`named_destinations` instead. """ deprecation_with_replacement("namedDestinations", "named_destinations", "3.0.0") return self.named_destinations
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L503-L510
39
[]
0
[]
0
false
91.582229
8
1
100
3
def namedDestinations(self) -> Dict[str, Any]: # deprecated deprecation_with_replacement("namedDestinations", "named_destinations", "3.0.0") return self.named_destinations
24,364
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.named_destinations
(self)
return self._get_named_destinations()
A read-only dictionary which maps names to :class:`Destinations<pypdf.generic.Destination>`
A read-only dictionary which maps names to :class:`Destinations<pypdf.generic.Destination>`
513
518
def named_destinations(self) -> Dict[str, Any]: """ A read-only dictionary which maps names to :class:`Destinations<pypdf.generic.Destination>` """ return self._get_named_destinations()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L513-L518
39
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
91.582229
6
1
100
2
def named_destinations(self) -> Dict[str, Any]: return self._get_named_destinations()
24,365
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.get_fields
( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, )
return retval
Extract field data if this PDF contains interactive form fields. The *tree* and *retval* parameters are for recursive use. Args: tree: retval: fileobj: A file object (usually a text file) to write a report to on all interactive form fields found. Returns: A dictionary where each key is a field name, and each value is a :class:`Field<pypdf.generic.Field>` object. By default, the mapping name is used for keys. ``None`` if form data could not be located.
Extract field data if this PDF contains interactive form fields.
523
572
def get_fields( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, ) -> Optional[Dict[str, Any]]: """ Extract field data if this PDF contains interactive form fields. The *tree* and *retval* parameters are for recursive use. Args: tree: retval: fileobj: A file object (usually a text file) to write a report to on all interactive form fields found. Returns: A dictionary where each key is a field name, and each value is a :class:`Field<pypdf.generic.Field>` object. By default, the mapping name is used for keys. ``None`` if form data could not be located. """ field_attributes = FieldDictionaryAttributes.attributes_dict() field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict()) if retval is None: retval = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the AcroForm tree if CD.ACRO_FORM in catalog: tree = cast(Optional[TreeObject], catalog[CD.ACRO_FORM]) else: return None if tree is None: return retval self._check_kids(tree, retval, fileobj) for attr in field_attributes: if attr in tree: # Tree is a field self._build_field(tree, retval, fileobj, field_attributes) break if "/Fields" in tree: fields = cast(ArrayObject, tree["/Fields"]) for f in fields: field = f.get_object() self._build_field(field, retval, fileobj, field_attributes) return retval
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L523-L572
39
[ 0, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49 ]
56
[]
0
false
91.582229
50
8
100
15
def get_fields( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, ) -> Optional[Dict[str, Any]]: field_attributes = FieldDictionaryAttributes.attributes_dict() field_attributes.update(CheckboxRadioButtonAttributes.attributes_dict()) if retval is None: retval = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the AcroForm tree if CD.ACRO_FORM in catalog: tree = cast(Optional[TreeObject], catalog[CD.ACRO_FORM]) else: return None if tree is None: return retval self._check_kids(tree, retval, fileobj) for attr in field_attributes: if attr in tree: # Tree is a field self._build_field(tree, retval, fileobj, field_attributes) break if "/Fields" in tree: fields = cast(ArrayObject, tree["/Fields"]) for f in fields: field = f.get_object() self._build_field(field, retval, fileobj, field_attributes) return retval
24,366
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getFields
( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, )
return self.get_fields(tree, retval, fileobj)
.. deprecated:: 1.28.0 Use :meth:`get_fields` instead.
.. deprecated:: 1.28.0
574
586
def getFields( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, ) -> Optional[Dict[str, Any]]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`get_fields` instead. """ deprecation_with_replacement("getFields", "get_fields", "3.0.0") return self.get_fields(tree, retval, fileobj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L574-L586
39
[]
0
[]
0
false
91.582229
13
1
100
3
def getFields( self, tree: Optional[TreeObject] = None, retval: Optional[Dict[Any, Any]] = None, fileobj: Optional[Any] = None, ) -> Optional[Dict[str, Any]]: # deprecated deprecation_with_replacement("getFields", "get_fields", "3.0.0") return self.get_fields(tree, retval, fileobj)
24,367
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_qualified_field_name
(self, parent: DictionaryObject)
588
600
def _get_qualified_field_name(self, parent: DictionaryObject) -> str: if "/TM" in parent: return cast(str, parent["/TM"]) elif "/Parent" in parent: return ( self._get_qualified_field_name( cast(DictionaryObject, parent["/Parent"]) ) + "." + cast(str, parent["/T"]) ) else: return cast(str, parent["/T"])
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L588-L600
39
[ 0, 1, 3, 12 ]
30.769231
[ 2, 4 ]
15.384615
false
91.582229
13
3
84.615385
0
def _get_qualified_field_name(self, parent: DictionaryObject) -> str: if "/TM" in parent: return cast(str, parent["/TM"]) elif "/Parent" in parent: return ( self._get_qualified_field_name( cast(DictionaryObject, parent["/Parent"]) ) + "." + cast(str, parent["/T"]) ) else: return cast(str, parent["/T"])
24,368
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._build_field
( self, field: Union[TreeObject, DictionaryObject], retval: Dict[Any, Any], fileobj: Any, field_attributes: Any, )
602
630
def _build_field( self, field: Union[TreeObject, DictionaryObject], retval: Dict[Any, Any], fileobj: Any, field_attributes: Any, ) -> None: self._check_kids(field, retval, fileobj) try: key = cast(str, field["/TM"]) except KeyError: try: if "/Parent" in field: key = ( self._get_qualified_field_name( cast(DictionaryObject, field["/Parent"]) ) + "." ) else: key = "" key += cast(str, field["/T"]) except KeyError: # Ignore no-name field for now return if fileobj: self._write_field(fileobj, field, field_attributes) fileobj.write("\n") retval[key] = Field(field)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L602-L630
39
[ 0, 7, 8, 9, 10, 11, 12, 13, 20, 21, 22, 23, 24, 25, 26, 27, 28 ]
58.62069
[]
0
false
91.582229
29
5
100
0
def _build_field( self, field: Union[TreeObject, DictionaryObject], retval: Dict[Any, Any], fileobj: Any, field_attributes: Any, ) -> None: self._check_kids(field, retval, fileobj) try: key = cast(str, field["/TM"]) except KeyError: try: if "/Parent" in field: key = ( self._get_qualified_field_name( cast(DictionaryObject, field["/Parent"]) ) + "." ) else: key = "" key += cast(str, field["/T"]) except KeyError: # Ignore no-name field for now return if fileobj: self._write_field(fileobj, field, field_attributes) fileobj.write("\n") retval[key] = Field(field)
24,369
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._check_kids
( self, tree: Union[TreeObject, DictionaryObject], retval: Any, fileobj: Any )
632
638
def _check_kids( self, tree: Union[TreeObject, DictionaryObject], retval: Any, fileobj: Any ) -> None: if PA.KIDS in tree: # recurse down the tree for kid in tree[PA.KIDS]: # type: ignore self.get_fields(kid.get_object(), retval, fileobj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L632-L638
39
[ 0, 3, 4, 5, 6 ]
71.428571
[]
0
false
91.582229
7
3
100
0
def _check_kids( self, tree: Union[TreeObject, DictionaryObject], retval: Any, fileobj: Any ) -> None: if PA.KIDS in tree: # recurse down the tree for kid in tree[PA.KIDS]: # type: ignore self.get_fields(kid.get_object(), retval, fileobj)
24,370
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._write_field
(self, fileobj: Any, field: Any, field_attributes: Any)
640
675
def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None: field_attributes_tuple = FieldDictionaryAttributes.attributes() field_attributes_tuple = ( field_attributes_tuple + CheckboxRadioButtonAttributes.attributes() ) for attr in field_attributes_tuple: if attr in ( FieldDictionaryAttributes.Kids, FieldDictionaryAttributes.AA, ): continue attr_name = field_attributes[attr] try: if attr == FieldDictionaryAttributes.FT: # Make the field type value more clear types = { "/Btn": "Button", "/Tx": "Text", "/Ch": "Choice", "/Sig": "Signature", } if field[attr] in types: fileobj.write(f"{attr_name}: {types[field[attr]]}\n") elif attr == FieldDictionaryAttributes.Parent: # Let's just write the name of the parent try: name = field[attr][FieldDictionaryAttributes.TM] except KeyError: name = field[attr][FieldDictionaryAttributes.T] fileobj.write(f"{attr_name}: {name}\n") else: fileobj.write(f"{attr_name}: {field[attr]}\n") except KeyError: # Field attribute is N/A or unknown, so don't write anything pass
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L640-L675
39
[ 0, 1, 2, 5, 6, 7, 11, 12, 13, 14, 15, 16, 22, 23, 24, 25, 26, 27, 28, 29, 30, 32, 33, 34, 35 ]
69.444444
[]
0
false
91.582229
36
8
100
0
def _write_field(self, fileobj: Any, field: Any, field_attributes: Any) -> None: field_attributes_tuple = FieldDictionaryAttributes.attributes() field_attributes_tuple = ( field_attributes_tuple + CheckboxRadioButtonAttributes.attributes() ) for attr in field_attributes_tuple: if attr in ( FieldDictionaryAttributes.Kids, FieldDictionaryAttributes.AA, ): continue attr_name = field_attributes[attr] try: if attr == FieldDictionaryAttributes.FT: # Make the field type value more clear types = { "/Btn": "Button", "/Tx": "Text", "/Ch": "Choice", "/Sig": "Signature", } if field[attr] in types: fileobj.write(f"{attr_name}: {types[field[attr]]}\n") elif attr == FieldDictionaryAttributes.Parent: # Let's just write the name of the parent try: name = field[attr][FieldDictionaryAttributes.TM] except KeyError: name = field[attr][FieldDictionaryAttributes.T] fileobj.write(f"{attr_name}: {name}\n") else: fileobj.write(f"{attr_name}: {field[attr]}\n") except KeyError: # Field attribute is N/A or unknown, so don't write anything pass
24,371
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.get_form_text_fields
(self, full_qualified_name: bool = False)
return ff
Retrieve form fields from the document with textual data. The key is the name of the form field, the value is the content of the field. If the document contains multiple form fields with the same name, the second and following will get the suffix .2, .3, ... full_qualified_name should be used to get full name
Retrieve form fields from the document with textual data.
677
718
def get_form_text_fields(self, full_qualified_name: bool = False) -> Dict[str, Any]: """ Retrieve form fields from the document with textual data. The key is the name of the form field, the value is the content of the field. If the document contains multiple form fields with the same name, the second and following will get the suffix .2, .3, ... full_qualified_name should be used to get full name """ def indexed_key(k: str, fields: dict) -> str: if k not in fields: return k else: return ( k + "." + str(sum([1 for kk in fields if kk.startswith(k + ".")]) + 2) ) # Retrieve document form fields formfields = self.get_fields() if formfields is None: return {} ff = {} for field, value in formfields.items(): if value.get("/FT") == "/Tx": if full_qualified_name: ff[field] = value.get("/V") else: ff[indexed_key(cast(str, value["/T"]), ff)] = value.get("/V") return ff """return { (field if full_qualified_name else formfields[field]["/T"]): formfields[ field ].get("/V") for field in formfields if formfields[field].get("/FT") == "/Tx" }"""
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L677-L718
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41 ]
100
[]
0
true
91.582229
42
8
100
9
def get_form_text_fields(self, full_qualified_name: bool = False) -> Dict[str, Any]: def indexed_key(k: str, fields: dict) -> str: if k not in fields: return k else: return ( k + "." + str(sum([1 for kk in fields if kk.startswith(k + ".")]) + 2) ) # Retrieve document form fields formfields = self.get_fields() if formfields is None: return {} ff = {} for field, value in formfields.items(): if value.get("/FT") == "/Tx": if full_qualified_name: ff[field] = value.get("/V") else: ff[indexed_key(cast(str, value["/T"]), ff)] = value.get("/V") return ff
24,372
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getFormTextFields
(self)
return self.get_form_text_fields()
.. deprecated:: 1.28.0 Use :meth:`get_form_text_fields` instead.
.. deprecated:: 1.28.0
720
729
def getFormTextFields(self) -> Dict[str, Any]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`get_form_text_fields` instead. """ deprecation_with_replacement( "getFormTextFields", "get_form_text_fields", "3.0.0" ) return self.get_form_text_fields()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L720-L729
39
[]
0
[]
0
false
91.582229
10
1
100
3
def getFormTextFields(self) -> Dict[str, Any]: # deprecated deprecation_with_replacement( "getFormTextFields", "get_form_text_fields", "3.0.0" ) return self.get_form_text_fields()
24,373
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_named_destinations
( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, )
return retval
Retrieve the named destinations present in the document. Args: tree: retval: Returns: A dictionary which maps names to :class:`Destinations<pypdf.generic.Destination>`.
Retrieve the named destinations present in the document.
731
783
def _get_named_destinations( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, ) -> Dict[str, Any]: """ Retrieve the named destinations present in the document. Args: tree: retval: Returns: A dictionary which maps names to :class:`Destinations<pypdf.generic.Destination>`. """ if retval is None: retval = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the name tree if CA.DESTS in catalog: tree = cast(TreeObject, catalog[CA.DESTS]) elif CA.NAMES in catalog: names = cast(DictionaryObject, catalog[CA.NAMES]) if CA.DESTS in names: tree = cast(TreeObject, names[CA.DESTS]) if tree is None: return retval if PA.KIDS in tree: # recurse down the tree for kid in cast(ArrayObject, tree[PA.KIDS]): self._get_named_destinations(kid.get_object(), retval) # TABLE 3.33 Entries in a name tree node dictionary (PDF 1.7 specs) elif CA.NAMES in tree: # KIDS and NAMES are exclusives (PDF 1.7 specs p 162) names = cast(DictionaryObject, tree[CA.NAMES]) for i in range(0, len(names), 2): key = cast(str, names[i].get_object()) value = names[i + 1].get_object() if isinstance(value, DictionaryObject) and "/D" in value: value = value["/D"] dest = self._build_destination(key, value) # type: ignore if dest is not None: retval[key] = dest else: # case where Dests is in root catalog (PDF 1.7 specs, §2 about PDF1.1 for k__, v__ in tree.items(): val = v__.get_object() dest = self._build_destination(k__, val) if dest is not None: retval[k__] = dest return retval
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L731-L783
39
[ 0, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52 ]
73.584906
[]
0
false
91.582229
53
15
100
9
def _get_named_destinations( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, ) -> Dict[str, Any]: if retval is None: retval = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the name tree if CA.DESTS in catalog: tree = cast(TreeObject, catalog[CA.DESTS]) elif CA.NAMES in catalog: names = cast(DictionaryObject, catalog[CA.NAMES]) if CA.DESTS in names: tree = cast(TreeObject, names[CA.DESTS]) if tree is None: return retval if PA.KIDS in tree: # recurse down the tree for kid in cast(ArrayObject, tree[PA.KIDS]): self._get_named_destinations(kid.get_object(), retval) # TABLE 3.33 Entries in a name tree node dictionary (PDF 1.7 specs) elif CA.NAMES in tree: # KIDS and NAMES are exclusives (PDF 1.7 specs p 162) names = cast(DictionaryObject, tree[CA.NAMES]) for i in range(0, len(names), 2): key = cast(str, names[i].get_object()) value = names[i + 1].get_object() if isinstance(value, DictionaryObject) and "/D" in value: value = value["/D"] dest = self._build_destination(key, value) # type: ignore if dest is not None: retval[key] = dest else: # case where Dests is in root catalog (PDF 1.7 specs, §2 about PDF1.1 for k__, v__ in tree.items(): val = v__.get_object() dest = self._build_destination(k__, val) if dest is not None: retval[k__] = dest return retval
24,374
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getNamedDestinations
( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, )
return self._get_named_destinations(tree, retval)
.. deprecated:: 1.28.0 Use :py:attr:`named_destinations` instead.
.. deprecated:: 1.28.0
785
798
def getNamedDestinations( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, ) -> Dict[str, Any]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`named_destinations` instead. """ deprecation_with_replacement( "getNamedDestinations", "named_destinations", "3.0.0" ) return self._get_named_destinations(tree, retval)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L785-L798
39
[]
0
[]
0
false
91.582229
14
1
100
3
def getNamedDestinations( self, tree: Union[TreeObject, None] = None, retval: Optional[Any] = None, ) -> Dict[str, Any]: # deprecated deprecation_with_replacement( "getNamedDestinations", "named_destinations", "3.0.0" ) return self._get_named_destinations(tree, retval)
24,375
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.outline
(self)
return self._get_outline()
Read-only property for the outline (i.e., a collection of 'outline items' which are also known as 'bookmarks') present in the document.
Read-only property for the outline (i.e., a collection of 'outline items' which are also known as 'bookmarks') present in the document.
801
806
def outline(self) -> OutlineType: """ Read-only property for the outline (i.e., a collection of 'outline items' which are also known as 'bookmarks') present in the document. """ return self._get_outline()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L801-L806
39
[ 0, 1, 2, 3, 4, 5 ]
100
[]
0
true
91.582229
6
1
100
2
def outline(self) -> OutlineType: return self._get_outline()
24,376
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.outlines
(self)
return self.outline
.. deprecated:: 2.9.0 Use :py:attr:`outline` instead.
.. deprecated:: 2.9.0
809
816
def outlines(self) -> OutlineType: # deprecated """ .. deprecated:: 2.9.0 Use :py:attr:`outline` instead. """ deprecation_with_replacement("outlines", "outline", "3.0.0") return self.outline
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L809-L816
39
[]
0
[]
0
false
91.582229
8
1
100
3
def outlines(self) -> OutlineType: # deprecated deprecation_with_replacement("outlines", "outline", "3.0.0") return self.outline
24,377
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_outline
( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None )
return outline
818
857
def _get_outline( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None ) -> OutlineType: if outline is None: outline = [] catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the outline dictionary and named destinations if CO.OUTLINES in catalog: lines = cast(DictionaryObject, catalog[CO.OUTLINES]) if isinstance(lines, NullObject): return outline # TABLE 8.3 Entries in the outline dictionary if lines is not None and "/First" in lines: node = cast(DictionaryObject, lines["/First"]) self._namedDests = self._get_named_destinations() if node is None: return outline # see if there are any more outline items while True: outline_obj = self._build_outline_item(node) if outline_obj: outline.append(outline_obj) # check for sub-outline if "/First" in node: sub_outline: List[Any] = [] self._get_outline(cast(DictionaryObject, node["/First"]), sub_outline) if sub_outline: outline.append(sub_outline) if "/Next" not in node: break node = cast(DictionaryObject, node["/Next"]) return outline
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L818-L857
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ]
90
[ 12 ]
2.5
false
91.582229
40
12
97.5
0
def _get_outline( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None ) -> OutlineType: if outline is None: outline = [] catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) # get the outline dictionary and named destinations if CO.OUTLINES in catalog: lines = cast(DictionaryObject, catalog[CO.OUTLINES]) if isinstance(lines, NullObject): return outline # TABLE 8.3 Entries in the outline dictionary if lines is not None and "/First" in lines: node = cast(DictionaryObject, lines["/First"]) self._namedDests = self._get_named_destinations() if node is None: return outline # see if there are any more outline items while True: outline_obj = self._build_outline_item(node) if outline_obj: outline.append(outline_obj) # check for sub-outline if "/First" in node: sub_outline: List[Any] = [] self._get_outline(cast(DictionaryObject, node["/First"]), sub_outline) if sub_outline: outline.append(sub_outline) if "/Next" not in node: break node = cast(DictionaryObject, node["/Next"]) return outline
24,378
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getOutlines
( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None )
return self._get_outline(node, outline)
.. deprecated:: 1.28.0 Use :py:attr:`outline` instead.
.. deprecated:: 1.28.0
859
868
def getOutlines( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None ) -> OutlineType: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`outline` instead. """ deprecation_with_replacement("getOutlines", "outline", "3.0.0") return self._get_outline(node, outline)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L859-L868
39
[]
0
[]
0
false
91.582229
10
1
100
3
def getOutlines( self, node: Optional[DictionaryObject] = None, outline: Optional[Any] = None ) -> OutlineType: # deprecated deprecation_with_replacement("getOutlines", "outline", "3.0.0") return self._get_outline(node, outline)
24,379
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.threads
(self)
Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec. It's an array of dictionaries with "/F" and "/I" properties or None if there are no articles.
Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec. It's an array of dictionaries with "/F" and "/I" properties or None if there are no articles.
871
881
def threads(self) -> Optional[ArrayObject]: """ Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec. It's an array of dictionaries with "/F" and "/I" properties or None if there are no articles. """ catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) if CO.THREADS in catalog: return cast("ArrayObject", catalog[CO.THREADS]) else: return None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L871-L881
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
91.582229
11
2
100
3
def threads(self) -> Optional[ArrayObject]: catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) if CO.THREADS in catalog: return cast("ArrayObject", catalog[CO.THREADS]) else: return None
24,380
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_page_number_by_indirect
( self, indirect_reference: Union[None, int, NullObject, IndirectObject] )
return ret
Generate _page_id2num Args: indirect_reference: Returns: The page number.
Generate _page_id2num
883
907
def _get_page_number_by_indirect( self, indirect_reference: Union[None, int, NullObject, IndirectObject] ) -> int: """Generate _page_id2num Args: indirect_reference: Returns: The page number. """ if self._page_id2num is None: self._page_id2num = { x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore } if indirect_reference is None or isinstance(indirect_reference, NullObject): return -1 if isinstance(indirect_reference, int): idnum = indirect_reference else: idnum = indirect_reference.idnum assert self._page_id2num is not None, "hint for mypy" ret = self._page_id2num.get(idnum, -1) return ret
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L883-L907
39
[ 0, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24 ]
64
[]
0
false
91.582229
25
6
100
7
def _get_page_number_by_indirect( self, indirect_reference: Union[None, int, NullObject, IndirectObject] ) -> int: if self._page_id2num is None: self._page_id2num = { x.indirect_reference.idnum: i for i, x in enumerate(self.pages) # type: ignore } if indirect_reference is None or isinstance(indirect_reference, NullObject): return -1 if isinstance(indirect_reference, int): idnum = indirect_reference else: idnum = indirect_reference.idnum assert self._page_id2num is not None, "hint for mypy" ret = self._page_id2num.get(idnum, -1) return ret
24,381
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.get_page_number
(self, page: PageObject)
return self._get_page_number_by_indirect(page.indirect_reference)
Retrieve page number of a given PageObject Args: page: The page to get page number. Should be an instance of :class:`PageObject<pypdf._page.PageObject>` Returns: The page number or -1 if page is not found
Retrieve page number of a given PageObject
909
920
def get_page_number(self, page: PageObject) -> int: """ Retrieve page number of a given PageObject Args: page: The page to get page number. Should be an instance of :class:`PageObject<pypdf._page.PageObject>` Returns: The page number or -1 if page is not found """ return self._get_page_number_by_indirect(page.indirect_reference)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L909-L920
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
91.582229
12
1
100
8
def get_page_number(self, page: PageObject) -> int: return self._get_page_number_by_indirect(page.indirect_reference)
24,382
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getPageNumber
(self, page: PageObject)
return self.get_page_number(page)
.. deprecated:: 1.28.0 Use :meth:`get_page_number` instead.
.. deprecated:: 1.28.0
922
929
def getPageNumber(self, page: PageObject) -> int: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`get_page_number` instead. """ deprecation_with_replacement("getPageNumber", "get_page_number", "3.0.0") return self.get_page_number(page)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L922-L929
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getPageNumber(self, page: PageObject) -> int: # deprecated deprecation_with_replacement("getPageNumber", "get_page_number", "3.0.0") return self.get_page_number(page)
24,383
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.get_destination_page_number
(self, destination: Destination)
return self._get_page_number_by_indirect(destination.page)
Retrieve page number of a given Destination object. Args: destination: The destination to get page number. Returns: The page number or -1 if page is not found
Retrieve page number of a given Destination object.
931
941
def get_destination_page_number(self, destination: Destination) -> int: """ Retrieve page number of a given Destination object. Args: destination: The destination to get page number. Returns: The page number or -1 if page is not found """ return self._get_page_number_by_indirect(destination.page)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L931-L941
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
100
[]
0
true
91.582229
11
1
100
7
def get_destination_page_number(self, destination: Destination) -> int: return self._get_page_number_by_indirect(destination.page)
24,384
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getDestinationPageNumber
(self, destination: Destination)
return self.get_destination_page_number(destination)
.. deprecated:: 1.28.0 Use :meth:`get_destination_page_number` instead.
.. deprecated:: 1.28.0
943
952
def getDestinationPageNumber(self, destination: Destination) -> int: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`get_destination_page_number` instead. """ deprecation_with_replacement( "getDestinationPageNumber", "get_destination_page_number", "3.0.0" ) return self.get_destination_page_number(destination)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L943-L952
39
[]
0
[]
0
false
91.582229
10
1
100
3
def getDestinationPageNumber(self, destination: Destination) -> int: # deprecated deprecation_with_replacement( "getDestinationPageNumber", "get_destination_page_number", "3.0.0" ) return self.get_destination_page_number(destination)
24,385
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._build_destination
( self, title: str, array: Optional[ List[ Union[NumberObject, IndirectObject, None, NullObject, DictionaryObject] ] ], )
954
985
def _build_destination( self, title: str, array: Optional[ List[ Union[NumberObject, IndirectObject, None, NullObject, DictionaryObject] ] ], ) -> Destination: page, typ = None, None # handle outline items with missing or invalid destination if ( isinstance(array, (NullObject, str)) or (isinstance(array, ArrayObject) and len(array) == 0) or array is None ): page = NullObject() return Destination(title, page, Fit.fit()) else: page, typ = array[0:2] # type: ignore array = array[2:] try: return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore except PdfReadError: logger_warning(f"Unknown destination: {title} {array}", __name__) if self.strict: raise # create a link to first Page tmp = self.pages[0].indirect_reference indirect_reference = NullObject() if tmp is None else tmp return Destination(title, indirect_reference, Fit.fit())
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L954-L985
39
[ 0, 9, 10, 11, 16, 17, 18, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]
59.375
[]
0
false
91.582229
32
7
100
0
def _build_destination( self, title: str, array: Optional[ List[ Union[NumberObject, IndirectObject, None, NullObject, DictionaryObject] ] ], ) -> Destination: page, typ = None, None # handle outline items with missing or invalid destination if ( isinstance(array, (NullObject, str)) or (isinstance(array, ArrayObject) and len(array) == 0) or array is None ): page = NullObject() return Destination(title, page, Fit.fit()) else: page, typ = array[0:2] # type: ignore array = array[2:] try: return Destination(title, page, Fit(fit_type=typ, fit_args=array)) # type: ignore except PdfReadError: logger_warning(f"Unknown destination: {title} {array}", __name__) if self.strict: raise # create a link to first Page tmp = self.pages[0].indirect_reference indirect_reference = NullObject() if tmp is None else tmp return Destination(title, indirect_reference, Fit.fit())
24,386
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._build_outline_item
(self, node: DictionaryObject)
return outline_item
987
1,052
def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]: dest, title, outline_item = None, None, None # title required for valid outline # PDF Reference 1.7: TABLE 8.4 Entries in an outline item dictionary try: title = cast("str", node["/Title"]) except KeyError: if self.strict: raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}") title = "" # type: ignore if "/A" in node: # Action, PDFv1.7 Section 12.6 (only type GoTo supported) action = cast(DictionaryObject, node["/A"]) action_type = cast(NameObject, action[GoToActionArguments.S]) if action_type == "/GoTo": dest = action[GoToActionArguments.D] elif "/Dest" in node: # Destination, PDFv1.7 Section 12.3.2 dest = node["/Dest"] # if array was referenced in another object, will be a dict w/ key "/D" if isinstance(dest, DictionaryObject) and "/D" in dest: dest = dest["/D"] if isinstance(dest, ArrayObject): outline_item = self._build_destination(title, dest) elif isinstance(dest, str): # named destination, addresses NameObject Issue #193 # TODO : keep named destination instead of replacing it ? try: outline_item = self._build_destination( title, self._namedDests[dest].dest_array ) except KeyError: # named destination not found in Name Dict outline_item = self._build_destination(title, None) elif dest is None: # outline item not required to have destination or action # PDFv1.7 Table 153 outline_item = self._build_destination(title, dest) else: if self.strict: raise PdfReadError(f"Unexpected destination {dest!r}") else: logger_warning( f"Removed unexpected destination {dest!r} from destination", __name__, ) outline_item = self._build_destination(title, None) # type: ignore # if outline item created, add color, format, and child count if present if outline_item: if "/C" in node: # Color of outline item font in (R, G, B) with values ranging 0.0-1.0 outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in node["/C"]) # type: ignore if "/F" in node: # specifies style characteristics bold and/or italic # 1=italic, 2=bold, 3=both outline_item[NameObject("/F")] = node["/F"] if "/Count" in node: # absolute value = num. visible children # positive = open/unfolded, negative = closed/folded outline_item[NameObject("/Count")] = node["/Count"] outline_item.node = node return outline_item
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L987-L1052
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 34, 35, 36, 37, 38, 39, 40, 42, 43, 45, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65 ]
89.393939
[]
0
false
91.582229
66
17
100
0
def _build_outline_item(self, node: DictionaryObject) -> Optional[Destination]: dest, title, outline_item = None, None, None # title required for valid outline # PDF Reference 1.7: TABLE 8.4 Entries in an outline item dictionary try: title = cast("str", node["/Title"]) except KeyError: if self.strict: raise PdfReadError(f"Outline Entry Missing /Title attribute: {node!r}") title = "" # type: ignore if "/A" in node: # Action, PDFv1.7 Section 12.6 (only type GoTo supported) action = cast(DictionaryObject, node["/A"]) action_type = cast(NameObject, action[GoToActionArguments.S]) if action_type == "/GoTo": dest = action[GoToActionArguments.D] elif "/Dest" in node: # Destination, PDFv1.7 Section 12.3.2 dest = node["/Dest"] # if array was referenced in another object, will be a dict w/ key "/D" if isinstance(dest, DictionaryObject) and "/D" in dest: dest = dest["/D"] if isinstance(dest, ArrayObject): outline_item = self._build_destination(title, dest) elif isinstance(dest, str): # named destination, addresses NameObject Issue #193 # TODO : keep named destination instead of replacing it ? try: outline_item = self._build_destination( title, self._namedDests[dest].dest_array ) except KeyError: # named destination not found in Name Dict outline_item = self._build_destination(title, None) elif dest is None: # outline item not required to have destination or action # PDFv1.7 Table 153 outline_item = self._build_destination(title, dest) else: if self.strict: raise PdfReadError(f"Unexpected destination {dest!r}") else: logger_warning( f"Removed unexpected destination {dest!r} from destination", __name__, ) outline_item = self._build_destination(title, None) # type: ignore # if outline item created, add color, format, and child count if present if outline_item: if "/C" in node: # Color of outline item font in (R, G, B) with values ranging 0.0-1.0 outline_item[NameObject("/C")] = ArrayObject(FloatObject(c) for c in node["/C"]) # type: ignore if "/F" in node: # specifies style characteristics bold and/or italic # 1=italic, 2=bold, 3=both outline_item[NameObject("/F")] = node["/F"] if "/Count" in node: # absolute value = num. visible children # positive = open/unfolded, negative = closed/folded outline_item[NameObject("/Count")] = node["/Count"] outline_item.node = node return outline_item
24,387
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.pages
(self)
return _VirtualList(self._get_num_pages, self._get_page)
Read-only property that emulates a list of :py:class:`Page<pypdf._page.Page>` objects.
Read-only property that emulates a list of :py:class:`Page<pypdf._page.Page>` objects.
1,055
1,057
def pages(self) -> List[PageObject]: """Read-only property that emulates a list of :py:class:`Page<pypdf._page.Page>` objects.""" return _VirtualList(self._get_num_pages, self._get_page)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1055-L1057
39
[ 0, 1, 2 ]
100
[]
0
true
91.582229
3
1
100
1
def pages(self) -> List[PageObject]: return _VirtualList(self._get_num_pages, self._get_page)
24,388
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.page_labels
(self)
return [page_index2page_label(self, i) for i in range(len(self.pages))]
A list of labels for the pages in this document. This property is read-only. The labels are in the order that the pages appear in the document.
A list of labels for the pages in this document.
1,060
1,067
def page_labels(self) -> List[str]: """ A list of labels for the pages in this document. This property is read-only. The labels are in the order that the pages appear in the document. """ return [page_index2page_label(self, i) for i in range(len(self.pages))]
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1060-L1067
39
[ 0, 1, 2, 3, 4, 5, 6 ]
87.5
[ 7 ]
12.5
false
91.582229
8
2
87.5
4
def page_labels(self) -> List[str]: return [page_index2page_label(self, i) for i in range(len(self.pages))]
24,389
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.page_layout
(self)
return None
Get the page layout currently being used. .. list-table:: Valid ``layout`` values :widths: 50 200 * - /NoLayout - Layout explicitly not specified * - /SinglePage - Show one page at a time * - /OneColumn - Show one column at a time * - /TwoColumnLeft - Show pages in two columns, odd-numbered pages on the left * - /TwoColumnRight - Show pages in two columns, odd-numbered pages on the right * - /TwoPageLeft - Show two pages at a time, odd-numbered pages on the left * - /TwoPageRight - Show two pages at a time, odd-numbered pages on the right
Get the page layout currently being used.
1,070
1,095
def page_layout(self) -> Optional[str]: """ Get the page layout currently being used. .. list-table:: Valid ``layout`` values :widths: 50 200 * - /NoLayout - Layout explicitly not specified * - /SinglePage - Show one page at a time * - /OneColumn - Show one column at a time * - /TwoColumnLeft - Show pages in two columns, odd-numbered pages on the left * - /TwoColumnRight - Show pages in two columns, odd-numbered pages on the right * - /TwoPageLeft - Show two pages at a time, odd-numbered pages on the left * - /TwoPageRight - Show two pages at a time, odd-numbered pages on the right """ trailer = cast(DictionaryObject, self.trailer[TK.ROOT]) if CD.PAGE_LAYOUT in trailer: return cast(NameObject, trailer[CD.PAGE_LAYOUT]) return None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1070-L1095
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
100
[]
0
true
91.582229
26
2
100
19
def page_layout(self) -> Optional[str]: trailer = cast(DictionaryObject, self.trailer[TK.ROOT]) if CD.PAGE_LAYOUT in trailer: return cast(NameObject, trailer[CD.PAGE_LAYOUT]) return None
24,390
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getPageLayout
(self)
return self.page_layout
.. deprecated:: 1.28.0 Use :py:attr:`page_layout` instead.
.. deprecated:: 1.28.0
1,097
1,104
def getPageLayout(self) -> Optional[str]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`page_layout` instead. """ deprecation_with_replacement("getPageLayout", "page_layout", "3.0.0") return self.page_layout
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1097-L1104
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getPageLayout(self) -> Optional[str]: # deprecated deprecation_with_replacement("getPageLayout", "page_layout", "3.0.0") return self.page_layout
24,391
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.pageLayout
(self)
return self.page_layout
.. deprecated:: 1.28.0 Use :py:attr:`page_layout` instead.
.. deprecated:: 1.28.0
1,107
1,114
def pageLayout(self) -> Optional[str]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`page_layout` instead. """ deprecation_with_replacement("pageLayout", "page_layout", "3.0.0") return self.page_layout
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1107-L1114
39
[]
0
[]
0
false
91.582229
8
1
100
3
def pageLayout(self) -> Optional[str]: # deprecated deprecation_with_replacement("pageLayout", "page_layout", "3.0.0") return self.page_layout
24,392
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.page_mode
(self)
Get the page mode currently being used. .. list-table:: Valid ``mode`` values :widths: 50 200 * - /UseNone - Do not show outline or thumbnails panels * - /UseOutlines - Show outline (aka bookmarks) panel * - /UseThumbs - Show page thumbnails panel * - /FullScreen - Fullscreen view * - /UseOC - Show Optional Content Group (OCG) panel * - /UseAttachments - Show attachments panel
Get the page mode currently being used.
1,117
1,140
def page_mode(self) -> Optional[PagemodeType]: """ Get the page mode currently being used. .. list-table:: Valid ``mode`` values :widths: 50 200 * - /UseNone - Do not show outline or thumbnails panels * - /UseOutlines - Show outline (aka bookmarks) panel * - /UseThumbs - Show page thumbnails panel * - /FullScreen - Fullscreen view * - /UseOC - Show Optional Content Group (OCG) panel * - /UseAttachments - Show attachments panel """ try: return self.trailer[TK.ROOT]["/PageMode"] # type: ignore except KeyError: return None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1117-L1140
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
100
[]
0
true
91.582229
24
2
100
17
def page_mode(self) -> Optional[PagemodeType]: try: return self.trailer[TK.ROOT]["/PageMode"] # type: ignore except KeyError: return None
24,393
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getPageMode
(self)
return self.page_mode
.. deprecated:: 1.28.0 Use :py:attr:`page_mode` instead.
.. deprecated:: 1.28.0
1,142
1,149
def getPageMode(self) -> Optional[PagemodeType]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`page_mode` instead. """ deprecation_with_replacement("getPageMode", "page_mode", "3.0.0") return self.page_mode
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1142-L1149
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getPageMode(self) -> Optional[PagemodeType]: # deprecated deprecation_with_replacement("getPageMode", "page_mode", "3.0.0") return self.page_mode
24,394
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.pageMode
(self)
return self.page_mode
.. deprecated:: 1.28.0 Use :py:attr:`page_mode` instead.
.. deprecated:: 1.28.0
1,152
1,159
def pageMode(self) -> Optional[PagemodeType]: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`page_mode` instead. """ deprecation_with_replacement("pageMode", "page_mode", "3.0.0") return self.page_mode
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1152-L1159
39
[]
0
[]
0
false
91.582229
8
1
100
3
def pageMode(self) -> Optional[PagemodeType]: # deprecated deprecation_with_replacement("pageMode", "page_mode", "3.0.0") return self.page_mode
24,395
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._flatten
( self, pages: Union[None, DictionaryObject, PageObject] = None, inherit: Optional[Dict[str, Any]] = None, indirect_reference: Optional[IndirectObject] = None, )
1,161
1,205
def _flatten( self, pages: Union[None, DictionaryObject, PageObject] = None, inherit: Optional[Dict[str, Any]] = None, indirect_reference: Optional[IndirectObject] = None, ) -> None: inheritable_page_attributes = ( NameObject(PG.RESOURCES), NameObject(PG.MEDIABOX), NameObject(PG.CROPBOX), NameObject(PG.ROTATE), ) if inherit is None: inherit = {} if pages is None: # Fix issue 327: set flattened_pages attribute only for # decrypted file catalog = self.trailer[TK.ROOT].get_object() pages = catalog["/Pages"].get_object() # type: ignore self.flattened_pages = [] t = "/Pages" if PA.TYPE in pages: t = pages[PA.TYPE] # type: ignore if t == "/Pages": for attr in inheritable_page_attributes: if attr in pages: inherit[attr] = pages[attr] for page in pages[PA.KIDS]: # type: ignore addt = {} if isinstance(page, IndirectObject): addt["indirect_reference"] = page self._flatten(page.get_object(), inherit, **addt) elif t == "/Page": for attr_in, value in list(inherit.items()): # if the page has it's own value, it does not inherit the # parent's value: if attr_in not in pages: pages[attr_in] = value page_obj = PageObject(self, indirect_reference) page_obj.update(pages) # TODO: Could flattened_pages be None at this point? self.flattened_pages.append(page_obj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1161-L1205
39
[ 0, 6, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44 ]
77.777778
[]
0
false
91.582229
45
12
100
0
def _flatten( self, pages: Union[None, DictionaryObject, PageObject] = None, inherit: Optional[Dict[str, Any]] = None, indirect_reference: Optional[IndirectObject] = None, ) -> None: inheritable_page_attributes = ( NameObject(PG.RESOURCES), NameObject(PG.MEDIABOX), NameObject(PG.CROPBOX), NameObject(PG.ROTATE), ) if inherit is None: inherit = {} if pages is None: # Fix issue 327: set flattened_pages attribute only for # decrypted file catalog = self.trailer[TK.ROOT].get_object() pages = catalog["/Pages"].get_object() # type: ignore self.flattened_pages = [] t = "/Pages" if PA.TYPE in pages: t = pages[PA.TYPE] # type: ignore if t == "/Pages": for attr in inheritable_page_attributes: if attr in pages: inherit[attr] = pages[attr] for page in pages[PA.KIDS]: # type: ignore addt = {} if isinstance(page, IndirectObject): addt["indirect_reference"] = page self._flatten(page.get_object(), inherit, **addt) elif t == "/Page": for attr_in, value in list(inherit.items()): # if the page has it's own value, it does not inherit the # parent's value: if attr_in not in pages: pages[attr_in] = value page_obj = PageObject(self, indirect_reference) page_obj.update(pages) # TODO: Could flattened_pages be None at this point? self.flattened_pages.append(page_obj)
24,396
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_object_from_stream
( self, indirect_reference: IndirectObject )
return NullObject()
1,207
1,259
def _get_object_from_stream( self, indirect_reference: IndirectObject ) -> Union[int, PdfObject, str]: # indirect reference to object in object stream # read the entire object stream into memory stmnum, idx = self.xref_objStm[indirect_reference.idnum] obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore # This is an xref to a stream, so its type better be a stream assert cast(str, obj_stm["/Type"]) == "/ObjStm" # /N is the number of indirect objects in the stream assert idx < obj_stm["/N"] stream_data = BytesIO(b_(obj_stm.get_data())) # type: ignore for i in range(obj_stm["/N"]): # type: ignore read_non_whitespace(stream_data) stream_data.seek(-1, 1) objnum = NumberObject.read_from_stream(stream_data) read_non_whitespace(stream_data) stream_data.seek(-1, 1) offset = NumberObject.read_from_stream(stream_data) read_non_whitespace(stream_data) stream_data.seek(-1, 1) if objnum != indirect_reference.idnum: # We're only interested in one object continue if self.strict and idx != i: raise PdfReadError("Object is in wrong index.") stream_data.seek(int(obj_stm["/First"] + offset), 0) # type: ignore # to cope with some case where the 'pointer' is on a white space read_non_whitespace(stream_data) stream_data.seek(-1, 1) try: obj = read_object(stream_data, self) except PdfStreamError as exc: # Stream object cannot be read. Normally, a critical error, but # Adobe Reader doesn't complain, so continue (in strict mode?) logger_warning( f"Invalid stream (index {i}) within object " f"{indirect_reference.idnum} {indirect_reference.generation}: " f"{exc}", __name__, ) if self.strict: raise PdfReadError(f"Can't read object stream: {exc}") # Replace with null. Hopefully it's nothing important. obj = NullObject() return obj if self.strict: raise PdfReadError("This is a fatal error in strict mode.") return NullObject()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1207-L1259
39
[ 0, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 26, 27, 28, 29, 30, 31, 32, 33, 48, 49 ]
60.377358
[ 25, 34, 37, 44, 45, 47, 50, 51, 52 ]
16.981132
false
91.582229
53
10
83.018868
0
def _get_object_from_stream( self, indirect_reference: IndirectObject ) -> Union[int, PdfObject, str]: # indirect reference to object in object stream # read the entire object stream into memory stmnum, idx = self.xref_objStm[indirect_reference.idnum] obj_stm: EncodedStreamObject = IndirectObject(stmnum, 0, self).get_object() # type: ignore # This is an xref to a stream, so its type better be a stream assert cast(str, obj_stm["/Type"]) == "/ObjStm" # /N is the number of indirect objects in the stream assert idx < obj_stm["/N"] stream_data = BytesIO(b_(obj_stm.get_data())) # type: ignore for i in range(obj_stm["/N"]): # type: ignore read_non_whitespace(stream_data) stream_data.seek(-1, 1) objnum = NumberObject.read_from_stream(stream_data) read_non_whitespace(stream_data) stream_data.seek(-1, 1) offset = NumberObject.read_from_stream(stream_data) read_non_whitespace(stream_data) stream_data.seek(-1, 1) if objnum != indirect_reference.idnum: # We're only interested in one object continue if self.strict and idx != i: raise PdfReadError("Object is in wrong index.") stream_data.seek(int(obj_stm["/First"] + offset), 0) # type: ignore # to cope with some case where the 'pointer' is on a white space read_non_whitespace(stream_data) stream_data.seek(-1, 1) try: obj = read_object(stream_data, self) except PdfStreamError as exc: # Stream object cannot be read. Normally, a critical error, but # Adobe Reader doesn't complain, so continue (in strict mode?) logger_warning( f"Invalid stream (index {i}) within object " f"{indirect_reference.idnum} {indirect_reference.generation}: " f"{exc}", __name__, ) if self.strict: raise PdfReadError(f"Can't read object stream: {exc}") # Replace with null. Hopefully it's nothing important. obj = NullObject() return obj if self.strict: raise PdfReadError("This is a fatal error in strict mode.") return NullObject()
24,397
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_indirect_object
(self, num: int, gen: int)
return IndirectObject(num, gen, self).get_object()
Used to ease development. This is equivalent to generic.IndirectObject(num,gen,self).get_object() Args: num: gen: Returns: A PdfObject
Used to ease development. This is equivalent to generic.IndirectObject(num,gen,self).get_object()
1,261
1,273
def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]: """ Used to ease development. This is equivalent to generic.IndirectObject(num,gen,self).get_object() Args: num: gen: Returns: A PdfObject """ return IndirectObject(num, gen, self).get_object()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1261-L1273
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
91.582229
13
1
100
9
def _get_indirect_object(self, num: int, gen: int) -> Optional[PdfObject]: return IndirectObject(num, gen, self).get_object()
24,398
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.get_object
( self, indirect_reference: Union[int, IndirectObject] )
return retval
1,275
1,403
def get_object( self, indirect_reference: Union[int, IndirectObject] ) -> Optional[PdfObject]: if isinstance(indirect_reference, int): indirect_reference = IndirectObject(indirect_reference, 0, self) retval = self.cache_get_indirect_object( indirect_reference.generation, indirect_reference.idnum ) if retval is not None: return retval if ( indirect_reference.generation == 0 and indirect_reference.idnum in self.xref_objStm ): retval = self._get_object_from_stream(indirect_reference) # type: ignore elif ( indirect_reference.generation in self.xref and indirect_reference.idnum in self.xref[indirect_reference.generation] ): if self.xref_free_entry.get(indirect_reference.generation, {}).get( indirect_reference.idnum, False ): return NullObject() start = self.xref[indirect_reference.generation][indirect_reference.idnum] self.stream.seek(start, 0) try: idnum, generation = self.read_object_header(self.stream) except Exception: if hasattr(self.stream, "getbuffer"): buf = bytes(self.stream.getbuffer()) # type: ignore else: p = self.stream.tell() self.stream.seek(0, 0) buf = self.stream.read(-1) self.stream.seek(p, 0) m = re.search( rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), buf, ) if m is not None: logger_warning( f"Object ID {indirect_reference.idnum},{indirect_reference.generation} ref repaired", __name__, ) self.xref[indirect_reference.generation][ indirect_reference.idnum ] = (m.start(0) + 1) self.stream.seek(m.start(0) + 1) idnum, generation = self.read_object_header(self.stream) else: idnum = -1 # exception will be raised below if idnum != indirect_reference.idnum and self.xref_index: # Xref table probably had bad indexes due to not being zero-indexed if self.strict: raise PdfReadError( f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " f"does not match actual ({idnum} {generation}); " "xref table not zero-indexed." ) # xref table is corrected in non-strict mode elif idnum != indirect_reference.idnum and self.strict: # some other problem raise PdfReadError( f"Expected object ID ({indirect_reference.idnum} " f"{indirect_reference.generation}) does not match actual " f"({idnum} {generation})." ) if self.strict: assert generation == indirect_reference.generation retval = read_object(self.stream, self) # type: ignore # override encryption is used for the /Encrypt dictionary if not self._override_encryption and self._encryption is not None: # if we don't have the encryption key: if not self._encryption.is_decrypted(): raise FileNotDecryptedError("File has not been decrypted") # otherwise, decrypt here... retval = cast(PdfObject, retval) retval = self._encryption.decrypt_object( retval, indirect_reference.idnum, indirect_reference.generation ) else: if hasattr(self.stream, "getbuffer"): buf = bytes(self.stream.getbuffer()) # type: ignore else: p = self.stream.tell() self.stream.seek(0, 0) buf = self.stream.read(-1) self.stream.seek(p, 0) m = re.search( rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), buf, ) if m is not None: logger_warning( f"Object {indirect_reference.idnum} {indirect_reference.generation} found", __name__, ) if indirect_reference.generation not in self.xref: self.xref[indirect_reference.generation] = {} self.xref[indirect_reference.generation][indirect_reference.idnum] = ( m.start(0) + 1 ) self.stream.seek(m.end(0) + 1) skip_over_whitespace(self.stream) self.stream.seek(-1, 1) retval = read_object(self.stream, self) # type: ignore # override encryption is used for the /Encrypt dictionary if not self._override_encryption and self._encryption is not None: # if we don't have the encryption key: if not self._encryption.is_decrypted(): raise FileNotDecryptedError("File has not been decrypted") # otherwise, decrypt here... retval = cast(PdfObject, retval) retval = self._encryption.decrypt_object( retval, indirect_reference.idnum, indirect_reference.generation ) else: logger_warning( f"Object {indirect_reference.idnum} {indirect_reference.generation} not defined.", __name__, ) if self.strict: raise PdfReadError("Could not find object.") self.cache_indirect_object( indirect_reference.generation, indirect_reference.idnum, retval ) return retval
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1275-L1403
39
[ 0, 3, 4, 5, 8, 9, 10, 14, 15, 19, 23, 24, 25, 26, 27, 28, 29, 35, 39, 40, 44, 47, 48, 51, 52, 59, 60, 61, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 82, 83, 89, 93, 94, 98, 100, 103, 104, 105, 106, 107, 108, 109, 110, 119, 123, 124, 125, 128 ]
46.511628
[ 22, 31, 32, 33, 34, 50, 53, 54, 62, 85, 86, 87, 88, 99, 111, 112, 114, 115 ]
13.953488
false
91.582229
129
28
86.046512
0
def get_object( self, indirect_reference: Union[int, IndirectObject] ) -> Optional[PdfObject]: if isinstance(indirect_reference, int): indirect_reference = IndirectObject(indirect_reference, 0, self) retval = self.cache_get_indirect_object( indirect_reference.generation, indirect_reference.idnum ) if retval is not None: return retval if ( indirect_reference.generation == 0 and indirect_reference.idnum in self.xref_objStm ): retval = self._get_object_from_stream(indirect_reference) # type: ignore elif ( indirect_reference.generation in self.xref and indirect_reference.idnum in self.xref[indirect_reference.generation] ): if self.xref_free_entry.get(indirect_reference.generation, {}).get( indirect_reference.idnum, False ): return NullObject() start = self.xref[indirect_reference.generation][indirect_reference.idnum] self.stream.seek(start, 0) try: idnum, generation = self.read_object_header(self.stream) except Exception: if hasattr(self.stream, "getbuffer"): buf = bytes(self.stream.getbuffer()) # type: ignore else: p = self.stream.tell() self.stream.seek(0, 0) buf = self.stream.read(-1) self.stream.seek(p, 0) m = re.search( rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), buf, ) if m is not None: logger_warning( f"Object ID {indirect_reference.idnum},{indirect_reference.generation} ref repaired", __name__, ) self.xref[indirect_reference.generation][ indirect_reference.idnum ] = (m.start(0) + 1) self.stream.seek(m.start(0) + 1) idnum, generation = self.read_object_header(self.stream) else: idnum = -1 # exception will be raised below if idnum != indirect_reference.idnum and self.xref_index: # Xref table probably had bad indexes due to not being zero-indexed if self.strict: raise PdfReadError( f"Expected object ID ({indirect_reference.idnum} {indirect_reference.generation}) " f"does not match actual ({idnum} {generation}); " "xref table not zero-indexed." ) # xref table is corrected in non-strict mode elif idnum != indirect_reference.idnum and self.strict: # some other problem raise PdfReadError( f"Expected object ID ({indirect_reference.idnum} " f"{indirect_reference.generation}) does not match actual " f"({idnum} {generation})." ) if self.strict: assert generation == indirect_reference.generation retval = read_object(self.stream, self) # type: ignore # override encryption is used for the /Encrypt dictionary if not self._override_encryption and self._encryption is not None: # if we don't have the encryption key: if not self._encryption.is_decrypted(): raise FileNotDecryptedError("File has not been decrypted") # otherwise, decrypt here... retval = cast(PdfObject, retval) retval = self._encryption.decrypt_object( retval, indirect_reference.idnum, indirect_reference.generation ) else: if hasattr(self.stream, "getbuffer"): buf = bytes(self.stream.getbuffer()) # type: ignore else: p = self.stream.tell() self.stream.seek(0, 0) buf = self.stream.read(-1) self.stream.seek(p, 0) m = re.search( rf"\s{indirect_reference.idnum}\s+{indirect_reference.generation}\s+obj".encode(), buf, ) if m is not None: logger_warning( f"Object {indirect_reference.idnum} {indirect_reference.generation} found", __name__, ) if indirect_reference.generation not in self.xref: self.xref[indirect_reference.generation] = {} self.xref[indirect_reference.generation][indirect_reference.idnum] = ( m.start(0) + 1 ) self.stream.seek(m.end(0) + 1) skip_over_whitespace(self.stream) self.stream.seek(-1, 1) retval = read_object(self.stream, self) # type: ignore # override encryption is used for the /Encrypt dictionary if not self._override_encryption and self._encryption is not None: # if we don't have the encryption key: if not self._encryption.is_decrypted(): raise FileNotDecryptedError("File has not been decrypted") # otherwise, decrypt here... retval = cast(PdfObject, retval) retval = self._encryption.decrypt_object( retval, indirect_reference.idnum, indirect_reference.generation ) else: logger_warning( f"Object {indirect_reference.idnum} {indirect_reference.generation} not defined.", __name__, ) if self.strict: raise PdfReadError("Could not find object.") self.cache_indirect_object( indirect_reference.generation, indirect_reference.idnum, retval ) return retval
24,399
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getObject
( self, indirectReference: IndirectObject )
return self.get_object(indirectReference)
.. deprecated:: 1.28.0 Use :meth:`get_object` instead.
.. deprecated:: 1.28.0
1,405
1,414
def getObject( self, indirectReference: IndirectObject ) -> Optional[PdfObject]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`get_object` instead. """ deprecation_with_replacement("getObject", "get_object", "3.0.0") return self.get_object(indirectReference)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1405-L1414
39
[]
0
[]
0
false
91.582229
10
1
100
3
def getObject( self, indirectReference: IndirectObject ) -> Optional[PdfObject]: # deprecated deprecation_with_replacement("getObject", "get_object", "3.0.0") return self.get_object(indirectReference)
24,400
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.read_object_header
(self, stream: StreamType)
return int(idnum), int(generation)
1,416
1,442
def read_object_header(self, stream: StreamType) -> Tuple[int, int]: # Should never be necessary to read out whitespace, since the # cross-reference table should put us in the right spot to read the # object header. In reality... some files have stupid cross reference # tables that are off by whitespace bytes. extra = False skip_over_comment(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) idnum = read_until_whitespace(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) generation = read_until_whitespace(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) # although it's not used, it might still be necessary to read _obj = stream.read(3) # noqa: F841 read_non_whitespace(stream) stream.seek(-1, 1) if extra and self.strict: logger_warning( f"Superfluous whitespace found in object header {idnum} {generation}", # type: ignore __name__, ) return int(idnum), int(generation)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1416-L1442
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 26 ]
88.888889
[]
0
false
91.582229
27
3
100
0
def read_object_header(self, stream: StreamType) -> Tuple[int, int]: # Should never be necessary to read out whitespace, since the # cross-reference table should put us in the right spot to read the # object header. In reality... some files have stupid cross reference # tables that are off by whitespace bytes. extra = False skip_over_comment(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) idnum = read_until_whitespace(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) generation = read_until_whitespace(stream) extra |= skip_over_whitespace(stream) stream.seek(-1, 1) # although it's not used, it might still be necessary to read _obj = stream.read(3) # noqa: F841 read_non_whitespace(stream) stream.seek(-1, 1) if extra and self.strict: logger_warning( f"Superfluous whitespace found in object header {idnum} {generation}", # type: ignore __name__, ) return int(idnum), int(generation)
24,401
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.readObjectHeader
(self, stream: StreamType)
return self.read_object_header(stream)
.. deprecated:: 1.28.0 Use :meth:`read_object_header` instead.
.. deprecated:: 1.28.0
1,444
1,451
def readObjectHeader(self, stream: StreamType) -> Tuple[int, int]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`read_object_header` instead. """ deprecation_with_replacement("readObjectHeader", "read_object_header", "3.0.0") return self.read_object_header(stream)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1444-L1451
39
[]
0
[]
0
false
91.582229
8
1
100
3
def readObjectHeader(self, stream: StreamType) -> Tuple[int, int]: # deprecated deprecation_with_replacement("readObjectHeader", "read_object_header", "3.0.0") return self.read_object_header(stream)
24,402
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.cache_get_indirect_object
( self, generation: int, idnum: int )
return self.resolved_objects.get((generation, idnum))
1,453
1,456
def cache_get_indirect_object( self, generation: int, idnum: int ) -> Optional[PdfObject]: return self.resolved_objects.get((generation, idnum))
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1453-L1456
39
[ 0, 3 ]
50
[]
0
false
91.582229
4
1
100
0
def cache_get_indirect_object( self, generation: int, idnum: int ) -> Optional[PdfObject]: return self.resolved_objects.get((generation, idnum))
24,403
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.cacheGetIndirectObject
( self, generation: int, idnum: int )
return self.cache_get_indirect_object(generation, idnum)
.. deprecated:: 1.28.0 Use :meth:`cache_get_indirect_object` instead.
.. deprecated:: 1.28.0
1,458
1,469
def cacheGetIndirectObject( self, generation: int, idnum: int ) -> Optional[PdfObject]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`cache_get_indirect_object` instead. """ deprecation_with_replacement( "cacheGetIndirectObject", "cache_get_indirect_object", "3.0.0" ) return self.cache_get_indirect_object(generation, idnum)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1458-L1469
39
[]
0
[]
0
false
91.582229
12
1
100
3
def cacheGetIndirectObject( self, generation: int, idnum: int ) -> Optional[PdfObject]: # deprecated deprecation_with_replacement( "cacheGetIndirectObject", "cache_get_indirect_object", "3.0.0" ) return self.cache_get_indirect_object(generation, idnum)
24,404
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.cache_indirect_object
( self, generation: int, idnum: int, obj: Optional[PdfObject] )
return obj
1,471
1,482
def cache_indirect_object( self, generation: int, idnum: int, obj: Optional[PdfObject] ) -> Optional[PdfObject]: if (generation, idnum) in self.resolved_objects: msg = f"Overwriting cache for {generation} {idnum}" if self.strict: raise PdfReadError(msg) logger_warning(msg, __name__) self.resolved_objects[(generation, idnum)] = obj if obj is not None: obj.indirect_reference = IndirectObject(idnum, generation, self) return obj
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1471-L1482
39
[ 0, 3, 4, 5, 7, 8, 9, 10, 11 ]
75
[ 6 ]
8.333333
false
91.582229
12
4
91.666667
0
def cache_indirect_object( self, generation: int, idnum: int, obj: Optional[PdfObject] ) -> Optional[PdfObject]: if (generation, idnum) in self.resolved_objects: msg = f"Overwriting cache for {generation} {idnum}" if self.strict: raise PdfReadError(msg) logger_warning(msg, __name__) self.resolved_objects[(generation, idnum)] = obj if obj is not None: obj.indirect_reference = IndirectObject(idnum, generation, self) return obj
24,405
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.cacheIndirectObject
( self, generation: int, idnum: int, obj: Optional[PdfObject] )
return self.cache_indirect_object(generation, idnum, obj)
.. deprecated:: 1.28.0 Use :meth:`cache_indirect_object` instead.
.. deprecated:: 1.28.0
1,484
1,493
def cacheIndirectObject( self, generation: int, idnum: int, obj: Optional[PdfObject] ) -> Optional[PdfObject]: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`cache_indirect_object` instead. """ deprecation_with_replacement("cacheIndirectObject", "cache_indirect_object") return self.cache_indirect_object(generation, idnum, obj)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1484-L1493
39
[]
0
[]
0
false
91.582229
10
1
100
3
def cacheIndirectObject( self, generation: int, idnum: int, obj: Optional[PdfObject] ) -> Optional[PdfObject]: # deprecated deprecation_with_replacement("cacheIndirectObject", "cache_indirect_object") return self.cache_indirect_object(generation, idnum, obj)
24,406
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.read
(self, stream: StreamType)
1,495
1,531
def read(self, stream: StreamType) -> None: self._basic_validation(stream) self._find_eof_marker(stream) startxref = self._find_startxref_pos(stream) # check and eventually correct the startxref only in not strict xref_issue_nr = self._get_xref_issues(stream, startxref) if xref_issue_nr != 0: if self.strict and xref_issue_nr: raise PdfReadError("Broken xref table") logger_warning(f"incorrect startxref pointer({xref_issue_nr})", __name__) # read all cross reference tables and their trailers self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr) # if not zero-indexed, verify that the table is correct; change it if necessary if self.xref_index and not self.strict: loc = stream.tell() for gen, xref_entry in self.xref.items(): if gen == 65535: continue xref_k = sorted( xref_entry.keys() ) # must ensure ascendant to prevent damange for id in xref_k: stream.seek(xref_entry[id], 0) try: pid, _pgen = self.read_object_header(stream) except ValueError: break if pid == id - self.xref_index: # fixing index item per item is required for revised PDF. self.xref[gen][pid] = self.xref[gen][id] del self.xref[gen][id] # if not, then either it's just plain wrong, or the # non-zero-index is actually correct stream.seek(loc, 0)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1495-L1531
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36 ]
94.594595
[]
0
false
91.582229
37
11
100
0
def read(self, stream: StreamType) -> None: self._basic_validation(stream) self._find_eof_marker(stream) startxref = self._find_startxref_pos(stream) # check and eventually correct the startxref only in not strict xref_issue_nr = self._get_xref_issues(stream, startxref) if xref_issue_nr != 0: if self.strict and xref_issue_nr: raise PdfReadError("Broken xref table") logger_warning(f"incorrect startxref pointer({xref_issue_nr})", __name__) # read all cross reference tables and their trailers self._read_xref_tables_and_trailers(stream, startxref, xref_issue_nr) # if not zero-indexed, verify that the table is correct; change it if necessary if self.xref_index and not self.strict: loc = stream.tell() for gen, xref_entry in self.xref.items(): if gen == 65535: continue xref_k = sorted( xref_entry.keys() ) # must ensure ascendant to prevent damange for id in xref_k: stream.seek(xref_entry[id], 0) try: pid, _pgen = self.read_object_header(stream) except ValueError: break if pid == id - self.xref_index: # fixing index item per item is required for revised PDF. self.xref[gen][pid] = self.xref[gen][id] del self.xref[gen][id] # if not, then either it's just plain wrong, or the # non-zero-index is actually correct stream.seek(loc, 0)
24,407
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._basic_validation
(self, stream: StreamType)
1,533
1,546
def _basic_validation(self, stream: StreamType) -> None: # start at the end: stream.seek(0, os.SEEK_END) if not stream.tell(): raise EmptyFileError("Cannot read an empty file") if self.strict: stream.seek(0, os.SEEK_SET) header_byte = stream.read(5) if header_byte != b"%PDF-": raise PdfReadError( f"PDF starts with '{header_byte.decode('utf8')}', " "but '%PDF-' expected" ) stream.seek(0, os.SEEK_END)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1533-L1546
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 13 ]
78.571429
[]
0
false
91.582229
14
4
100
0
def _basic_validation(self, stream: StreamType) -> None: # start at the end: stream.seek(0, os.SEEK_END) if not stream.tell(): raise EmptyFileError("Cannot read an empty file") if self.strict: stream.seek(0, os.SEEK_SET) header_byte = stream.read(5) if header_byte != b"%PDF-": raise PdfReadError( f"PDF starts with '{header_byte.decode('utf8')}', " "but '%PDF-' expected" ) stream.seek(0, os.SEEK_END)
24,408
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._find_eof_marker
(self, stream: StreamType)
1,548
1,554
def _find_eof_marker(self, stream: StreamType) -> None: last_mb = 8 # to parse whole file line = b"" while line[:5] != b"%%EOF": if stream.tell() < last_mb: raise PdfReadError("EOF marker not found") line = read_previous_line(stream)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1548-L1554
39
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
91.582229
7
3
100
0
def _find_eof_marker(self, stream: StreamType) -> None: last_mb = 8 # to parse whole file line = b"" while line[:5] != b"%%EOF": if stream.tell() < last_mb: raise PdfReadError("EOF marker not found") line = read_previous_line(stream)
24,409
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._find_startxref_pos
(self, stream: StreamType)
return startxref
Find startxref entry - the location of the xref table. Args: stream: Returns: The bytes offset
Find startxref entry - the location of the xref table.
1,556
1,579
def _find_startxref_pos(self, stream: StreamType) -> int: """ Find startxref entry - the location of the xref table. Args: stream: Returns: The bytes offset """ line = read_previous_line(stream) try: startxref = int(line) except ValueError: # 'startxref' may be on the same line as the location if not line.startswith(b"startxref"): raise PdfReadError("startxref not found") startxref = int(line[9:].strip()) logger_warning("startxref on same line as offset", __name__) else: line = read_previous_line(stream) if line[:9] != b"startxref": raise PdfReadError("startxref not found") return startxref
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1556-L1579
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 23 ]
95.833333
[ 22 ]
4.166667
false
91.582229
24
4
95.833333
7
def _find_startxref_pos(self, stream: StreamType) -> int: line = read_previous_line(stream) try: startxref = int(line) except ValueError: # 'startxref' may be on the same line as the location if not line.startswith(b"startxref"): raise PdfReadError("startxref not found") startxref = int(line[9:].strip()) logger_warning("startxref on same line as offset", __name__) else: line = read_previous_line(stream) if line[:9] != b"startxref": raise PdfReadError("startxref not found") return startxref
24,410
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_standard_xref_table
(self, stream: StreamType)
1,581
1,688
def _read_standard_xref_table(self, stream: StreamType) -> None: # standard cross-reference table ref = stream.read(4) if ref[:3] != b"ref": raise PdfReadError("xref table read error") read_non_whitespace(stream) stream.seek(-1, 1) firsttime = True # check if the first time looking at the xref table while True: num = cast(int, read_object(stream, self)) if firsttime and num != 0: self.xref_index = num if self.strict: logger_warning( "Xref table not zero-indexed. ID numbers for objects will be corrected.", __name__, ) # if table not zero indexed, could be due to error from when PDF was created # which will lead to mismatched indices later on, only warned and corrected if self.strict==True firsttime = False read_non_whitespace(stream) stream.seek(-1, 1) size = cast(int, read_object(stream, self)) read_non_whitespace(stream) stream.seek(-1, 1) cnt = 0 while cnt < size: line = stream.read(20) # It's very clear in section 3.4.3 of the PDF spec # that all cross-reference table lines are a fixed # 20 bytes (as of PDF 1.7). However, some files have # 21-byte entries (or more) due to the use of \r\n # (CRLF) EOL's. Detect that case, and adjust the line # until it does not begin with a \r (CR) or \n (LF). while line[0] in b"\x0D\x0A": stream.seek(-20 + 1, 1) line = stream.read(20) # On the other hand, some malformed PDF files # use a single character EOL without a preceding # space. Detect that case, and seek the stream # back one character. (0-9 means we've bled into # the next xref entry, t means we've bled into the # text "trailer"): if line[-1] in b"0123456789t": stream.seek(-1, 1) try: offset_b, generation_b = line[:16].split(b" ") entry_type_b = line[17:18] offset, generation = int(offset_b), int(generation_b) except Exception: # if something wrong occured if hasattr(stream, "getbuffer"): buf = bytes(stream.getbuffer()) # type: ignore else: p = stream.tell() stream.seek(0, 0) buf = stream.read(-1) stream.seek(p) f = re.search(f"{num}\\s+(\\d+)\\s+obj".encode(), buf) if f is None: logger_warning( f"entry {num} in Xref table invalid; object not found", __name__, ) generation = 65535 offset = -1 else: logger_warning( f"entry {num} in Xref table invalid but object found", __name__, ) generation = int(f.group(1)) offset = f.start() if generation not in self.xref: self.xref[generation] = {} self.xref_free_entry[generation] = {} if num in self.xref[generation]: # It really seems like we should allow the last # xref table in the file to override previous # ones. Since we read the file backwards, assume # any existing key is already set correctly. pass else: self.xref[generation][num] = offset try: self.xref_free_entry[generation][num] = entry_type_b == b"f" except Exception: pass try: self.xref_free_entry[65535][num] = entry_type_b == b"f" except Exception: pass cnt += 1 num += 1 read_non_whitespace(stream) stream.seek(-1, 1) trailertag = stream.read(7) if trailertag != b"trailer": # more xrefs! stream.seek(-7, 1) else: break
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1581-L1688
39
[ 0, 1, 2, 3, 5, 6, 7, 8, 9, 10, 11, 12, 13, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 62, 63, 64, 65, 69, 70, 72, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 86, 87, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 107 ]
82.407407
[ 4, 58, 59, 60, 61 ]
4.62963
false
91.582229
108
17
95.37037
0
def _read_standard_xref_table(self, stream: StreamType) -> None: # standard cross-reference table ref = stream.read(4) if ref[:3] != b"ref": raise PdfReadError("xref table read error") read_non_whitespace(stream) stream.seek(-1, 1) firsttime = True # check if the first time looking at the xref table while True: num = cast(int, read_object(stream, self)) if firsttime and num != 0: self.xref_index = num if self.strict: logger_warning( "Xref table not zero-indexed. ID numbers for objects will be corrected.", __name__, ) # if table not zero indexed, could be due to error from when PDF was created # which will lead to mismatched indices later on, only warned and corrected if self.strict==True firsttime = False read_non_whitespace(stream) stream.seek(-1, 1) size = cast(int, read_object(stream, self)) read_non_whitespace(stream) stream.seek(-1, 1) cnt = 0 while cnt < size: line = stream.read(20) # It's very clear in section 3.4.3 of the PDF spec # that all cross-reference table lines are a fixed # 20 bytes (as of PDF 1.7). However, some files have # 21-byte entries (or more) due to the use of \r\n # (CRLF) EOL's. Detect that case, and adjust the line # until it does not begin with a \r (CR) or \n (LF). while line[0] in b"\x0D\x0A": stream.seek(-20 + 1, 1) line = stream.read(20) # On the other hand, some malformed PDF files # use a single character EOL without a preceding # space. Detect that case, and seek the stream # back one character. (0-9 means we've bled into # the next xref entry, t means we've bled into the # text "trailer"): if line[-1] in b"0123456789t": stream.seek(-1, 1) try: offset_b, generation_b = line[:16].split(b" ") entry_type_b = line[17:18] offset, generation = int(offset_b), int(generation_b) except Exception: # if something wrong occured if hasattr(stream, "getbuffer"): buf = bytes(stream.getbuffer()) # type: ignore else: p = stream.tell() stream.seek(0, 0) buf = stream.read(-1) stream.seek(p) f = re.search(f"{num}\\s+(\\d+)\\s+obj".encode(), buf) if f is None: logger_warning( f"entry {num} in Xref table invalid; object not found", __name__, ) generation = 65535 offset = -1 else: logger_warning( f"entry {num} in Xref table invalid but object found", __name__, ) generation = int(f.group(1)) offset = f.start() if generation not in self.xref: self.xref[generation] = {} self.xref_free_entry[generation] = {} if num in self.xref[generation]: # It really seems like we should allow the last # xref table in the file to override previous # ones. Since we read the file backwards, assume # any existing key is already set correctly. pass else: self.xref[generation][num] = offset try: self.xref_free_entry[generation][num] = entry_type_b == b"f" except Exception: pass try: self.xref_free_entry[65535][num] = entry_type_b == b"f" except Exception: pass cnt += 1 num += 1 read_non_whitespace(stream) stream.seek(-1, 1) trailertag = stream.read(7) if trailertag != b"trailer": # more xrefs! stream.seek(-7, 1) else: break
24,411
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_xref_tables_and_trailers
( self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int )
1,690
1,737
def _read_xref_tables_and_trailers( self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int ) -> None: self.xref: Dict[int, Dict[Any, Any]] = {} self.xref_free_entry: Dict[int, Dict[Any, Any]] = {} self.xref_objStm: Dict[int, Tuple[Any, Any]] = {} self.trailer = DictionaryObject() while startxref is not None: # load the xref table stream.seek(startxref, 0) x = stream.read(1) if x in b"\r\n": x = stream.read(1) if x == b"x": startxref = self._read_xref(stream) elif xref_issue_nr: try: self._rebuild_xref_table(stream) break except Exception: xref_issue_nr = 0 elif x.isdigit(): try: xrefstream = self._read_pdf15_xref_stream(stream) except Exception as e: if TK.ROOT in self.trailer: logger_warning( f"Previous trailer can not be read {e.args}", __name__, ) break else: raise PdfReadError(f"trailer can not be read {e.args}") trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID for key in trailer_keys: if key in xrefstream and key not in self.trailer: self.trailer[NameObject(key)] = xrefstream.raw_get(key) if "/XRefStm" in xrefstream: p = stream.tell() stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0) self._read_pdf15_xref_stream(stream) stream.seek(p, 0) if "/Prev" in xrefstream: startxref = cast(int, xrefstream["/Prev"]) else: break else: startxref = self._read_xref_other_error(stream, startxref)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1690-L1737
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 21, 22, 23, 24, 25, 26, 30, 33, 34, 35, 36, 37, 42, 43, 45, 47 ]
68.75
[ 19, 20, 32, 38, 39, 40, 41 ]
14.583333
false
91.582229
48
14
85.416667
0
def _read_xref_tables_and_trailers( self, stream: StreamType, startxref: Optional[int], xref_issue_nr: int ) -> None: self.xref: Dict[int, Dict[Any, Any]] = {} self.xref_free_entry: Dict[int, Dict[Any, Any]] = {} self.xref_objStm: Dict[int, Tuple[Any, Any]] = {} self.trailer = DictionaryObject() while startxref is not None: # load the xref table stream.seek(startxref, 0) x = stream.read(1) if x in b"\r\n": x = stream.read(1) if x == b"x": startxref = self._read_xref(stream) elif xref_issue_nr: try: self._rebuild_xref_table(stream) break except Exception: xref_issue_nr = 0 elif x.isdigit(): try: xrefstream = self._read_pdf15_xref_stream(stream) except Exception as e: if TK.ROOT in self.trailer: logger_warning( f"Previous trailer can not be read {e.args}", __name__, ) break else: raise PdfReadError(f"trailer can not be read {e.args}") trailer_keys = TK.ROOT, TK.ENCRYPT, TK.INFO, TK.ID for key in trailer_keys: if key in xrefstream and key not in self.trailer: self.trailer[NameObject(key)] = xrefstream.raw_get(key) if "/XRefStm" in xrefstream: p = stream.tell() stream.seek(cast(int, xrefstream["/XRefStm"]) + 1, 0) self._read_pdf15_xref_stream(stream) stream.seek(p, 0) if "/Prev" in xrefstream: startxref = cast(int, xrefstream["/Prev"]) else: break else: startxref = self._read_xref_other_error(stream, startxref)
24,412
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_xref
(self, stream: StreamType)
1,739
1,762
def _read_xref(self, stream: StreamType) -> Optional[int]: self._read_standard_xref_table(stream) read_non_whitespace(stream) stream.seek(-1, 1) new_trailer = cast(Dict[str, Any], read_object(stream, self)) for key, value in new_trailer.items(): if key not in self.trailer: self.trailer[key] = value if "/XRefStm" in new_trailer: p = stream.tell() stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0) try: self._read_pdf15_xref_stream(stream) except Exception: logger_warning( f"XRef object at {new_trailer['/XRefStm']} can not be read, some object may be missing", __name__, ) stream.seek(p, 0) if "/Prev" in new_trailer: startxref = new_trailer["/Prev"] return startxref else: return None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1739-L1762
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 18, 19, 20, 21, 23 ]
83.333333
[]
0
false
91.582229
24
6
100
0
def _read_xref(self, stream: StreamType) -> Optional[int]: self._read_standard_xref_table(stream) read_non_whitespace(stream) stream.seek(-1, 1) new_trailer = cast(Dict[str, Any], read_object(stream, self)) for key, value in new_trailer.items(): if key not in self.trailer: self.trailer[key] = value if "/XRefStm" in new_trailer: p = stream.tell() stream.seek(cast(int, new_trailer["/XRefStm"]) + 1, 0) try: self._read_pdf15_xref_stream(stream) except Exception: logger_warning( f"XRef object at {new_trailer['/XRefStm']} can not be read, some object may be missing", __name__, ) stream.seek(p, 0) if "/Prev" in new_trailer: startxref = new_trailer["/Prev"] return startxref else: return None
24,413
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_xref_other_error
( self, stream: StreamType, startxref: int )
1,764
1,803
def _read_xref_other_error( self, stream: StreamType, startxref: int ) -> Optional[int]: # some PDFs have /Prev=0 in the trailer, instead of no /Prev if startxref == 0: if self.strict: raise PdfReadError( "/Prev=0 in the trailer (try opening with strict=False)" ) logger_warning( "/Prev=0 in the trailer - assuming there is no previous xref table", __name__, ) return None # bad xref character at startxref. Let's see if we can find # the xref table nearby, as we've observed this error with an # off-by-one before. stream.seek(-11, 1) tmp = stream.read(20) xref_loc = tmp.find(b"xref") if xref_loc != -1: startxref -= 10 - xref_loc return startxref # No explicit xref table, try finding a cross-reference stream. stream.seek(startxref, 0) for look in range(5): if stream.read(1).isdigit(): # This is not a standard PDF, consider adding a warning startxref += look return startxref # no xref table found at specified location if "/Root" in self.trailer and not self.strict: # if Root has been already found, just raise warning logger_warning("Invalid parent xref., rebuild xref", __name__) try: self._rebuild_xref_table(stream) return None except Exception: raise PdfReadError("can not rebuild xref") raise PdfReadError("Could not find xref table at specified location")
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1764-L1803
39
[ 0, 3, 4, 5, 6, 9, 13, 14, 15, 16, 17, 18, 19, 20, 23, 24, 25, 26, 27, 30, 31, 32, 33, 34, 35, 36 ]
65
[ 21, 22, 28, 29, 37, 38, 39 ]
17.5
false
91.582229
40
9
82.5
0
def _read_xref_other_error( self, stream: StreamType, startxref: int ) -> Optional[int]: # some PDFs have /Prev=0 in the trailer, instead of no /Prev if startxref == 0: if self.strict: raise PdfReadError( "/Prev=0 in the trailer (try opening with strict=False)" ) logger_warning( "/Prev=0 in the trailer - assuming there is no previous xref table", __name__, ) return None # bad xref character at startxref. Let's see if we can find # the xref table nearby, as we've observed this error with an # off-by-one before. stream.seek(-11, 1) tmp = stream.read(20) xref_loc = tmp.find(b"xref") if xref_loc != -1: startxref -= 10 - xref_loc return startxref # No explicit xref table, try finding a cross-reference stream. stream.seek(startxref, 0) for look in range(5): if stream.read(1).isdigit(): # This is not a standard PDF, consider adding a warning startxref += look return startxref # no xref table found at specified location if "/Root" in self.trailer and not self.strict: # if Root has been already found, just raise warning logger_warning("Invalid parent xref., rebuild xref", __name__) try: self._rebuild_xref_table(stream) return None except Exception: raise PdfReadError("can not rebuild xref") raise PdfReadError("Could not find xref table at specified location")
24,414
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_pdf15_xref_stream
( self, stream: StreamType )
return xrefstream
1,805
1,843
def _read_pdf15_xref_stream( self, stream: StreamType ) -> Union[ContentStream, EncodedStreamObject, DecodedStreamObject]: # PDF 1.5+ Cross-Reference Stream stream.seek(-1, 1) idnum, generation = self.read_object_header(stream) xrefstream = cast(ContentStream, read_object(stream, self)) assert cast(str, xrefstream["/Type"]) == "/XRef" self.cache_indirect_object(generation, idnum, xrefstream) stream_data = BytesIO(b_(xrefstream.get_data())) # Index pairs specify the subsections in the dictionary. If # none create one subsection that spans everything. idx_pairs = xrefstream.get("/Index", [0, xrefstream.get("/Size")]) entry_sizes = cast(Dict[Any, Any], xrefstream.get("/W")) assert len(entry_sizes) >= 3 if self.strict and len(entry_sizes) > 3: raise PdfReadError(f"Too many entry sizes: {entry_sizes}") def get_entry(i: int) -> Union[int, Tuple[int, ...]]: # Reads the correct number of bytes for each entry. See the # discussion of the W parameter in PDF spec table 17. if entry_sizes[i] > 0: d = stream_data.read(entry_sizes[i]) return convert_to_int(d, entry_sizes[i]) # PDF Spec Table 17: A value of zero for an element in the # W array indicates...the default value shall be used if i == 0: return 1 # First value defaults to 1 else: return 0 def used_before(num: int, generation: Union[int, Tuple[int, ...]]) -> bool: # We move backwards through the xrefs, don't replace any. return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore # Iterate through each subsection self._read_xref_subsections(idx_pairs, get_entry, used_before) return xrefstream
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1805-L1843
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 30, 31, 32, 33, 34, 35, 36, 37, 38 ]
87.179487
[ 16, 28 ]
5.128205
false
91.582229
39
10
94.871795
0
def _read_pdf15_xref_stream( self, stream: StreamType ) -> Union[ContentStream, EncodedStreamObject, DecodedStreamObject]: # PDF 1.5+ Cross-Reference Stream stream.seek(-1, 1) idnum, generation = self.read_object_header(stream) xrefstream = cast(ContentStream, read_object(stream, self)) assert cast(str, xrefstream["/Type"]) == "/XRef" self.cache_indirect_object(generation, idnum, xrefstream) stream_data = BytesIO(b_(xrefstream.get_data())) # Index pairs specify the subsections in the dictionary. If # none create one subsection that spans everything. idx_pairs = xrefstream.get("/Index", [0, xrefstream.get("/Size")]) entry_sizes = cast(Dict[Any, Any], xrefstream.get("/W")) assert len(entry_sizes) >= 3 if self.strict and len(entry_sizes) > 3: raise PdfReadError(f"Too many entry sizes: {entry_sizes}") def get_entry(i: int) -> Union[int, Tuple[int, ...]]: # Reads the correct number of bytes for each entry. See the # discussion of the W parameter in PDF spec table 17. if entry_sizes[i] > 0: d = stream_data.read(entry_sizes[i]) return convert_to_int(d, entry_sizes[i]) # PDF Spec Table 17: A value of zero for an element in the # W array indicates...the default value shall be used if i == 0: return 1 # First value defaults to 1 else: return 0 def used_before(num: int, generation: Union[int, Tuple[int, ...]]) -> bool: # We move backwards through the xrefs, don't replace any. return num in self.xref.get(generation, []) or num in self.xref_objStm # type: ignore # Iterate through each subsection self._read_xref_subsections(idx_pairs, get_entry, used_before) return xrefstream
24,415
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._get_xref_issues
(stream: StreamType, startxref: int)
return 0
Return an int which indicates an issue. 0 means there is no issue. Args: stream: startxref: Returns: 0 means no issue, other values represent specific issues.
Return an int which indicates an issue. 0 means there is no issue.
1,846
1,877
def _get_xref_issues(stream: StreamType, startxref: int) -> int: """ Return an int which indicates an issue. 0 means there is no issue. Args: stream: startxref: Returns: 0 means no issue, other values represent specific issues. """ stream.seek(startxref - 1, 0) # -1 to check character before line = stream.read(1) if line not in b"\r\n \t": return 1 line = stream.read(4) if line != b"xref": # not an xref so check if it is an XREF object line = b"" while line in b"0123456789 \t": line = stream.read(1) if line == b"": return 2 line += stream.read(2) # 1 char already read, +2 to check "obj" if line.lower() != b"obj": return 3 # while stream.read(1) in b" \t\r\n": # pass # line = stream.read(256) # check that it is xref obj # if b"/xref" not in line.lower(): # return 4 return 0
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1846-L1877
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]
100
[]
0
true
91.582229
32
6
100
8
def _get_xref_issues(stream: StreamType, startxref: int) -> int: stream.seek(startxref - 1, 0) # -1 to check character before line = stream.read(1) if line not in b"\r\n \t": return 1 line = stream.read(4) if line != b"xref": # not an xref so check if it is an XREF object line = b"" while line in b"0123456789 \t": line = stream.read(1) if line == b"": return 2 line += stream.read(2) # 1 char already read, +2 to check "obj" if line.lower() != b"obj": return 3 # while stream.read(1) in b" \t\r\n": # pass # line = stream.read(256) # check that it is xref obj # if b"/xref" not in line.lower(): # return 4 return 0
24,416
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._rebuild_xref_table
(self, stream: StreamType)
1,879
1,896
def _rebuild_xref_table(self, stream: StreamType) -> None: self.xref = {} stream.seek(0, 0) f_ = stream.read(-1) for m in re.finditer(rb"[\r\n \t][ \t]*(\d+)[ \t]+(\d+)[ \t]+obj", f_): idnum = int(m.group(1)) generation = int(m.group(2)) if generation not in self.xref: self.xref[generation] = {} self.xref[generation][idnum] = m.start(1) stream.seek(0, 0) for m in re.finditer(rb"[\r\n \t][ \t]*trailer[\r\n \t]*(<<)", f_): stream.seek(m.start(1), 0) new_trailer = cast(Dict[Any, Any], read_object(stream, self)) # Here, we are parsing the file from start to end, the new data have to erase the existing. for key, value in list(new_trailer.items()): self.trailer[key] = value
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1879-L1896
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 ]
100
[]
0
true
91.582229
18
5
100
0
def _rebuild_xref_table(self, stream: StreamType) -> None: self.xref = {} stream.seek(0, 0) f_ = stream.read(-1) for m in re.finditer(rb"[\r\n \t][ \t]*(\d+)[ \t]+(\d+)[ \t]+obj", f_): idnum = int(m.group(1)) generation = int(m.group(2)) if generation not in self.xref: self.xref[generation] = {} self.xref[generation][idnum] = m.start(1) stream.seek(0, 0) for m in re.finditer(rb"[\r\n \t][ \t]*trailer[\r\n \t]*(<<)", f_): stream.seek(m.start(1), 0) new_trailer = cast(Dict[Any, Any], read_object(stream, self)) # Here, we are parsing the file from start to end, the new data have to erase the existing. for key, value in list(new_trailer.items()): self.trailer[key] = value
24,417
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._read_xref_subsections
( self, idx_pairs: List[int], get_entry: Callable[[int], Union[int, Tuple[int, ...]]], used_before: Callable[[int, Union[int, Tuple[int, ...]]], bool], )
1,898
1,933
def _read_xref_subsections( self, idx_pairs: List[int], get_entry: Callable[[int], Union[int, Tuple[int, ...]]], used_before: Callable[[int, Union[int, Tuple[int, ...]]], bool], ) -> None: last_end = 0 for start, size in self._pairs(idx_pairs): # The subsections must increase assert start >= last_end last_end = start + size for num in range(start, start + size): # The first entry is the type xref_type = get_entry(0) # The rest of the elements depend on the xref_type if xref_type == 0: # linked list of free objects next_free_object = get_entry(1) # noqa: F841 next_generation = get_entry(2) # noqa: F841 elif xref_type == 1: # objects that are in use but are not compressed byte_offset = get_entry(1) generation = get_entry(2) if generation not in self.xref: self.xref[generation] = {} # type: ignore if not used_before(num, generation): self.xref[generation][num] = byte_offset # type: ignore elif xref_type == 2: # compressed objects objstr_num = get_entry(1) obstr_idx = get_entry(2) generation = 0 # PDF spec table 18, generation is 0 if not used_before(num, generation): self.xref_objStm[num] = (objstr_num, obstr_idx) elif self.strict: raise PdfReadError(f"Unknown xref type: {xref_type}")
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1898-L1933
39
[ 0, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33 ]
80.555556
[ 34, 35 ]
5.555556
false
91.582229
36
11
94.444444
0
def _read_xref_subsections( self, idx_pairs: List[int], get_entry: Callable[[int], Union[int, Tuple[int, ...]]], used_before: Callable[[int, Union[int, Tuple[int, ...]]], bool], ) -> None: last_end = 0 for start, size in self._pairs(idx_pairs): # The subsections must increase assert start >= last_end last_end = start + size for num in range(start, start + size): # The first entry is the type xref_type = get_entry(0) # The rest of the elements depend on the xref_type if xref_type == 0: # linked list of free objects next_free_object = get_entry(1) # noqa: F841 next_generation = get_entry(2) # noqa: F841 elif xref_type == 1: # objects that are in use but are not compressed byte_offset = get_entry(1) generation = get_entry(2) if generation not in self.xref: self.xref[generation] = {} # type: ignore if not used_before(num, generation): self.xref[generation][num] = byte_offset # type: ignore elif xref_type == 2: # compressed objects objstr_num = get_entry(1) obstr_idx = get_entry(2) generation = 0 # PDF spec table 18, generation is 0 if not used_before(num, generation): self.xref_objStm[num] = (objstr_num, obstr_idx) elif self.strict: raise PdfReadError(f"Unknown xref type: {xref_type}")
24,418
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader._pairs
(self, array: List[int])
1,935
1,941
def _pairs(self, array: List[int]) -> Iterable[Tuple[int, int]]: i = 0 while True: yield array[i], array[i + 1] i += 2 if (i + 1) >= len(array): break
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1935-L1941
39
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
91.582229
7
3
100
0
def _pairs(self, array: List[int]) -> Iterable[Tuple[int, int]]: i = 0 while True: yield array[i], array[i + 1] i += 2 if (i + 1) >= len(array): break
24,419
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.read_next_end_line
( self, stream: StreamType, limit_offset: int = 0 )
return b"".join(line_parts)
.. deprecated:: 2.1.0
.. deprecated:: 2.1.0
1,943
1,974
def read_next_end_line( self, stream: StreamType, limit_offset: int = 0 ) -> bytes: # deprecated """.. deprecated:: 2.1.0""" deprecate_no_replacement("read_next_end_line", removed_in="4.0.0") line_parts = [] while True: # Prevent infinite loops in malformed PDFs if stream.tell() == 0 or stream.tell() == limit_offset: raise PdfReadError("Could not read malformed PDF file") x = stream.read(1) if stream.tell() < 2: raise PdfReadError("EOL marker not found") stream.seek(-2, 1) if x in (b"\n", b"\r"): # \n = LF; \r = CR crlf = False while x in (b"\n", b"\r"): x = stream.read(1) if x in (b"\n", b"\r"): # account for CR+LF stream.seek(-1, 1) crlf = True if stream.tell() < 2: raise PdfReadError("EOL marker not found") stream.seek(-2, 1) stream.seek( 2 if crlf else 1, 1 ) # if using CR+LF, go back 2 bytes, else 1 break else: line_parts.append(x) line_parts.reverse() return b"".join(line_parts)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1943-L1974
39
[]
0
[]
0
false
91.582229
32
9
100
1
def read_next_end_line( self, stream: StreamType, limit_offset: int = 0 ) -> bytes: # deprecated deprecate_no_replacement("read_next_end_line", removed_in="4.0.0") line_parts = [] while True: # Prevent infinite loops in malformed PDFs if stream.tell() == 0 or stream.tell() == limit_offset: raise PdfReadError("Could not read malformed PDF file") x = stream.read(1) if stream.tell() < 2: raise PdfReadError("EOL marker not found") stream.seek(-2, 1) if x in (b"\n", b"\r"): # \n = LF; \r = CR crlf = False while x in (b"\n", b"\r"): x = stream.read(1) if x in (b"\n", b"\r"): # account for CR+LF stream.seek(-1, 1) crlf = True if stream.tell() < 2: raise PdfReadError("EOL marker not found") stream.seek(-2, 1) stream.seek( 2 if crlf else 1, 1 ) # if using CR+LF, go back 2 bytes, else 1 break else: line_parts.append(x) line_parts.reverse() return b"".join(line_parts)
24,420
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.readNextEndLine
( self, stream: StreamType, limit_offset: int = 0 )
return self.read_next_end_line(stream, limit_offset)
.. deprecated:: 1.28.0
.. deprecated:: 1.28.0
1,976
1,981
def readNextEndLine( self, stream: StreamType, limit_offset: int = 0 ) -> bytes: # deprecated """.. deprecated:: 1.28.0""" deprecation_no_replacement("readNextEndLine", "3.0.0") return self.read_next_end_line(stream, limit_offset)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1976-L1981
39
[]
0
[]
0
false
91.582229
6
1
100
1
def readNextEndLine( self, stream: StreamType, limit_offset: int = 0 ) -> bytes: # deprecated deprecation_no_replacement("readNextEndLine", "3.0.0") return self.read_next_end_line(stream, limit_offset)
24,421
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.decrypt
(self, password: Union[str, bytes])
return self._encryption.verify(password)
When using an encrypted / secured PDF file with the PDF Standard encryption handler, this function will allow the file to be decrypted. It checks the given password against the document's user password and owner password, and then stores the resulting decryption key if either password is correct. It does not matter which password was matched. Both passwords provide the correct decryption key that will allow the document to be used with this library. Args: password: The password to match. Returns: A `PasswordType`.
When using an encrypted / secured PDF file with the PDF Standard encryption handler, this function will allow the file to be decrypted. It checks the given password against the document's user password and owner password, and then stores the resulting decryption key if either password is correct.
1,983
2,004
def decrypt(self, password: Union[str, bytes]) -> PasswordType: """ When using an encrypted / secured PDF file with the PDF Standard encryption handler, this function will allow the file to be decrypted. It checks the given password against the document's user password and owner password, and then stores the resulting decryption key if either password is correct. It does not matter which password was matched. Both passwords provide the correct decryption key that will allow the document to be used with this library. Args: password: The password to match. Returns: A `PasswordType`. """ if not self._encryption: raise PdfReadError("Not encrypted file") # TODO: raise Exception for wrong password return self._encryption.verify(password)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L1983-L2004
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 20, 21 ]
95.454545
[ 19 ]
4.545455
false
91.582229
22
2
95.454545
15
def decrypt(self, password: Union[str, bytes]) -> PasswordType: if not self._encryption: raise PdfReadError("Not encrypted file") # TODO: raise Exception for wrong password return self._encryption.verify(password)
24,422
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.decode_permissions
(self, permissions_code: int)
return permissions
2,006
2,019
def decode_permissions(self, permissions_code: int) -> Dict[str, bool]: # Takes the permissions as an integer, returns the allowed access permissions = {} permissions["print"] = permissions_code & (1 << 3 - 1) != 0 # bit 3 permissions["modify"] = permissions_code & (1 << 4 - 1) != 0 # bit 4 permissions["copy"] = permissions_code & (1 << 5 - 1) != 0 # bit 5 permissions["annotations"] = permissions_code & (1 << 6 - 1) != 0 # bit 6 permissions["forms"] = permissions_code & (1 << 9 - 1) != 0 # bit 9 permissions["accessability"] = permissions_code & (1 << 10 - 1) != 0 # bit 10 permissions["assemble"] = permissions_code & (1 << 11 - 1) != 0 # bit 11 permissions["print_high_quality"] = ( permissions_code & (1 << 12 - 1) != 0 ) # bit 12 return permissions
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2006-L2019
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 13 ]
85.714286
[]
0
false
91.582229
14
1
100
0
def decode_permissions(self, permissions_code: int) -> Dict[str, bool]: # Takes the permissions as an integer, returns the allowed access permissions = {} permissions["print"] = permissions_code & (1 << 3 - 1) != 0 # bit 3 permissions["modify"] = permissions_code & (1 << 4 - 1) != 0 # bit 4 permissions["copy"] = permissions_code & (1 << 5 - 1) != 0 # bit 5 permissions["annotations"] = permissions_code & (1 << 6 - 1) != 0 # bit 6 permissions["forms"] = permissions_code & (1 << 9 - 1) != 0 # bit 9 permissions["accessability"] = permissions_code & (1 << 10 - 1) != 0 # bit 10 permissions["assemble"] = permissions_code & (1 << 11 - 1) != 0 # bit 11 permissions["print_high_quality"] = ( permissions_code & (1 << 12 - 1) != 0 ) # bit 12 return permissions
24,423
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.is_encrypted
(self)
return TK.ENCRYPT in self.trailer
Read-only boolean property showing whether this PDF file is encrypted. Note that this property, if true, will remain true even after the :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
Read-only boolean property showing whether this PDF file is encrypted. Note that this property, if true, will remain true even after the :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called.
2,022
2,028
def is_encrypted(self) -> bool: """ Read-only boolean property showing whether this PDF file is encrypted. Note that this property, if true, will remain true even after the :meth:`decrypt()<pypdf.PdfReader.decrypt>` method is called. """ return TK.ENCRYPT in self.trailer
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2022-L2028
39
[ 0, 1, 2, 3, 4, 5, 6 ]
100
[]
0
true
91.582229
7
1
100
3
def is_encrypted(self) -> bool: return TK.ENCRYPT in self.trailer
24,424
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.getIsEncrypted
(self)
return self.is_encrypted
.. deprecated:: 1.28.0 Use :py:attr:`is_encrypted` instead.
.. deprecated:: 1.28.0
2,030
2,037
def getIsEncrypted(self) -> bool: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`is_encrypted` instead. """ deprecation_with_replacement("getIsEncrypted", "is_encrypted", "3.0.0") return self.is_encrypted
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2030-L2037
39
[]
0
[]
0
false
91.582229
8
1
100
3
def getIsEncrypted(self) -> bool: # deprecated deprecation_with_replacement("getIsEncrypted", "is_encrypted", "3.0.0") return self.is_encrypted
24,425
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.isEncrypted
(self)
return self.is_encrypted
.. deprecated:: 1.28.0 Use :py:attr:`is_encrypted` instead.
.. deprecated:: 1.28.0
2,040
2,047
def isEncrypted(self) -> bool: # deprecated """ .. deprecated:: 1.28.0 Use :py:attr:`is_encrypted` instead. """ deprecation_with_replacement("isEncrypted", "is_encrypted", "3.0.0") return self.is_encrypted
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2040-L2047
39
[]
0
[]
0
false
91.582229
8
1
100
3
def isEncrypted(self) -> bool: # deprecated deprecation_with_replacement("isEncrypted", "is_encrypted", "3.0.0") return self.is_encrypted
24,426
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfReader.xfa
(self)
return retval
2,050
2,071
def xfa(self) -> Optional[Dict[str, Any]]: tree: Optional[TreeObject] = None retval: Dict[str, Any] = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) if "/AcroForm" not in catalog or not catalog["/AcroForm"]: return None tree = cast(TreeObject, catalog["/AcroForm"]) if "/XFA" in tree: fields = cast(ArrayObject, tree["/XFA"]) i = iter(fields) for f in i: tag = f f = next(i) if isinstance(f, IndirectObject): field = cast(Optional[EncodedStreamObject], f.get_object()) if field: es = zlib.decompress(field._data) retval[tag] = es return retval
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2050-L2071
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21 ]
100
[]
0
true
91.582229
22
7
100
0
def xfa(self) -> Optional[Dict[str, Any]]: tree: Optional[TreeObject] = None retval: Dict[str, Any] = {} catalog = cast(DictionaryObject, self.trailer[TK.ROOT]) if "/AcroForm" not in catalog or not catalog["/AcroForm"]: return None tree = cast(TreeObject, catalog["/AcroForm"]) if "/XFA" in tree: fields = cast(ArrayObject, tree["/XFA"]) i = iter(fields) for f in i: tag = f f = next(i) if isinstance(f, IndirectObject): field = cast(Optional[EncodedStreamObject], f.get_object()) if field: es = zlib.decompress(field._data) retval[tag] = es return retval
24,427
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_reader.py
PdfFileReader.__init__
(self, *args: Any, **kwargs: Any)
2,075
2,079
def __init__(self, *args: Any, **kwargs: Any) -> None: deprecation_with_replacement("PdfFileReader", "PdfReader", "3.0.0") if "strict" not in kwargs and len(args) < 2: kwargs["strict"] = True # maintain the default super().__init__(*args, **kwargs)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L2075-L2079
39
[]
0
[]
0
false
91.582229
5
3
100
0
def __init__(self, *args: Any, **kwargs: Any) -> None: deprecation_with_replacement("PdfFileReader", "PdfReader", "3.0.0") if "strict" not in kwargs and len(args) < 2: kwargs["strict"] = True # maintain the default super().__init__(*args, **kwargs)
24,428
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
_MergedPage.__init__
(self, pagedata: PageObject, src: PdfReader, id: int)
81
85
def __init__(self, pagedata: PageObject, src: PdfReader, id: int) -> None: self.src = src self.pagedata = pagedata self.out_pagedata = None self.id = id
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L81-L85
39
[ 0, 1, 2, 3, 4 ]
100
[]
0
true
95.477387
5
1
100
0
def __init__(self, pagedata: PageObject, src: PdfReader, id: int) -> None: self.src = src self.pagedata = pagedata self.out_pagedata = None self.id = id
24,429
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.__init__
( self, strict: bool = False, fileobj: Union[Path, StrByteType] = "" )
107
117
def __init__( self, strict: bool = False, fileobj: Union[Path, StrByteType] = "" ) -> None: self.inputs: List[Tuple[Any, PdfReader]] = [] self.pages: List[Any] = [] self.output: Optional[PdfWriter] = PdfWriter() self.outline: OutlineType = [] self.named_dests: List[Any] = [] self.id_count = 0 self.fileobj = fileobj self.strict = strict
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L107-L117
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10 ]
81.818182
[]
0
false
95.477387
11
1
100
0
def __init__( self, strict: bool = False, fileobj: Union[Path, StrByteType] = "" ) -> None: self.inputs: List[Tuple[Any, PdfReader]] = [] self.pages: List[Any] = [] self.output: Optional[PdfWriter] = PdfWriter() self.outline: OutlineType = [] self.named_dests: List[Any] = [] self.id_count = 0 self.fileobj = fileobj self.strict = strict
24,430
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.__enter__
(self)
return self
119
121
def __enter__(self) -> "PdfMerger": # There is nothing to do. return self
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L119-L121
39
[ 0, 1, 2 ]
100
[]
0
true
95.477387
3
1
100
0
def __enter__(self) -> "PdfMerger": # There is nothing to do. return self
24,431
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.__exit__
( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], )
Write to the fileobj and close the merger.
Write to the fileobj and close the merger.
123
132
def __exit__( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: """Write to the fileobj and close the merger.""" if self.fileobj: self.write(self.fileobj) self.close()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L123-L132
39
[ 0, 6, 7, 8, 9 ]
50
[]
0
false
95.477387
10
2
100
1
def __exit__( self, exc_type: Optional[Type[BaseException]], exc: Optional[BaseException], traceback: Optional[TracebackType], ) -> None: if self.fileobj: self.write(self.fileobj) self.close()
24,432
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.merge
( self, page_number: Optional[int] = None, fileobj: Union[None, Path, StrByteType, PdfReader] = None, outline_item: Optional[str] = None, pages: Optional[PageRangeSpec] = None, import_outline: bool = True, position: Optional[int] = None, # deprecated )
Merge the pages from the given file into the output file at the specified page number. Args: page_number: The *page number* to insert this file. File will be inserted after the given number. fileobj: A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file. None as an argument is deprecated. outline_item: Optionally, you may specify an outline item (previously referred to as a 'bookmark') to be applied at the beginning of the included file by supplying the text of the outline item. pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple to merge only the specified range of pages from the source document into the output document. Can also be a list of pages to merge. import_outline: You may prevent the source document's outline (collection of outline items, previously referred to as 'bookmarks') from being imported by specifying this as ``False``.
Merge the pages from the given file into the output file at the specified page number.
135
248
def merge( self, page_number: Optional[int] = None, fileobj: Union[None, Path, StrByteType, PdfReader] = None, outline_item: Optional[str] = None, pages: Optional[PageRangeSpec] = None, import_outline: bool = True, position: Optional[int] = None, # deprecated ) -> None: """ Merge the pages from the given file into the output file at the specified page number. Args: page_number: The *page number* to insert this file. File will be inserted after the given number. fileobj: A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file. None as an argument is deprecated. outline_item: Optionally, you may specify an outline item (previously referred to as a 'bookmark') to be applied at the beginning of the included file by supplying the text of the outline item. pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple to merge only the specified range of pages from the source document into the output document. Can also be a list of pages to merge. import_outline: You may prevent the source document's outline (collection of outline items, previously referred to as 'bookmarks') from being imported by specifying this as ``False``. """ if position is not None: # deprecated if page_number is None: page_number = position old_term = "position" new_term = "page_number" warnings.warn( ( f"{old_term} is deprecated as an argument and will be " f"removed in pypdf=4.0.0. Use {new_term} instead" ), DeprecationWarning, ) else: raise ValueError( "The argument position of merge is deprecated. Use page_number only." ) if page_number is None: # deprecated # The paremter is only marked as Optional as long as # position is not fully deprecated raise ValueError("page_number may not be None") if fileobj is None: # deprecated # The argument is only Optional due to the deprecated position # argument raise ValueError("fileobj may not be None") stream, encryption_obj = self._create_stream(fileobj) # Create a new PdfReader instance using the stream # (either file or BytesIO or StringIO) created above reader = PdfReader(stream, strict=self.strict) # type: ignore[arg-type] self.inputs.append((stream, reader)) if encryption_obj is not None: reader._encryption = encryption_obj # Find the range of pages to merge. if pages is None: pages = (0, len(reader.pages)) elif isinstance(pages, PageRange): pages = pages.indices(len(reader.pages)) elif isinstance(pages, list): pass elif not isinstance(pages, tuple): raise TypeError('"pages" must be a tuple of (start, stop[, step])') srcpages = [] outline = [] if import_outline: outline = reader.outline outline = self._trim_outline(reader, outline, pages) if outline_item: outline_item_typ = OutlineItem( TextStringObject(outline_item), NumberObject(self.id_count), Fit.fit(), ) self.outline += [outline_item_typ, outline] # type: ignore else: self.outline += outline dests = reader.named_destinations trimmed_dests = self._trim_dests(reader, dests, pages) self.named_dests += trimmed_dests # Gather all the pages that are going to be merged for i in range(*pages): page = reader.pages[i] id = self.id_count self.id_count += 1 mp = _MergedPage(page, reader, id) srcpages.append(mp) self._associate_dests_to_pages(srcpages) self._associate_outline_items_to_pages(srcpages) # Slice to insert the pages at the specified page_number self.pages[page_number:page_number] = srcpages
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L135-L248
39
[ 57, 58, 59, 60, 61, 62, 63, 64, 65, 66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, 79, 80, 81, 82, 83, 84, 85, 90, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113 ]
53.061224
[]
0
false
95.477387
114
13
100
21
def merge( self, page_number: Optional[int] = None, fileobj: Union[None, Path, StrByteType, PdfReader] = None, outline_item: Optional[str] = None, pages: Optional[PageRangeSpec] = None, import_outline: bool = True, position: Optional[int] = None, # deprecated ) -> None: if position is not None: # deprecated if page_number is None: page_number = position old_term = "position" new_term = "page_number" warnings.warn( ( f"{old_term} is deprecated as an argument and will be " f"removed in pypdf=4.0.0. Use {new_term} instead" ), DeprecationWarning, ) else: raise ValueError( "The argument position of merge is deprecated. Use page_number only." ) if page_number is None: # deprecated # The paremter is only marked as Optional as long as # position is not fully deprecated raise ValueError("page_number may not be None") if fileobj is None: # deprecated # The argument is only Optional due to the deprecated position # argument raise ValueError("fileobj may not be None") stream, encryption_obj = self._create_stream(fileobj) # Create a new PdfReader instance using the stream # (either file or BytesIO or StringIO) created above reader = PdfReader(stream, strict=self.strict) # type: ignore[arg-type] self.inputs.append((stream, reader)) if encryption_obj is not None: reader._encryption = encryption_obj # Find the range of pages to merge. if pages is None: pages = (0, len(reader.pages)) elif isinstance(pages, PageRange): pages = pages.indices(len(reader.pages)) elif isinstance(pages, list): pass elif not isinstance(pages, tuple): raise TypeError('"pages" must be a tuple of (start, stop[, step])') srcpages = [] outline = [] if import_outline: outline = reader.outline outline = self._trim_outline(reader, outline, pages) if outline_item: outline_item_typ = OutlineItem( TextStringObject(outline_item), NumberObject(self.id_count), Fit.fit(), ) self.outline += [outline_item_typ, outline] # type: ignore else: self.outline += outline dests = reader.named_destinations trimmed_dests = self._trim_dests(reader, dests, pages) self.named_dests += trimmed_dests # Gather all the pages that are going to be merged for i in range(*pages): page = reader.pages[i] id = self.id_count self.id_count += 1 mp = _MergedPage(page, reader, id) srcpages.append(mp) self._associate_dests_to_pages(srcpages) self._associate_outline_items_to_pages(srcpages) # Slice to insert the pages at the specified page_number self.pages[page_number:page_number] = srcpages
24,433
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._create_stream
( self, fileobj: Union[Path, StrByteType, PdfReader] )
return stream, encryption_obj
250
283
def _create_stream( self, fileobj: Union[Path, StrByteType, PdfReader] ) -> Tuple[IOBase, Optional[Encryption]]: # If the fileobj parameter is a string, assume it is a path # and create a file object at that location. If it is a file, # copy the file's contents into a BytesIO stream object; if # it is a PdfReader, copy that reader's stream into a # BytesIO stream. # If fileobj is none of the above types, it is not modified encryption_obj = None stream: IOBase if isinstance(fileobj, (str, Path)): stream = FileIO(fileobj, "rb") elif isinstance(fileobj, PdfReader): if fileobj._encryption: encryption_obj = fileobj._encryption orig_tell = fileobj.stream.tell() fileobj.stream.seek(0) stream = BytesIO(fileobj.stream.read()) # reset the stream to its original location fileobj.stream.seek(orig_tell) elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"): fileobj.seek(0) filecontent = fileobj.read() stream = BytesIO(filecontent) else: raise NotImplementedError( "PdfMerger.merge requires an object that PdfReader can parse. " "Typically, that is a Path or a string representing a Path, " "a file object, or an object implementing .seek and .read. " "Passing a PdfReader directly works as well." ) return stream, encryption_obj
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L250-L283
39
[ 0, 8, 9, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 33 ]
57.575758
[]
0
false
95.477387
34
6
100
0
def _create_stream( self, fileobj: Union[Path, StrByteType, PdfReader] ) -> Tuple[IOBase, Optional[Encryption]]: # If the fileobj parameter is a string, assume it is a path # and create a file object at that location. If it is a file, # copy the file's contents into a BytesIO stream object; if # it is a PdfReader, copy that reader's stream into a # BytesIO stream. # If fileobj is none of the above types, it is not modified encryption_obj = None stream: IOBase if isinstance(fileobj, (str, Path)): stream = FileIO(fileobj, "rb") elif isinstance(fileobj, PdfReader): if fileobj._encryption: encryption_obj = fileobj._encryption orig_tell = fileobj.stream.tell() fileobj.stream.seek(0) stream = BytesIO(fileobj.stream.read()) # reset the stream to its original location fileobj.stream.seek(orig_tell) elif hasattr(fileobj, "seek") and hasattr(fileobj, "read"): fileobj.seek(0) filecontent = fileobj.read() stream = BytesIO(filecontent) else: raise NotImplementedError( "PdfMerger.merge requires an object that PdfReader can parse. " "Typically, that is a Path or a string representing a Path, " "a file object, or an object implementing .seek and .read. " "Passing a PdfReader directly works as well." ) return stream, encryption_obj
24,434
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.append
( self, fileobj: Union[StrByteType, PdfReader, Path], outline_item: Optional[str] = None, pages: Union[ None, PageRange, Tuple[int, int], Tuple[int, int, int], List[int] ] = None, import_outline: bool = True, )
Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate all pages onto the end of the file instead of specifying a position. Args: fileobj: A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file. outline_item: Optionally, you may specify an outline item (previously referred to as a 'bookmark') to be applied at the beginning of the included file by supplying the text of the outline item. pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple to merge only the specified range of pages from the source document into the output document. Can also be a list of pages to append. import_outline: You may prevent the source document's outline (collection of outline items, previously referred to as 'bookmarks') from being imported by specifying this as ``False``.
Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate all pages onto the end of the file instead of specifying a position.
286
316
def append( self, fileobj: Union[StrByteType, PdfReader, Path], outline_item: Optional[str] = None, pages: Union[ None, PageRange, Tuple[int, int], Tuple[int, int, int], List[int] ] = None, import_outline: bool = True, ) -> None: """ Identical to the :meth:`merge()<merge>` method, but assumes you want to concatenate all pages onto the end of the file instead of specifying a position. Args: fileobj: A File Object or an object that supports the standard read and seek methods similar to a File Object. Could also be a string representing a path to a PDF file. outline_item: Optionally, you may specify an outline item (previously referred to as a 'bookmark') to be applied at the beginning of the included file by supplying the text of the outline item. pages: can be a :class:`PageRange<pypdf.pagerange.PageRange>` or a ``(start, stop[, step])`` tuple to merge only the specified range of pages from the source document into the output document. Can also be a list of pages to append. import_outline: You may prevent the source document's outline (collection of outline items, previously referred to as 'bookmarks') from being imported by specifying this as ``False``. """ self.merge(len(self.pages), fileobj, outline_item, pages, import_outline)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L286-L316
39
[ 0, 29, 30 ]
9.677419
[]
0
false
95.477387
31
1
100
19
def append( self, fileobj: Union[StrByteType, PdfReader, Path], outline_item: Optional[str] = None, pages: Union[ None, PageRange, Tuple[int, int], Tuple[int, int, int], List[int] ] = None, import_outline: bool = True, ) -> None: self.merge(len(self.pages), fileobj, outline_item, pages, import_outline)
24,435
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.write
(self, fileobj: Union[Path, StrByteType])
Write all data that has been merged to the given output file. Args: fileobj: Output file. Can be a filename or any kind of file-like object.
Write all data that has been merged to the given output file.
318
349
def write(self, fileobj: Union[Path, StrByteType]) -> None: """ Write all data that has been merged to the given output file. Args: fileobj: Output file. Can be a filename or any kind of file-like object. """ if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) # Add pages to the PdfWriter # The commented out line below was replaced with the two lines below it # to allow PdfMerger to work with PyPdf 1.13 for page in self.pages: self.output.add_page(page.pagedata) pages_obj = cast(Dict[str, Any], self.output._pages.get_object()) page.out_pagedata = self.output.get_reference( pages_obj[PA.KIDS][-1].get_object() ) # idnum = self.output._objects.index(self.output._pages.get_object()[PA.KIDS][-1].get_object()) + 1 # page.out_pagedata = IndirectObject(idnum, 0, self.output) # Once all pages are added, create outline items to point at those pages self._write_dests() self._write_outline() # Write the output to the file my_file, ret_fileobj = self.output.write(fileobj) if my_file: ret_fileobj.close()
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L318-L349
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31 ]
100
[]
0
true
95.477387
32
4
100
5
def write(self, fileobj: Union[Path, StrByteType]) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) # Add pages to the PdfWriter # The commented out line below was replaced with the two lines below it # to allow PdfMerger to work with PyPdf 1.13 for page in self.pages: self.output.add_page(page.pagedata) pages_obj = cast(Dict[str, Any], self.output._pages.get_object()) page.out_pagedata = self.output.get_reference( pages_obj[PA.KIDS][-1].get_object() ) # idnum = self.output._objects.index(self.output._pages.get_object()[PA.KIDS][-1].get_object()) + 1 # page.out_pagedata = IndirectObject(idnum, 0, self.output) # Once all pages are added, create outline items to point at those pages self._write_dests() self._write_outline() # Write the output to the file my_file, ret_fileobj = self.output.write(fileobj) if my_file: ret_fileobj.close()
24,436
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.close
(self)
Shut all file descriptors (input and output) and clear all memory usage.
Shut all file descriptors (input and output) and clear all memory usage.
351
358
def close(self) -> None: """Shut all file descriptors (input and output) and clear all memory usage.""" self.pages = [] for fo, _reader in self.inputs: fo.close() self.inputs = [] self.output = None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L351-L358
39
[ 0, 1, 2, 3, 4, 5, 6, 7 ]
100
[]
0
true
95.477387
8
2
100
1
def close(self) -> None: self.pages = [] for fo, _reader in self.inputs: fo.close() self.inputs = [] self.output = None
24,437
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.add_metadata
(self, infos: Dict[str, Any])
Add custom metadata to the output. Args: infos: a Python dictionary where each key is a field and each value is your new metadata. An example is ``{'/Title': 'My title'}``
Add custom metadata to the output.
360
371
def add_metadata(self, infos: Dict[str, Any]) -> None: """ Add custom metadata to the output. Args: infos: a Python dictionary where each key is a field and each value is your new metadata. An example is ``{'/Title': 'My title'}`` """ if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output.add_metadata(infos)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L360-L371
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 ]
100
[]
0
true
95.477387
12
2
100
6
def add_metadata(self, infos: Dict[str, Any]) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output.add_metadata(infos)
24,438
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.addMetadata
(self, infos: Dict[str, Any])
.. deprecated:: 1.28.0 Use :meth:`add_metadata` instead.
.. deprecated:: 1.28.0
373
380
def addMetadata(self, infos: Dict[str, Any]) -> None: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`add_metadata` instead. """ deprecation_with_replacement("addMetadata", "add_metadata") self.add_metadata(infos)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L373-L380
39
[]
0
[]
0
false
95.477387
8
1
100
3
def addMetadata(self, infos: Dict[str, Any]) -> None: # deprecated deprecation_with_replacement("addMetadata", "add_metadata") self.add_metadata(infos)
24,439
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.setPageLayout
(self, layout: LayoutType)
.. deprecated:: 1.28.0 Use :meth:`set_page_layout` instead.
.. deprecated:: 1.28.0
382
389
def setPageLayout(self, layout: LayoutType) -> None: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`set_page_layout` instead. """ deprecation_with_replacement("setPageLayout", "set_page_layout") self.set_page_layout(layout)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L382-L389
39
[]
0
[]
0
false
95.477387
8
1
100
3
def setPageLayout(self, layout: LayoutType) -> None: # deprecated deprecation_with_replacement("setPageLayout", "set_page_layout") self.set_page_layout(layout)
24,440
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.set_page_layout
(self, layout: LayoutType)
Set the page layout. Args: layout: The page layout to be used .. list-table:: Valid ``layout`` arguments :widths: 50 200 * - /NoLayout - Layout explicitly not specified * - /SinglePage - Show one page at a time * - /OneColumn - Show one column at a time * - /TwoColumnLeft - Show pages in two columns, odd-numbered pages on the left * - /TwoColumnRight - Show pages in two columns, odd-numbered pages on the right * - /TwoPageLeft - Show two pages at a time, odd-numbered pages on the left * - /TwoPageRight - Show two pages at a time, odd-numbered pages on the right
Set the page layout.
391
418
def set_page_layout(self, layout: LayoutType) -> None: """ Set the page layout. Args: layout: The page layout to be used .. list-table:: Valid ``layout`` arguments :widths: 50 200 * - /NoLayout - Layout explicitly not specified * - /SinglePage - Show one page at a time * - /OneColumn - Show one column at a time * - /TwoColumnLeft - Show pages in two columns, odd-numbered pages on the left * - /TwoColumnRight - Show pages in two columns, odd-numbered pages on the right * - /TwoPageLeft - Show two pages at a time, odd-numbered pages on the left * - /TwoPageRight - Show two pages at a time, odd-numbered pages on the right """ if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output._set_page_layout(layout)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L391-L418
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27 ]
100
[]
0
true
95.477387
28
2
100
22
def set_page_layout(self, layout: LayoutType) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output._set_page_layout(layout)
24,441
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.setPageMode
(self, mode: PagemodeType)
.. deprecated:: 1.28.0 Use :meth:`set_page_mode` instead.
.. deprecated:: 1.28.0
420
427
def setPageMode(self, mode: PagemodeType) -> None: # deprecated """ .. deprecated:: 1.28.0 Use :meth:`set_page_mode` instead. """ deprecation_with_replacement("setPageMode", "set_page_mode", "3.0.0") self.set_page_mode(mode)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L420-L427
39
[]
0
[]
0
false
95.477387
8
1
100
3
def setPageMode(self, mode: PagemodeType) -> None: # deprecated deprecation_with_replacement("setPageMode", "set_page_mode", "3.0.0") self.set_page_mode(mode)
24,442
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.set_page_mode
(self, mode: PagemodeType)
Set the page mode. Args: mode: The page mode to use. .. list-table:: Valid ``mode`` arguments :widths: 50 200 * - /UseNone - Do not show outline or thumbnails panels * - /UseOutlines - Show outline (aka bookmarks) panel * - /UseThumbs - Show page thumbnails panel * - /FullScreen - Fullscreen view * - /UseOC - Show Optional Content Group (OCG) panel * - /UseAttachments - Show attachments panel
Set the page mode.
429
454
def set_page_mode(self, mode: PagemodeType) -> None: """ Set the page mode. Args: mode: The page mode to use. .. list-table:: Valid ``mode`` arguments :widths: 50 200 * - /UseNone - Do not show outline or thumbnails panels * - /UseOutlines - Show outline (aka bookmarks) panel * - /UseThumbs - Show page thumbnails panel * - /FullScreen - Fullscreen view * - /UseOC - Show Optional Content Group (OCG) panel * - /UseAttachments - Show attachments panel """ if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output.set_page_mode(mode)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L429-L454
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
100
[]
0
true
95.477387
26
2
100
20
def set_page_mode(self, mode: PagemodeType) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) self.output.set_page_mode(mode)
24,443
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._trim_dests
( self, pdf: PdfReader, dests: Dict[str, Dict[str, Any]], pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], )
return new_dests
Remove named destinations that are not a part of the specified page set. Args: pdf: dests: pages:
Remove named destinations that are not a part of the specified page set.
456
479
def _trim_dests( self, pdf: PdfReader, dests: Dict[str, Dict[str, Any]], pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], ) -> List[Dict[str, Any]]: """ Remove named destinations that are not a part of the specified page set. Args: pdf: dests: pages: """ new_dests = [] lst = pages if isinstance(pages, list) else list(range(*pages)) for key, obj in dests.items(): for j in lst: if pdf.pages[j].get_object() == obj["/Page"].get_object(): obj[NameObject("/Page")] = obj["/Page"].get_object() assert str_(key) == str_(obj["/Title"]) new_dests.append(obj) break return new_dests
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L456-L479
39
[ 0, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23 ]
50
[]
0
false
95.477387
24
5
100
6
def _trim_dests( self, pdf: PdfReader, dests: Dict[str, Dict[str, Any]], pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], ) -> List[Dict[str, Any]]: new_dests = [] lst = pages if isinstance(pages, list) else list(range(*pages)) for key, obj in dests.items(): for j in lst: if pdf.pages[j].get_object() == obj["/Page"].get_object(): obj[NameObject("/Page")] = obj["/Page"].get_object() assert str_(key) == str_(obj["/Title"]) new_dests.append(obj) break return new_dests
24,444
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._trim_outline
( self, pdf: PdfReader, outline: OutlineType, pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], )
return new_outline
Remove outline item entries that are not a part of the specified page set. Args: pdf: outline: pages: Returns: An outline type
Remove outline item entries that are not a part of the specified page set.
481
520
def _trim_outline( self, pdf: PdfReader, outline: OutlineType, pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], ) -> OutlineType: """ Remove outline item entries that are not a part of the specified page set. Args: pdf: outline: pages: Returns: An outline type """ new_outline = [] prev_header_added = True lst = pages if isinstance(pages, list) else list(range(*pages)) for i, outline_item in enumerate(outline): if isinstance(outline_item, list): sub = self._trim_outline(pdf, outline_item, lst) # type: ignore if sub: if not prev_header_added: new_outline.append(outline[i - 1]) new_outline.append(sub) # type: ignore else: prev_header_added = False for j in lst: if outline_item["/Page"] is None: continue if pdf.pages[j].get_object() == outline_item["/Page"].get_object(): outline_item[NameObject("/Page")] = outline_item[ "/Page" ].get_object() new_outline.append(outline_item) prev_header_added = True break return new_outline
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L481-L520
39
[ 0, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39 ]
62.5
[]
0
false
95.477387
40
8
100
9
def _trim_outline( self, pdf: PdfReader, outline: OutlineType, pages: Union[Tuple[int, int], Tuple[int, int, int], List[int]], ) -> OutlineType: new_outline = [] prev_header_added = True lst = pages if isinstance(pages, list) else list(range(*pages)) for i, outline_item in enumerate(outline): if isinstance(outline_item, list): sub = self._trim_outline(pdf, outline_item, lst) # type: ignore if sub: if not prev_header_added: new_outline.append(outline[i - 1]) new_outline.append(sub) # type: ignore else: prev_header_added = False for j in lst: if outline_item["/Page"] is None: continue if pdf.pages[j].get_object() == outline_item["/Page"].get_object(): outline_item[NameObject("/Page")] = outline_item[ "/Page" ].get_object() new_outline.append(outline_item) prev_header_added = True break return new_outline
24,445
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._write_dests
(self)
522
534
def _write_dests(self) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) for named_dest in self.named_dests: pageno = None if "/Page" in named_dest: for pageno, page in enumerate(self.pages): # noqa: B007 if page.id == named_dest["/Page"]: named_dest[NameObject("/Page")] = page.out_pagedata break if pageno is not None: self.output.add_named_destination_object(named_dest)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L522-L534
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
100
[]
0
true
95.477387
13
7
100
0
def _write_dests(self) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) for named_dest in self.named_dests: pageno = None if "/Page" in named_dest: for pageno, page in enumerate(self.pages): # noqa: B007 if page.id == named_dest["/Page"]: named_dest[NameObject("/Page")] = page.out_pagedata break if pageno is not None: self.output.add_named_destination_object(named_dest)
24,446
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._write_outline
( self, outline: Optional[Iterable[OutlineItem]] = None, parent: Optional[TreeObject] = None, )
537
562
def _write_outline( self, outline: Optional[Iterable[OutlineItem]] = None, parent: Optional[TreeObject] = None, ) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) if outline is None: outline = self.outline # type: ignore assert outline is not None, "hint for mypy" # TODO: is that true? last_added = None for outline_item in outline: if isinstance(outline_item, list): self._write_outline(outline_item, last_added) continue page_no = None if "/Page" in outline_item: for page_no, page in enumerate(self.pages): # noqa: B007 if page.id == outline_item["/Page"]: self._write_outline_item_on_page(outline_item, page) break if page_no is not None: del outline_item["/Page"], outline_item["/Type"] last_added = self.output.add_outline_item_dict(outline_item, parent)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L537-L562
39
[ 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25 ]
84.615385
[]
0
false
95.477387
26
10
100
0
def _write_outline( self, outline: Optional[Iterable[OutlineItem]] = None, parent: Optional[TreeObject] = None, ) -> None: if self.output is None: raise RuntimeError(ERR_CLOSED_WRITER) if outline is None: outline = self.outline # type: ignore assert outline is not None, "hint for mypy" # TODO: is that true? last_added = None for outline_item in outline: if isinstance(outline_item, list): self._write_outline(outline_item, last_added) continue page_no = None if "/Page" in outline_item: for page_no, page in enumerate(self.pages): # noqa: B007 if page.id == outline_item["/Page"]: self._write_outline_item_on_page(outline_item, page) break if page_no is not None: del outline_item["/Page"], outline_item["/Type"] last_added = self.output.add_outline_item_dict(outline_item, parent)
24,447
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._write_outline_item_on_page
( self, outline_item: Union[OutlineItem, Destination], page: _MergedPage )
565
597
def _write_outline_item_on_page( self, outline_item: Union[OutlineItem, Destination], page: _MergedPage ) -> None: oi_type = cast(str, outline_item["/Type"]) args = [NumberObject(page.id), NameObject(oi_type)] fit2arg_keys: Dict[str, Tuple[str, ...]] = { TypFitArguments.FIT_H: (TypArguments.TOP,), TypFitArguments.FIT_BH: (TypArguments.TOP,), TypFitArguments.FIT_V: (TypArguments.LEFT,), TypFitArguments.FIT_BV: (TypArguments.LEFT,), TypFitArguments.XYZ: (TypArguments.LEFT, TypArguments.TOP, "/Zoom"), TypFitArguments.FIT_R: ( TypArguments.LEFT, TypArguments.BOTTOM, TypArguments.RIGHT, TypArguments.TOP, ), } for arg_key in fit2arg_keys.get(oi_type, tuple()): if arg_key in outline_item and not isinstance( outline_item[arg_key], NullObject ): args.append(FloatObject(outline_item[arg_key])) else: args.append(FloatObject(0)) del outline_item[arg_key] outline_item[NameObject("/A")] = DictionaryObject( { NameObject(GoToActionArguments.S): NameObject("/GoTo"), NameObject(GoToActionArguments.D): ArrayObject(args), } )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L565-L597
39
[ 0, 3, 4, 5, 18, 19, 22, 24, 25, 26, 27 ]
33.333333
[]
0
false
95.477387
33
4
100
0
def _write_outline_item_on_page( self, outline_item: Union[OutlineItem, Destination], page: _MergedPage ) -> None: oi_type = cast(str, outline_item["/Type"]) args = [NumberObject(page.id), NameObject(oi_type)] fit2arg_keys: Dict[str, Tuple[str, ...]] = { TypFitArguments.FIT_H: (TypArguments.TOP,), TypFitArguments.FIT_BH: (TypArguments.TOP,), TypFitArguments.FIT_V: (TypArguments.LEFT,), TypFitArguments.FIT_BV: (TypArguments.LEFT,), TypFitArguments.XYZ: (TypArguments.LEFT, TypArguments.TOP, "/Zoom"), TypFitArguments.FIT_R: ( TypArguments.LEFT, TypArguments.BOTTOM, TypArguments.RIGHT, TypArguments.TOP, ), } for arg_key in fit2arg_keys.get(oi_type, tuple()): if arg_key in outline_item and not isinstance( outline_item[arg_key], NullObject ): args.append(FloatObject(outline_item[arg_key])) else: args.append(FloatObject(0)) del outline_item[arg_key] outline_item[NameObject("/A")] = DictionaryObject( { NameObject(GoToActionArguments.S): NameObject("/GoTo"), NameObject(GoToActionArguments.D): ArrayObject(args), } )
24,448
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._associate_dests_to_pages
(self, pages: List[_MergedPage])
599
615
def _associate_dests_to_pages(self, pages: List[_MergedPage]) -> None: for named_dest in self.named_dests: pageno = None np = named_dest["/Page"] if isinstance(np, NumberObject): continue for page in pages: if np.get_object() == page.pagedata.get_object(): pageno = page.id if pageno is None: raise ValueError( f"Unresolved named destination '{named_dest['/Title']}'" ) named_dest[NameObject("/Page")] = NumberObject(pageno)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L599-L615
39
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 16 ]
82.352941
[ 13 ]
5.882353
false
95.477387
17
6
94.117647
0
def _associate_dests_to_pages(self, pages: List[_MergedPage]) -> None: for named_dest in self.named_dests: pageno = None np = named_dest["/Page"] if isinstance(np, NumberObject): continue for page in pages: if np.get_object() == page.pagedata.get_object(): pageno = page.id if pageno is None: raise ValueError( f"Unresolved named destination '{named_dest['/Title']}'" ) named_dest[NameObject("/Page")] = NumberObject(pageno)
24,449
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger._associate_outline_items_to_pages
( self, pages: List[_MergedPage], outline: Optional[Iterable[OutlineItem]] = None )
618
640
def _associate_outline_items_to_pages( self, pages: List[_MergedPage], outline: Optional[Iterable[OutlineItem]] = None ) -> None: if outline is None: outline = self.outline # type: ignore # TODO: self.bookmarks can be None! assert outline is not None, "hint for mypy" for outline_item in outline: if isinstance(outline_item, list): self._associate_outline_items_to_pages(pages, outline_item) continue pageno = None outline_item_page = outline_item["/Page"] if isinstance(outline_item_page, NumberObject): continue for p in pages: if outline_item_page.get_object() == p.pagedata.get_object(): pageno = p.id if pageno is not None: outline_item[NameObject("/Page")] = NumberObject(pageno)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L618-L640
39
[ 0, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22 ]
91.304348
[]
0
false
95.477387
23
9
100
0
def _associate_outline_items_to_pages( self, pages: List[_MergedPage], outline: Optional[Iterable[OutlineItem]] = None ) -> None: if outline is None: outline = self.outline # type: ignore # TODO: self.bookmarks can be None! assert outline is not None, "hint for mypy" for outline_item in outline: if isinstance(outline_item, list): self._associate_outline_items_to_pages(pages, outline_item) continue pageno = None outline_item_page = outline_item["/Page"] if isinstance(outline_item_page, NumberObject): continue for p in pages: if outline_item_page.get_object() == p.pagedata.get_object(): pageno = p.id if pageno is not None: outline_item[NameObject("/Page")] = NumberObject(pageno)
24,450
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.find_outline_item
( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, )
return None
643
665
def find_outline_item( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, ) -> Optional[List[int]]: if root is None: root = self.outline for i, oi_enum in enumerate(root): if isinstance(oi_enum, list): # oi_enum is still an inner node # (OutlineType, if recursive types were supported by mypy) res = self.find_outline_item(outline_item, oi_enum) # type: ignore if res: return [i] + res elif ( oi_enum == outline_item or cast(Dict[Any, Any], oi_enum["/Title"]) == outline_item ): # we found a leaf node return [i] return None
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L643-L665
39
[ 0, 5, 6, 7, 8, 9, 10, 11, 12, 13, 15, 19, 20, 21, 22 ]
65.217391
[ 14 ]
4.347826
false
95.477387
23
7
95.652174
0
def find_outline_item( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, ) -> Optional[List[int]]: if root is None: root = self.outline for i, oi_enum in enumerate(root): if isinstance(oi_enum, list): # oi_enum is still an inner node # (OutlineType, if recursive types were supported by mypy) res = self.find_outline_item(outline_item, oi_enum) # type: ignore if res: return [i] + res elif ( oi_enum == outline_item or cast(Dict[Any, Any], oi_enum["/Title"]) == outline_item ): # we found a leaf node return [i] return None
24,451
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.find_bookmark
( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, )
return self.find_outline_item(outline_item, root)
.. deprecated:: 2.9.0 Use :meth:`find_outline_item` instead.
.. deprecated:: 2.9.0 Use :meth:`find_outline_item` instead.
668
677
def find_bookmark( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, ) -> Optional[List[int]]: # deprecated """ .. deprecated:: 2.9.0 Use :meth:`find_outline_item` instead. """ return self.find_outline_item(outline_item, root)
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L668-L677
39
[]
0
[]
0
false
95.477387
10
1
100
2
def find_bookmark( self, outline_item: Dict[str, Any], root: Optional[OutlineType] = None, ) -> Optional[List[int]]: # deprecated return self.find_outline_item(outline_item, root)
24,452
py-pdf/pypdf
d942a49074de9fb89ea374cd7f36f6d74a4a3451
pypdf/_merger.py
PdfMerger.add_outline_item
( self, title: str, page_number: Optional[int] = None, parent: Union[None, TreeObject, IndirectObject] = None, color: Optional[Tuple[float, float, float]] = None, bold: bool = False, italic: bool = False, fit: Fit = PAGE_FIT, pagenum: Optional[int] = None, # deprecated )
return writer.add_outline_item( title, page_number, parent, None, color, bold, italic, fit, )
Add an outline item (commonly referred to as a "Bookmark") to this PDF file. Args: title: Title to use for this outline item. page_number: Page number this outline item will point to. parent: A reference to a parent outline item to create nested outline items. color: Color of the outline item's font as a red, green, blue tuple from 0.0 to 1.0 bold: Outline item font is bold italic: Outline item font is italic fit: The fit of the destination page.
Add an outline item (commonly referred to as a "Bookmark") to this PDF file.
679
733
def add_outline_item( self, title: str, page_number: Optional[int] = None, parent: Union[None, TreeObject, IndirectObject] = None, color: Optional[Tuple[float, float, float]] = None, bold: bool = False, italic: bool = False, fit: Fit = PAGE_FIT, pagenum: Optional[int] = None, # deprecated ) -> IndirectObject: """ Add an outline item (commonly referred to as a "Bookmark") to this PDF file. Args: title: Title to use for this outline item. page_number: Page number this outline item will point to. parent: A reference to a parent outline item to create nested outline items. color: Color of the outline item's font as a red, green, blue tuple from 0.0 to 1.0 bold: Outline item font is bold italic: Outline item font is italic fit: The fit of the destination page. """ if page_number is not None and pagenum is not None: raise ValueError( "The argument pagenum of add_outline_item is deprecated. Use page_number only." ) if pagenum is not None: old_term = "pagenum" new_term = "page_number" warnings.warn( ( f"{old_term} is deprecated as an argument and will be " f"removed in pypdf==4.0.0. Use {new_term} instead" ), DeprecationWarning, ) page_number = pagenum if page_number is None: raise ValueError("page_number may not be None") writer = self.output if writer is None: raise RuntimeError(ERR_CLOSED_WRITER) return writer.add_outline_item( title, page_number, parent, None, color, bold, italic, fit, )
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_merger.py#L679-L733
39
[ 24, 25, 26, 27, 28, 29, 40, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54 ]
38.461538
[ 30, 31, 39, 41 ]
7.692308
false
95.477387
55
6
92.307692
12
def add_outline_item( self, title: str, page_number: Optional[int] = None, parent: Union[None, TreeObject, IndirectObject] = None, color: Optional[Tuple[float, float, float]] = None, bold: bool = False, italic: bool = False, fit: Fit = PAGE_FIT, pagenum: Optional[int] = None, # deprecated ) -> IndirectObject: if page_number is not None and pagenum is not None: raise ValueError( "The argument pagenum of add_outline_item is deprecated. Use page_number only." ) if pagenum is not None: old_term = "pagenum" new_term = "page_number" warnings.warn( ( f"{old_term} is deprecated as an argument and will be " f"removed in pypdf==4.0.0. Use {new_term} instead" ), DeprecationWarning, ) page_number = pagenum if page_number is None: raise ValueError("page_number may not be None") writer = self.output if writer is None: raise RuntimeError(ERR_CLOSED_WRITER) return writer.add_outline_item( title, page_number, parent, None, color, bold, italic, fit, )
24,453