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/_writer.py
|
pdf_header
|
(self, new_header: bytes)
| 207 | 208 |
def pdf_header(self, new_header: bytes) -> None:
self._header = new_header
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L207-L208
| 39 |
[
0,
1
] | 100 |
[] | 0 | true | 85.547144 | 2 | 1 | 100 | 0 |
def pdf_header(self, new_header: bytes) -> None:
self._header = new_header
| 24,254 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_add_object
|
(self, obj: PdfObject)
|
return obj.indirect_reference
| 210 | 215 |
def _add_object(self, obj: PdfObject) -> IndirectObject:
if hasattr(obj, "indirect_reference") and obj.indirect_reference.pdf == self: # type: ignore
return obj.indirect_reference # type: ignore
self._objects.append(obj)
obj.indirect_reference = IndirectObject(len(self._objects), 0, self)
return obj.indirect_reference
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L210-L215
| 39 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 85.547144 | 6 | 3 | 100 | 0 |
def _add_object(self, obj: PdfObject) -> IndirectObject:
if hasattr(obj, "indirect_reference") and obj.indirect_reference.pdf == self: # type: ignore
return obj.indirect_reference # type: ignore
self._objects.append(obj)
obj.indirect_reference = IndirectObject(len(self._objects), 0, self)
return obj.indirect_reference
| 24,255 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_object
|
(
self,
indirect_reference: Union[None, int, IndirectObject] = None,
ido: Optional[IndirectObject] = None,
)
|
return self._objects[indirect_reference.idnum - 1]
| 217 | 240 |
def get_object(
self,
indirect_reference: Union[None, int, IndirectObject] = None,
ido: Optional[IndirectObject] = None,
) -> PdfObject:
if ido is not None: # deprecated
if indirect_reference is not None:
raise ValueError(
"Please only set 'indirect_reference'. The 'ido' argument is deprecated."
)
else:
indirect_reference = ido
warnings.warn(
"The parameter 'ido' is depreciated and will be removed in pypdf 4.0.0.",
DeprecationWarning,
)
assert (
indirect_reference is not None
) # the None value is only there to keep the deprecated name
if isinstance(indirect_reference, int):
return self._objects[indirect_reference - 1]
if indirect_reference.pdf != self:
raise ValueError("pdf must be self")
return self._objects[indirect_reference.idnum - 1]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L217-L240
| 39 |
[
0,
19,
20,
21,
22,
23
] | 35.294118 |
[] | 0 | false | 85.547144 | 24 | 6 | 100 | 0 |
def get_object(
self,
indirect_reference: Union[None, int, IndirectObject] = None,
ido: Optional[IndirectObject] = None,
) -> PdfObject:
if ido is not None: # deprecated
if indirect_reference is not None:
raise ValueError(
"Please only set 'indirect_reference'. The 'ido' argument is deprecated."
)
else:
indirect_reference = ido
warnings.warn(
"The parameter 'ido' is depreciated and will be removed in pypdf 4.0.0.",
DeprecationWarning,
)
assert (
indirect_reference is not None
) # the None value is only there to keep the deprecated name
if isinstance(indirect_reference, int):
return self._objects[indirect_reference - 1]
if indirect_reference.pdf != self:
raise ValueError("pdf must be self")
return self._objects[indirect_reference.idnum - 1]
| 24,256 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getObject
|
(self, ido: Union[int, IndirectObject])
|
return self.get_object(ido)
|
.. deprecated:: 1.28.0
Use :meth:`get_object` instead.
|
.. deprecated:: 1.28.0
| 242 | 249 |
def getObject(self, ido: Union[int, IndirectObject]) -> PdfObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`get_object` instead.
"""
deprecation_with_replacement("getObject", "get_object", "3.0.0")
return self.get_object(ido)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L242-L249
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getObject(self, ido: Union[int, IndirectObject]) -> PdfObject: # deprecated
deprecation_with_replacement("getObject", "get_object", "3.0.0")
return self.get_object(ido)
| 24,257 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_add_page
|
(
self,
page: PageObject,
action: Callable[[Any, IndirectObject], None],
excluded_keys: Iterable[str] = (),
)
|
return page
| 251 | 283 |
def _add_page(
self,
page: PageObject,
action: Callable[[Any, IndirectObject], None],
excluded_keys: Iterable[str] = (),
) -> PageObject:
assert cast(str, page[PA.TYPE]) == CO.PAGE
page_org = page
excluded_keys = list(excluded_keys)
excluded_keys += [PA.PARENT, "/StructParents"]
# acrobat does not accept to have two indirect ref pointing on the same page;
# therefore in order to add easily multiple copies of the same page, we need to create a new
# dictionary for the page, however the objects below (including content) is not duplicated
try: # delete an already existing page
del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore
page_org.indirect_reference.idnum # type: ignore
]
except Exception:
pass
page = cast("PageObject", page_org.clone(self, False, excluded_keys))
# page_ind = self._add_object(page)
if page_org.pdf is not None:
other = page_org.pdf.pdf_header
if isinstance(other, str):
other = other.encode() # type: ignore
self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other) # type: ignore
page[NameObject(PA.PARENT)] = self._pages
pages = cast(DictionaryObject, self.get_object(self._pages))
assert page.indirect_reference is not None
action(pages[PA.KIDS], page.indirect_reference)
page_count = cast(int, pages[PA.COUNT])
pages[NameObject(PA.COUNT)] = NumberObject(page_count + 1)
return page
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L251-L283
| 39 |
[
0,
6,
7,
8,
9,
10,
11,
12,
13,
14,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32
] | 78.787879 |
[] | 0 | false | 85.547144 | 33 | 6 | 100 | 0 |
def _add_page(
self,
page: PageObject,
action: Callable[[Any, IndirectObject], None],
excluded_keys: Iterable[str] = (),
) -> PageObject:
assert cast(str, page[PA.TYPE]) == CO.PAGE
page_org = page
excluded_keys = list(excluded_keys)
excluded_keys += [PA.PARENT, "/StructParents"]
# acrobat does not accept to have two indirect ref pointing on the same page;
# therefore in order to add easily multiple copies of the same page, we need to create a new
# dictionary for the page, however the objects below (including content) is not duplicated
try: # delete an already existing page
del self._id_translated[id(page_org.indirect_reference.pdf)][ # type: ignore
page_org.indirect_reference.idnum # type: ignore
]
except Exception:
pass
page = cast("PageObject", page_org.clone(self, False, excluded_keys))
# page_ind = self._add_object(page)
if page_org.pdf is not None:
other = page_org.pdf.pdf_header
if isinstance(other, str):
other = other.encode() # type: ignore
self.pdf_header = _get_max_pdf_version_header(self.pdf_header, other) # type: ignore
page[NameObject(PA.PARENT)] = self._pages
pages = cast(DictionaryObject, self.get_object(self._pages))
assert page.indirect_reference is not None
action(pages[PA.KIDS], page.indirect_reference)
page_count = cast(int, pages[PA.COUNT])
pages[NameObject(PA.COUNT)] = NumberObject(page_count + 1)
return page
| 24,258 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
set_need_appearances_writer
|
(self)
| 285 | 303 |
def set_need_appearances_writer(self) -> None:
# See 12.7.2 and 7.7.2 for more information:
# http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
try:
catalog = self._root_object
# get the AcroForm tree
if CatalogDictionary.ACRO_FORM not in catalog:
self._root_object.update(
{
NameObject(CatalogDictionary.ACRO_FORM): IndirectObject(
len(self._objects), 0, self
)
}
)
need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances)
self._root_object[CatalogDictionary.ACRO_FORM][need_appearances] = BooleanObject(True) # type: ignore
except Exception as exc:
logger.error("set_need_appearances_writer() catch : ", repr(exc))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L285-L303
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
14,
15,
16
] | 57.894737 |
[
17,
18
] | 10.526316 | false | 85.547144 | 19 | 3 | 89.473684 | 0 |
def set_need_appearances_writer(self) -> None:
# See 12.7.2 and 7.7.2 for more information:
# http://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
try:
catalog = self._root_object
# get the AcroForm tree
if CatalogDictionary.ACRO_FORM not in catalog:
self._root_object.update(
{
NameObject(CatalogDictionary.ACRO_FORM): IndirectObject(
len(self._objects), 0, self
)
}
)
need_appearances = NameObject(InteractiveFormDictEntries.NeedAppearances)
self._root_object[CatalogDictionary.ACRO_FORM][need_appearances] = BooleanObject(True) # type: ignore
except Exception as exc:
logger.error("set_need_appearances_writer() catch : ", repr(exc))
| 24,259 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_page
|
(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
)
|
return self._add_page(page, list.append, excluded_keys)
|
Add a page to this PDF file.
Recommended for advanced usage including the adequate excluded_keys
The page is usually acquired from a :class:`PdfReader<pypdf.PdfReader>`
instance.
Args:
page: The page to add to the document. Should be
an instance of :class:`PageObject<pypdf._page.PageObject>`
excluded_keys:
Returns:
The added PageObject.
|
Add a page to this PDF file.
Recommended for advanced usage including the adequate excluded_keys
| 305 | 325 |
def add_page(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
) -> PageObject:
"""
Add a page to this PDF file.
Recommended for advanced usage including the adequate excluded_keys
The page is usually acquired from a :class:`PdfReader<pypdf.PdfReader>`
instance.
Args:
page: The page to add to the document. Should be
an instance of :class:`PageObject<pypdf._page.PageObject>`
excluded_keys:
Returns:
The added PageObject.
"""
return self._add_page(page, list.append, excluded_keys)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L305-L325
| 39 |
[
0,
19,
20
] | 14.285714 |
[] | 0 | false | 85.547144 | 21 | 1 | 100 | 13 |
def add_page(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
) -> PageObject:
return self._add_page(page, list.append, excluded_keys)
| 24,260 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addPage
|
(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
)
|
return self.add_page(page, excluded_keys)
|
.. deprecated:: 1.28.0
Use :meth:`add_page` instead.
|
.. deprecated:: 1.28.0
| 327 | 338 |
def addPage(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
) -> PageObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_page` instead.
"""
deprecation_with_replacement("addPage", "add_page", "3.0.0")
return self.add_page(page, excluded_keys)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L327-L338
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def addPage(
self,
page: PageObject,
excluded_keys: Iterable[str] = (),
) -> PageObject: # deprecated
deprecation_with_replacement("addPage", "add_page", "3.0.0")
return self.add_page(page, excluded_keys)
| 24,261 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
insert_page
|
(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
)
|
return self._add_page(page, lambda kids, p: kids.insert(index, p))
|
Insert a page in this PDF file. The page is usually acquired from a
:class:`PdfReader<pypdf.PdfReader>` instance.
Args:
page: The page to add to the document.
index: Position at which the page will be inserted.
excluded_keys:
Returns:
The added PageObject.
|
Insert a page in this PDF file. The page is usually acquired from a
:class:`PdfReader<pypdf.PdfReader>` instance.
| 340 | 358 |
def insert_page(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
) -> PageObject:
"""
Insert a page in this PDF file. The page is usually acquired from a
:class:`PdfReader<pypdf.PdfReader>` instance.
Args:
page: The page to add to the document.
index: Position at which the page will be inserted.
excluded_keys:
Returns:
The added PageObject.
"""
return self._add_page(page, lambda kids, p: kids.insert(index, p))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L340-L358
| 39 |
[
0,
17,
18
] | 15.789474 |
[] | 0 | false | 85.547144 | 19 | 1 | 100 | 10 |
def insert_page(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
) -> PageObject:
return self._add_page(page, lambda kids, p: kids.insert(index, p))
| 24,262 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
insertPage
|
(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
)
|
return self.insert_page(page, index, excluded_keys)
|
.. deprecated:: 1.28.0
Use :meth:`insert_page` instead.
|
.. deprecated:: 1.28.0
| 360 | 372 |
def insertPage(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
) -> PageObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`insert_page` instead.
"""
deprecation_with_replacement("insertPage", "insert_page", "3.0.0")
return self.insert_page(page, index, excluded_keys)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L360-L372
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 13 | 1 | 100 | 3 |
def insertPage(
self,
page: PageObject,
index: int = 0,
excluded_keys: Iterable[str] = (),
) -> PageObject: # deprecated
deprecation_with_replacement("insertPage", "insert_page", "3.0.0")
return self.insert_page(page, index, excluded_keys)
| 24,263 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_page
|
(
self, page_number: Optional[int] = None, pageNumber: Optional[int] = None
)
|
return cast(PageObject, pages[PA.KIDS][page_number].get_object())
|
Retrieve a page by number from this PDF file.
Args:
page_number: The page number to retrieve
(pages begin at zero)
Returns:
The page at the index given by *page_number*
|
Retrieve a page by number from this PDF file.
| 374 | 398 |
def get_page(
self, page_number: Optional[int] = None, pageNumber: Optional[int] = None
) -> PageObject:
"""
Retrieve a page by number from this PDF file.
Args:
page_number: The page number to retrieve
(pages begin at zero)
Returns:
The page at the index given by *page_number*
"""
if pageNumber is not None: # deprecated
if page_number is not None:
raise ValueError("Please only use the page_number parameter")
deprecate_with_replacement(
"get_page(pageNumber)", "get_page(page_number)", "4.0.0"
)
page_number = pageNumber
if page_number is None and pageNumber is None: # deprecated
raise ValueError("Please specify the page_number")
pages = cast(Dict[str, Any], self.get_object(self._pages))
# TODO: crude hack
return cast(PageObject, pages[PA.KIDS][page_number].get_object())
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L374-L398
| 39 |
[
0,
22,
23,
24
] | 22.222222 |
[] | 0 | false | 85.547144 | 25 | 5 | 100 | 8 |
def get_page(
self, page_number: Optional[int] = None, pageNumber: Optional[int] = None
) -> PageObject:
if pageNumber is not None: # deprecated
if page_number is not None:
raise ValueError("Please only use the page_number parameter")
deprecate_with_replacement(
"get_page(pageNumber)", "get_page(page_number)", "4.0.0"
)
page_number = pageNumber
if page_number is None and pageNumber is None: # deprecated
raise ValueError("Please specify the page_number")
pages = cast(Dict[str, Any], self.get_object(self._pages))
# TODO: crude hack
return cast(PageObject, pages[PA.KIDS][page_number].get_object())
| 24,264 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getPage
|
(self, pageNumber: int)
|
return self.get_page(pageNumber)
|
.. deprecated:: 1.28.0
Use :code:`writer.pages[page_number]` instead.
|
.. deprecated:: 1.28.0
| 400 | 407 |
def getPage(self, pageNumber: int) -> PageObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :code:`writer.pages[page_number]` instead.
"""
deprecation_with_replacement("getPage", "writer.pages[page_number]", "3.0.0")
return self.get_page(pageNumber)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L400-L407
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getPage(self, pageNumber: int) -> PageObject: # deprecated
deprecation_with_replacement("getPage", "writer.pages[page_number]", "3.0.0")
return self.get_page(pageNumber)
| 24,265 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_get_num_pages
|
(self)
|
return int(pages[NameObject("/Count")])
| 409 | 411 |
def _get_num_pages(self) -> int:
pages = cast(Dict[str, Any], self.get_object(self._pages))
return int(pages[NameObject("/Count")])
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L409-L411
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 85.547144 | 3 | 1 | 100 | 0 |
def _get_num_pages(self) -> int:
pages = cast(Dict[str, Any], self.get_object(self._pages))
return int(pages[NameObject("/Count")])
| 24,266 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getNumPages
|
(self)
|
return self._get_num_pages()
|
.. deprecated:: 1.28.0
Use :code:`len(writer.pages)` instead.
|
.. deprecated:: 1.28.0
| 413 | 420 |
def getNumPages(self) -> int: # deprecated
"""
.. deprecated:: 1.28.0
Use :code:`len(writer.pages)` instead.
"""
deprecation_with_replacement("getNumPages", "len(writer.pages)", "3.0.0")
return self._get_num_pages()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L413-L420
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getNumPages(self) -> int: # deprecated
deprecation_with_replacement("getNumPages", "len(writer.pages)", "3.0.0")
return self._get_num_pages()
| 24,267 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
pages
|
(self)
|
return _VirtualList(self._get_num_pages, self.get_page)
|
Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
|
Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`.
| 423 | 425 |
def pages(self) -> List[PageObject]:
"""Property that emulates a list of :class:`PageObject<pypdf._page.PageObject>`."""
return _VirtualList(self._get_num_pages, self.get_page)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L423-L425
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 85.547144 | 3 | 1 | 100 | 1 |
def pages(self) -> List[PageObject]:
return _VirtualList(self._get_num_pages, self.get_page)
| 24,268 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_blank_page
|
(
self, width: Optional[float] = None, height: Optional[float] = None
)
|
return page
|
Append a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
Args:
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default
user space units.
Returns:
The newly appended page
Raises:
PageSizeNotDefinedError: if width and height are not defined
and previous page does not exist.
|
Append a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
| 427 | 449 |
def add_blank_page(
self, width: Optional[float] = None, height: Optional[float] = None
) -> PageObject:
"""
Append a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
Args:
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default
user space units.
Returns:
The newly appended page
Raises:
PageSizeNotDefinedError: if width and height are not defined
and previous page does not exist.
"""
page = PageObject.create_blank_page(self, width, height)
self.add_page(page)
return page
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L427-L449
| 39 |
[
0,
19,
20,
21,
22
] | 21.73913 |
[] | 0 | false | 85.547144 | 23 | 1 | 100 | 15 |
def add_blank_page(
self, width: Optional[float] = None, height: Optional[float] = None
) -> PageObject:
page = PageObject.create_blank_page(self, width, height)
self.add_page(page)
return page
| 24,269 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addBlankPage
|
(
self, width: Optional[float] = None, height: Optional[float] = None
)
|
return self.add_blank_page(width, height)
|
.. deprecated:: 1.28.0
Use :meth:`add_blank_page` instead.
|
.. deprecated:: 1.28.0
| 451 | 460 |
def addBlankPage(
self, width: Optional[float] = None, height: Optional[float] = None
) -> PageObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_blank_page` instead.
"""
deprecation_with_replacement("addBlankPage", "add_blank_page", "3.0.0")
return self.add_blank_page(width, height)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L451-L460
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 10 | 1 | 100 | 3 |
def addBlankPage(
self, width: Optional[float] = None, height: Optional[float] = None
) -> PageObject: # deprecated
deprecation_with_replacement("addBlankPage", "add_blank_page", "3.0.0")
return self.add_blank_page(width, height)
| 24,270 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
insert_blank_page
|
(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
)
|
return page
|
Insert a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
Args:
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default
user space units.
index: Position to add the page.
Returns:
The newly appended page
Raises:
PageSizeNotDefinedError: if width and height are not defined
and previous page does not exist.
|
Insert a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
| 462 | 492 |
def insert_blank_page(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
) -> PageObject:
"""
Insert a blank page to this PDF file and returns it. If no page size
is specified, use the size of the last page.
Args:
width: The width of the new page expressed in default user
space units.
height: The height of the new page expressed in default
user space units.
index: Position to add the page.
Returns:
The newly appended page
Raises:
PageSizeNotDefinedError: if width and height are not defined
and previous page does not exist.
"""
if width is None or height is None and (self._get_num_pages() - 1) >= index:
oldpage = self.pages[index]
width = oldpage.mediabox.width
height = oldpage.mediabox.height
page = PageObject.create_blank_page(self, width, height)
self.insert_page(page, index)
return page
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L462-L492
| 39 |
[
0,
23,
24,
25,
26,
27,
28,
29,
30
] | 29.032258 |
[] | 0 | false | 85.547144 | 31 | 4 | 100 | 16 |
def insert_blank_page(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
) -> PageObject:
if width is None or height is None and (self._get_num_pages() - 1) >= index:
oldpage = self.pages[index]
width = oldpage.mediabox.width
height = oldpage.mediabox.height
page = PageObject.create_blank_page(self, width, height)
self.insert_page(page, index)
return page
| 24,271 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
insertBlankPage
|
(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
)
|
return self.insert_blank_page(width, height, index)
|
.. deprecated:: 1.28.0
Use :meth:`insertBlankPage` instead.
|
.. deprecated:: 1.28.0
| 494 | 506 |
def insertBlankPage(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
) -> PageObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`insertBlankPage` instead.
"""
deprecation_with_replacement("insertBlankPage", "insert_blank_page", "3.0.0")
return self.insert_blank_page(width, height, index)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L494-L506
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 13 | 1 | 100 | 3 |
def insertBlankPage(
self,
width: Optional[decimal.Decimal] = None,
height: Optional[decimal.Decimal] = None,
index: int = 0,
) -> PageObject: # deprecated
deprecation_with_replacement("insertBlankPage", "insert_blank_page", "3.0.0")
return self.insert_blank_page(width, height, index)
| 24,272 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
open_destination
|
(
self,
)
|
Property to access the opening destination (``/OpenAction`` entry in the
PDF catalog).
it returns `None` if the entry does not exist is not set.
|
Property to access the opening destination (``/OpenAction`` entry in the
PDF catalog).
it returns `None` if the entry does not exist is not set.
| 509 | 531 |
def open_destination(
self,
) -> Union[None, Destination, TextStringObject, ByteStringObject]:
"""
Property to access the opening destination (``/OpenAction`` entry in the
PDF catalog).
it returns `None` if the entry does not exist is not set.
"""
if "/OpenAction" not in self._root_object:
return None
oa = self._root_object["/OpenAction"]
if isinstance(oa, (str, bytes)):
return create_string_object(str(oa))
elif isinstance(oa, ArrayObject):
try:
page, typ = oa[0:2] # type: ignore
array = oa[2:]
fit = Fit(typ, tuple(array))
return Destination("OpenAction", page, fit)
except Exception as exc:
raise Exception(f"Invalid Destination {oa}: {exc}")
else:
return None
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L509-L531
| 39 |
[
0,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22
] | 73.913043 |
[] | 0 | false | 85.547144 | 23 | 5 | 100 | 3 |
def open_destination(
self,
) -> Union[None, Destination, TextStringObject, ByteStringObject]:
if "/OpenAction" not in self._root_object:
return None
oa = self._root_object["/OpenAction"]
if isinstance(oa, (str, bytes)):
return create_string_object(str(oa))
elif isinstance(oa, ArrayObject):
try:
page, typ = oa[0:2] # type: ignore
array = oa[2:]
fit = Fit(typ, tuple(array))
return Destination("OpenAction", page, fit)
except Exception as exc:
raise Exception(f"Invalid Destination {oa}: {exc}")
else:
return None
| 24,273 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
open_destination
|
(self, dest: Union[None, str, Destination, PageObject])
| 534 | 551 |
def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None:
if dest is None:
try:
del self._root_object["/OpenAction"]
except KeyError:
pass
elif isinstance(dest, str):
self._root_object[NameObject("/OpenAction")] = TextStringObject(dest)
elif isinstance(dest, Destination):
self._root_object[NameObject("/OpenAction")] = dest.dest_array
elif isinstance(dest, PageObject):
self._root_object[NameObject("/OpenAction")] = Destination(
"Opening",
dest.indirect_reference
if dest.indirect_reference is not None
else NullObject(),
PAGE_FIT,
).dest_array
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L534-L551
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 66.666667 |
[] | 0 | false | 85.547144 | 18 | 6 | 100 | 0 |
def open_destination(self, dest: Union[None, str, Destination, PageObject]) -> None:
if dest is None:
try:
del self._root_object["/OpenAction"]
except KeyError:
pass
elif isinstance(dest, str):
self._root_object[NameObject("/OpenAction")] = TextStringObject(dest)
elif isinstance(dest, Destination):
self._root_object[NameObject("/OpenAction")] = dest.dest_array
elif isinstance(dest, PageObject):
self._root_object[NameObject("/OpenAction")] = Destination(
"Opening",
dest.indirect_reference
if dest.indirect_reference is not None
else NullObject(),
PAGE_FIT,
).dest_array
| 24,274 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_js
|
(self, javascript: str)
|
Add Javascript which will launch upon opening this PDF.
Args:
javascript: Your Javascript.
>>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
# Example: This will launch the print window when the PDF is opened.
|
Add Javascript which will launch upon opening this PDF.
| 553 | 586 |
def add_js(self, javascript: str) -> None:
"""
Add Javascript which will launch upon opening this PDF.
Args:
javascript: Your Javascript.
>>> output.add_js("this.print({bUI:true,bSilent:false,bShrinkToFit:true});")
# Example: This will launch the print window when the PDF is opened.
"""
# Names / JavaScript prefered to be able to add multiple scripts
if "/Names" not in self._root_object:
self._root_object[NameObject(CA.NAMES)] = DictionaryObject()
names = cast(DictionaryObject, self._root_object[CA.NAMES])
if "/JavaScript" not in names:
names[NameObject("/JavaScript")] = DictionaryObject(
{NameObject("/Names"): ArrayObject()}
)
# cast(DictionaryObject, names[NameObject("/JavaScript")])[NameObject("/Names")] = ArrayObject()
js_list = cast(
ArrayObject, cast(DictionaryObject, names["/JavaScript"])["/Names"]
)
js = DictionaryObject()
js.update(
{
NameObject(PA.TYPE): NameObject("/Action"),
NameObject("/S"): NameObject("/JavaScript"),
NameObject("/JS"): TextStringObject(f"{javascript}"),
}
)
# We need a name for parameterized javascript in the pdf file, but it can be anything.
js_list.append(create_string_object(str(uuid.uuid4())))
js_list.append(self._add_object(js))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L553-L586
| 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
] | 100 |
[] | 0 | true | 85.547144 | 34 | 3 | 100 | 7 |
def add_js(self, javascript: str) -> None:
# Names / JavaScript prefered to be able to add multiple scripts
if "/Names" not in self._root_object:
self._root_object[NameObject(CA.NAMES)] = DictionaryObject()
names = cast(DictionaryObject, self._root_object[CA.NAMES])
if "/JavaScript" not in names:
names[NameObject("/JavaScript")] = DictionaryObject(
{NameObject("/Names"): ArrayObject()}
)
# cast(DictionaryObject, names[NameObject("/JavaScript")])[NameObject("/Names")] = ArrayObject()
js_list = cast(
ArrayObject, cast(DictionaryObject, names["/JavaScript"])["/Names"]
)
js = DictionaryObject()
js.update(
{
NameObject(PA.TYPE): NameObject("/Action"),
NameObject("/S"): NameObject("/JavaScript"),
NameObject("/JS"): TextStringObject(f"{javascript}"),
}
)
# We need a name for parameterized javascript in the pdf file, but it can be anything.
js_list.append(create_string_object(str(uuid.uuid4())))
js_list.append(self._add_object(js))
| 24,275 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addJS
|
(self, javascript: str)
|
return self.add_js(javascript)
|
.. deprecated:: 1.28.0
Use :meth:`add_js` instead.
|
.. deprecated:: 1.28.0
| 588 | 595 |
def addJS(self, javascript: str) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_js` instead.
"""
deprecation_with_replacement("addJS", "add_js", "3.0.0")
return self.add_js(javascript)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L588-L595
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def addJS(self, javascript: str) -> None: # deprecated
deprecation_with_replacement("addJS", "add_js", "3.0.0")
return self.add_js(javascript)
| 24,276 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_attachment
|
(self, filename: str, data: Union[str, bytes])
|
Embed a file inside the PDF.
Reference:
https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
Section 7.11.3
Args:
filename: The filename to display.
data: The data in the file.
|
Embed a file inside the PDF.
| 597 | 678 |
def add_attachment(self, filename: str, data: Union[str, bytes]) -> None:
"""
Embed a file inside the PDF.
Reference:
https://www.adobe.com/content/dam/Adobe/en/devnet/acrobat/pdfs/PDF32000_2008.pdf
Section 7.11.3
Args:
filename: The filename to display.
data: The data in the file.
"""
# We need three entries:
# * The file's data
# * The /Filespec entry
# * The file's name, which goes in the Catalog
# The entry for the file
# Sample:
# 8 0 obj
# <<
# /Length 12
# /Type /EmbeddedFile
# >>
# stream
# Hello world!
# endstream
# endobj
file_entry = DecodedStreamObject()
file_entry.set_data(data)
file_entry.update({NameObject(PA.TYPE): NameObject("/EmbeddedFile")})
# The Filespec entry
# Sample:
# 7 0 obj
# <<
# /Type /Filespec
# /F (hello.txt)
# /EF << /F 8 0 R >>
# >>
ef_entry = DictionaryObject()
ef_entry.update({NameObject("/F"): file_entry})
filespec = DictionaryObject()
filespec.update(
{
NameObject(PA.TYPE): NameObject("/Filespec"),
NameObject(FileSpecificationDictionaryEntries.F): create_string_object(
filename
), # Perhaps also try TextStringObject
NameObject(FileSpecificationDictionaryEntries.EF): ef_entry,
}
)
# Then create the entry for the root, as it needs a reference to the Filespec
# Sample:
# 1 0 obj
# <<
# /Type /Catalog
# /Outlines 2 0 R
# /Pages 3 0 R
# /Names << /EmbeddedFiles << /Names [(hello.txt) 7 0 R] >> >>
# >>
# endobj
embedded_files_names_dictionary = DictionaryObject()
embedded_files_names_dictionary.update(
{
NameObject(CA.NAMES): ArrayObject(
[create_string_object(filename), filespec]
)
}
)
embedded_files_dictionary = DictionaryObject()
embedded_files_dictionary.update(
{NameObject("/EmbeddedFiles"): embedded_files_names_dictionary}
)
# Update the root
self._root_object.update({NameObject(CA.NAMES): embedded_files_dictionary})
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L597-L678
| 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,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56,
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
] | 100 |
[] | 0 | true | 85.547144 | 82 | 1 | 100 | 9 |
def add_attachment(self, filename: str, data: Union[str, bytes]) -> None:
# We need three entries:
# * The file's data
# * The /Filespec entry
# * The file's name, which goes in the Catalog
# The entry for the file
# Sample:
# 8 0 obj
# <<
# /Length 12
# /Type /EmbeddedFile
# >>
# stream
# Hello world!
# endstream
# endobj
file_entry = DecodedStreamObject()
file_entry.set_data(data)
file_entry.update({NameObject(PA.TYPE): NameObject("/EmbeddedFile")})
# The Filespec entry
# Sample:
# 7 0 obj
# <<
# /Type /Filespec
# /F (hello.txt)
# /EF << /F 8 0 R >>
# >>
ef_entry = DictionaryObject()
ef_entry.update({NameObject("/F"): file_entry})
filespec = DictionaryObject()
filespec.update(
{
NameObject(PA.TYPE): NameObject("/Filespec"),
NameObject(FileSpecificationDictionaryEntries.F): create_string_object(
filename
), # Perhaps also try TextStringObject
NameObject(FileSpecificationDictionaryEntries.EF): ef_entry,
}
)
# Then create the entry for the root, as it needs a reference to the Filespec
# Sample:
# 1 0 obj
# <<
# /Type /Catalog
# /Outlines 2 0 R
# /Pages 3 0 R
# /Names << /EmbeddedFiles << /Names [(hello.txt) 7 0 R] >> >>
# >>
# endobj
embedded_files_names_dictionary = DictionaryObject()
embedded_files_names_dictionary.update(
{
NameObject(CA.NAMES): ArrayObject(
[create_string_object(filename), filespec]
)
}
)
embedded_files_dictionary = DictionaryObject()
embedded_files_dictionary.update(
{NameObject("/EmbeddedFiles"): embedded_files_names_dictionary}
)
# Update the root
self._root_object.update({NameObject(CA.NAMES): embedded_files_dictionary})
| 24,277 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addAttachment
|
(self, fname: str, fdata: Union[str, bytes])
|
return self.add_attachment(fname, fdata)
|
.. deprecated:: 1.28.0
Use :meth:`add_attachment` instead.
|
.. deprecated:: 1.28.0
| 680 | 687 |
def addAttachment(self, fname: str, fdata: Union[str, bytes]) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_attachment` instead.
"""
deprecation_with_replacement("addAttachment", "add_attachment", "3.0.0")
return self.add_attachment(fname, fdata)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L680-L687
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def addAttachment(self, fname: str, fdata: Union[str, bytes]) -> None: # deprecated
deprecation_with_replacement("addAttachment", "add_attachment", "3.0.0")
return self.add_attachment(fname, fdata)
| 24,278 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
append_pages_from_reader
|
(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
)
|
Copy pages from reader to writer. Includes an optional callback parameter
which is invoked after pages are appended to the writer.
`append` should be prefered.
Args:
reader: a PdfReader object from which to copy page
annotations to this writer object. The writer's annots
will then be updated
after_page_append:
Callback function that is invoked after each page is appended to
the writer. Signature includes a reference to the appended page
(delegates to append_pages_from_reader). The single parameter of the
callback is a reference to the page just appended to the document.
|
Copy pages from reader to writer. Includes an optional callback parameter
which is invoked after pages are appended to the writer.
| 689 | 718 |
def append_pages_from_reader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None:
"""
Copy pages from reader to writer. Includes an optional callback parameter
which is invoked after pages are appended to the writer.
`append` should be prefered.
Args:
reader: a PdfReader object from which to copy page
annotations to this writer object. The writer's annots
will then be updated
after_page_append:
Callback function that is invoked after each page is appended to
the writer. Signature includes a reference to the appended page
(delegates to append_pages_from_reader). The single parameter of the
callback is a reference to the page just appended to the document.
"""
# Get page count from writer and reader
reader_num_pages = len(reader.pages)
# Copy pages from reader to writer
for reader_page_number in range(reader_num_pages):
reader_page = reader.pages[reader_page_number]
writer_page = self.add_page(reader_page)
# Trigger callback, pass writer page as parameter
if callable(after_page_append):
after_page_append(writer_page)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L689-L718
| 39 |
[
0,
21,
22,
23,
24,
25,
26,
27,
28,
29
] | 33.333333 |
[] | 0 | false | 85.547144 | 30 | 3 | 100 | 14 |
def append_pages_from_reader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None:
# Get page count from writer and reader
reader_num_pages = len(reader.pages)
# Copy pages from reader to writer
for reader_page_number in range(reader_num_pages):
reader_page = reader.pages[reader_page_number]
writer_page = self.add_page(reader_page)
# Trigger callback, pass writer page as parameter
if callable(after_page_append):
after_page_append(writer_page)
| 24,279 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
appendPagesFromReader
|
(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
)
|
.. deprecated:: 1.28.0
Use :meth:`append_pages_from_reader` instead.
|
.. deprecated:: 1.28.0
| 720 | 733 |
def appendPagesFromReader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`append_pages_from_reader` instead.
"""
deprecation_with_replacement(
"appendPagesFromReader", "append_pages_from_reader", "3.0.0"
)
self.append_pages_from_reader(reader, after_page_append)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L720-L733
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 14 | 1 | 100 | 3 |
def appendPagesFromReader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None: # deprecated
deprecation_with_replacement(
"appendPagesFromReader", "append_pages_from_reader", "3.0.0"
)
self.append_pages_from_reader(reader, after_page_append)
| 24,280 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
update_page_form_field_values
|
(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
)
|
Update the form field values for a given page from a fields dictionary.
Copy field texts and values from fields to page.
If the field links to a parent object, add the information to the parent.
Args:
page: Page reference from PDF writer where the
annotations and field data will be updated.
fields: a Python dictionary of field names (/T) and text
values (/V)
flags: An integer (0 to 7). The first bit sets ReadOnly, the
second bit sets Required, the third bit sets NoExport. See
PDF Reference Table 8.70 for details.
|
Update the form field values for a given page from a fields dictionary.
| 735 | 799 |
def update_page_form_field_values(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
) -> None:
"""
Update the form field values for a given page from a fields dictionary.
Copy field texts and values from fields to page.
If the field links to a parent object, add the information to the parent.
Args:
page: Page reference from PDF writer where the
annotations and field data will be updated.
fields: a Python dictionary of field names (/T) and text
values (/V)
flags: An integer (0 to 7). The first bit sets ReadOnly, the
second bit sets Required, the third bit sets NoExport. See
PDF Reference Table 8.70 for details.
"""
self.set_need_appearances_writer()
# Iterate through pages, update field values
if PG.ANNOTS not in page:
logger_warning("No fields to update on this page", __name__)
return
for j in range(len(page[PG.ANNOTS])): # type: ignore
writer_annot = page[PG.ANNOTS][j].get_object() # type: ignore
# retrieve parent field values, if present
writer_parent_annot = {} # fallback if it's not there
if PG.PARENT in writer_annot:
writer_parent_annot = writer_annot[PG.PARENT]
for field in fields:
if writer_annot.get(FieldDictionaryAttributes.T) == field:
if writer_annot.get(FieldDictionaryAttributes.FT) == "/Btn":
writer_annot.update(
{
NameObject(
AnnotationDictionaryAttributes.AS
): NameObject(fields[field])
}
)
writer_annot.update(
{
NameObject(FieldDictionaryAttributes.V): TextStringObject(
fields[field]
)
}
)
if flags:
writer_annot.update(
{
NameObject(FieldDictionaryAttributes.Ff): NumberObject(
flags
)
}
)
elif writer_parent_annot.get(FieldDictionaryAttributes.T) == field:
writer_parent_annot.update(
{
NameObject(FieldDictionaryAttributes.V): TextStringObject(
fields[field]
)
}
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L735-L799
| 39 |
[
0,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
32,
33,
34,
41,
42,
43,
44,
45,
46,
47,
48,
49,
50,
51,
52,
53,
54,
55,
56
] | 47.692308 |
[
31,
35,
57,
58
] | 6.153846 | false | 85.547144 | 65 | 9 | 93.846154 | 13 |
def update_page_form_field_values(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
) -> None:
self.set_need_appearances_writer()
# Iterate through pages, update field values
if PG.ANNOTS not in page:
logger_warning("No fields to update on this page", __name__)
return
for j in range(len(page[PG.ANNOTS])): # type: ignore
writer_annot = page[PG.ANNOTS][j].get_object() # type: ignore
# retrieve parent field values, if present
writer_parent_annot = {} # fallback if it's not there
if PG.PARENT in writer_annot:
writer_parent_annot = writer_annot[PG.PARENT]
for field in fields:
if writer_annot.get(FieldDictionaryAttributes.T) == field:
if writer_annot.get(FieldDictionaryAttributes.FT) == "/Btn":
writer_annot.update(
{
NameObject(
AnnotationDictionaryAttributes.AS
): NameObject(fields[field])
}
)
writer_annot.update(
{
NameObject(FieldDictionaryAttributes.V): TextStringObject(
fields[field]
)
}
)
if flags:
writer_annot.update(
{
NameObject(FieldDictionaryAttributes.Ff): NumberObject(
flags
)
}
)
elif writer_parent_annot.get(FieldDictionaryAttributes.T) == field:
writer_parent_annot.update(
{
NameObject(FieldDictionaryAttributes.V): TextStringObject(
fields[field]
)
}
)
| 24,281 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
updatePageFormFieldValues
|
(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
)
|
return self.update_page_form_field_values(page, fields, flags)
|
.. deprecated:: 1.28.0
Use :meth:`update_page_form_field_values` instead.
|
.. deprecated:: 1.28.0
| 801 | 815 |
def updatePageFormFieldValues(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`update_page_form_field_values` instead.
"""
deprecation_with_replacement(
"updatePageFormFieldValues", "update_page_form_field_values", "3.0.0"
)
return self.update_page_form_field_values(page, fields, flags)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L801-L815
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 15 | 1 | 100 | 3 |
def updatePageFormFieldValues(
self,
page: PageObject,
fields: Dict[str, Any],
flags: FieldFlag = OPTIONAL_READ_WRITE_FIELD,
) -> None: # deprecated
deprecation_with_replacement(
"updatePageFormFieldValues", "update_page_form_field_values", "3.0.0"
)
return self.update_page_form_field_values(page, fields, flags)
| 24,282 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
clone_reader_document_root
|
(self, reader: PdfReader)
|
Copy the reader document root to the writer and all sub elements,
including pages, threads, outlines,...
For partial insertion, `append` should be considered.
Args:
reader: PdfReader from the document root should be copied.
|
Copy the reader document root to the writer and all sub elements,
including pages, threads, outlines,...
For partial insertion, `append` should be considered.
| 817 | 833 |
def clone_reader_document_root(self, reader: PdfReader) -> None:
"""
Copy the reader document root to the writer and all sub elements,
including pages, threads, outlines,...
For partial insertion, `append` should be considered.
Args:
reader: PdfReader from the document root should be copied.
"""
self._root_object = cast(DictionaryObject, reader.trailer[TK.ROOT].clone(self))
self._root = self._root_object.indirect_reference # type: ignore[assignment]
self._pages = self._root_object.raw_get("/Pages")
self._flatten()
self._root_object[NameObject("/Pages")][ # type: ignore[index]
NameObject("/Kids")
] = self.flattened_pages
del self.flattened_pages
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L817-L833
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16
] | 100 |
[] | 0 | true | 85.547144 | 17 | 1 | 100 | 6 |
def clone_reader_document_root(self, reader: PdfReader) -> None:
self._root_object = cast(DictionaryObject, reader.trailer[TK.ROOT].clone(self))
self._root = self._root_object.indirect_reference # type: ignore[assignment]
self._pages = self._root_object.raw_get("/Pages")
self._flatten()
self._root_object[NameObject("/Pages")][ # type: ignore[index]
NameObject("/Kids")
] = self.flattened_pages
del self.flattened_pages
| 24,283 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
cloneReaderDocumentRoot
|
(self, reader: PdfReader)
|
.. deprecated:: 1.28.0
Use :meth:`clone_reader_document_root` instead.
|
.. deprecated:: 1.28.0
| 835 | 844 |
def cloneReaderDocumentRoot(self, reader: PdfReader) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`clone_reader_document_root` instead.
"""
deprecation_with_replacement(
"cloneReaderDocumentRoot", "clone_reader_document_root", "3.0.0"
)
self.clone_reader_document_root(reader)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L835-L844
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 10 | 1 | 100 | 3 |
def cloneReaderDocumentRoot(self, reader: PdfReader) -> None: # deprecated
deprecation_with_replacement(
"cloneReaderDocumentRoot", "clone_reader_document_root", "3.0.0"
)
self.clone_reader_document_root(reader)
| 24,284 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_flatten
|
(
self,
pages: Union[None, DictionaryObject, PageObject] = None,
inherit: Optional[Dict[str, Any]] = None,
indirect_reference: Optional[IndirectObject] = None,
)
| 846 | 886 |
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:
pages = cast(DictionaryObject, self._root_object["/Pages"])
self.flattened_pages = ArrayObject()
assert pages is not None # hint for mypy
t = "/Pages"
if PA.TYPE in pages:
t = cast(str, pages[PA.TYPE])
if t == "/Pages":
for attr in inheritable_page_attributes:
if attr in pages:
inherit[attr] = pages[attr]
for page in cast(ArrayObject, cast(DictionaryObject, pages)[PA.KIDS]):
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
pages[NameObject("/Parent")] = cast(
IndirectObject, self._root_object.raw_get("/Pages")
)
self.flattened_pages.append(indirect_reference)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L846-L886
| 39 |
[
0,
6,
12,
13,
14,
15,
16,
17,
18,
19,
20,
21,
22,
23,
24,
26,
27,
28,
29,
30,
31,
32,
33,
34,
37,
40
] | 63.414634 |
[
25,
35,
36
] | 7.317073 | false | 85.547144 | 41 | 13 | 92.682927 | 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:
pages = cast(DictionaryObject, self._root_object["/Pages"])
self.flattened_pages = ArrayObject()
assert pages is not None # hint for mypy
t = "/Pages"
if PA.TYPE in pages:
t = cast(str, pages[PA.TYPE])
if t == "/Pages":
for attr in inheritable_page_attributes:
if attr in pages:
inherit[attr] = pages[attr]
for page in cast(ArrayObject, cast(DictionaryObject, pages)[PA.KIDS]):
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
pages[NameObject("/Parent")] = cast(
IndirectObject, self._root_object.raw_get("/Pages")
)
self.flattened_pages.append(indirect_reference)
| 24,285 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
clone_document_from_reader
|
(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
)
|
Create a copy (clone) of a document from a PDF file reader
cloning section '/Root' and '/Info' and '/ID' of the pdf
Args:
reader: PDF file reader instance from which the clone
should be created.
after_page_append:
Callback function that is invoked after each page is appended to
the writer. Signature includes a reference to the appended page
(delegates to append_pages_from_reader). The single parameter of the
callback is a reference to the page just appended to the document.
|
Create a copy (clone) of a document from a PDF file reader
cloning section '/Root' and '/Info' and '/ID' of the pdf
| 888 | 916 |
def clone_document_from_reader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None:
"""
Create a copy (clone) of a document from a PDF file reader
cloning section '/Root' and '/Info' and '/ID' of the pdf
Args:
reader: PDF file reader instance from which the clone
should be created.
after_page_append:
Callback function that is invoked after each page is appended to
the writer. Signature includes a reference to the appended page
(delegates to append_pages_from_reader). The single parameter of the
callback is a reference to the page just appended to the document.
"""
self.clone_reader_document_root(reader)
self._info = reader.trailer[TK.INFO].clone(self).indirect_reference # type: ignore
try:
self._ID = reader.trailer[TK.ID].clone(self) # type: ignore
except KeyError:
pass
if callable(after_page_append):
for page in cast(
ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"]
):
after_page_append(page.get_object())
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L888-L916
| 39 |
[
0,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28
] | 44.827586 |
[] | 0 | false | 85.547144 | 29 | 4 | 100 | 11 |
def clone_document_from_reader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None:
self.clone_reader_document_root(reader)
self._info = reader.trailer[TK.INFO].clone(self).indirect_reference # type: ignore
try:
self._ID = reader.trailer[TK.ID].clone(self) # type: ignore
except KeyError:
pass
if callable(after_page_append):
for page in cast(
ArrayObject, cast(DictionaryObject, self._pages.get_object())["/Kids"]
):
after_page_append(page.get_object())
| 24,286 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
cloneDocumentFromReader
|
(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
)
|
.. deprecated:: 1.28.0
Use :meth:`clone_document_from_reader` instead.
|
.. deprecated:: 1.28.0
| 918 | 931 |
def cloneDocumentFromReader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`clone_document_from_reader` instead.
"""
deprecation_with_replacement(
"cloneDocumentFromReader", "clone_document_from_reader", "3.0.0"
)
self.clone_document_from_reader(reader, after_page_append)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L918-L931
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 14 | 1 | 100 | 3 |
def cloneDocumentFromReader(
self,
reader: PdfReader,
after_page_append: Optional[Callable[[PageObject], None]] = None,
) -> None: # deprecated
deprecation_with_replacement(
"cloneDocumentFromReader", "clone_document_from_reader", "3.0.0"
)
self.clone_document_from_reader(reader, after_page_append)
| 24,287 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
encrypt
|
(
self,
user_password: Optional[str] = None,
owner_password: Optional[str] = None,
use_128bit: bool = True,
permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS,
user_pwd: Optional[str] = None, # deprecated
owner_pwd: Optional[str] = None, # deprecated
)
|
Encrypt this PDF file with the PDF Standard encryption handler.
Args:
user_password: The password which allows for opening
and reading the PDF file with the restrictions provided.
owner_password: The password which allows for
opening the PDF files without any restrictions. By default,
the owner password is the same as the user password.
use_128bit: flag as to whether to use 128bit
encryption. When false, 40bit encryption will be used. By default,
this flag is on.
permissions_flag: permissions as described in
TABLE 3.20 of the PDF 1.7 specification. A bit value of 1 means the
permission is grantend. Hence an integer value of -1 will set all
flags.
Bit position 3 is for printing, 4 is for modifying content, 5 and 6
control annotations, 9 for form fields, 10 for extraction of
text and graphics.
|
Encrypt this PDF file with the PDF Standard encryption handler.
| 933 | 1,026 |
def encrypt(
self,
user_password: Optional[str] = None,
owner_password: Optional[str] = None,
use_128bit: bool = True,
permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS,
user_pwd: Optional[str] = None, # deprecated
owner_pwd: Optional[str] = None, # deprecated
) -> None:
"""
Encrypt this PDF file with the PDF Standard encryption handler.
Args:
user_password: The password which allows for opening
and reading the PDF file with the restrictions provided.
owner_password: The password which allows for
opening the PDF files without any restrictions. By default,
the owner password is the same as the user password.
use_128bit: flag as to whether to use 128bit
encryption. When false, 40bit encryption will be used. By default,
this flag is on.
permissions_flag: permissions as described in
TABLE 3.20 of the PDF 1.7 specification. A bit value of 1 means the
permission is grantend. Hence an integer value of -1 will set all
flags.
Bit position 3 is for printing, 4 is for modifying content, 5 and 6
control annotations, 9 for form fields, 10 for extraction of
text and graphics.
"""
if user_pwd is not None:
if user_password is not None:
raise ValueError(
"Please only set 'user_password'. "
"The 'user_pwd' argument is deprecated."
)
else:
warnings.warn(
"Please use 'user_password' instead of 'user_pwd'. "
"The 'user_pwd' argument is deprecated and "
"will be removed in pypdf 4.0.0."
)
user_password = user_pwd
if user_password is None: # deprecated
# user_password is only Optional for due to the deprecated user_pwd
raise ValueError("user_password may not be None")
if owner_pwd is not None: # deprecated
if owner_password is not None:
raise ValueError(
"The argument owner_pwd of encrypt is deprecated. Use owner_password only."
)
else:
old_term = "owner_pwd"
new_term = "owner_password"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
owner_password = owner_pwd
if owner_password is None:
owner_password = user_password
if use_128bit:
V = 2
rev = 3
keylen = int(128 / 8)
else:
V = 1
rev = 2
keylen = int(40 / 8)
P = permissions_flag
O = ByteStringObject(_alg33(owner_password, user_password, rev, keylen)) # type: ignore[arg-type]
ID_1 = ByteStringObject(md5((repr(time.time())).encode("utf8")).digest())
ID_2 = ByteStringObject(md5((repr(random.random())).encode("utf8")).digest())
self._ID = ArrayObject((ID_1, ID_2))
if rev == 2:
U, key = _alg34(user_password, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_password, rev, keylen, O, P, ID_1, False) # type: ignore[arg-type]
encrypt = DictionaryObject()
encrypt[NameObject(SA.FILTER)] = NameObject("/Standard")
encrypt[NameObject("/V")] = NumberObject(V)
if V == 2:
encrypt[NameObject(SA.LENGTH)] = NumberObject(keylen * 8)
encrypt[NameObject(ED.R)] = NumberObject(rev)
encrypt[NameObject(ED.O)] = ByteStringObject(O)
encrypt[NameObject(ED.U)] = ByteStringObject(U)
encrypt[NameObject(ED.P)] = NumberObject(P)
self._encrypt = self._add_object(encrypt)
self._encrypt_key = key
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L933-L1026
| 39 |
[
28,
29,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74,
75,
76,
77,
78,
79,
80,
81,
82,
83,
84,
85,
86,
87,
88,
89,
90,
91,
92,
93
] | 42.5 |
[
30,
41
] | 2.5 | false | 85.547144 | 94 | 11 | 97.5 | 18 |
def encrypt(
self,
user_password: Optional[str] = None,
owner_password: Optional[str] = None,
use_128bit: bool = True,
permissions_flag: UserAccessPermissions = ALL_DOCUMENT_PERMISSIONS,
user_pwd: Optional[str] = None, # deprecated
owner_pwd: Optional[str] = None, # deprecated
) -> None:
if user_pwd is not None:
if user_password is not None:
raise ValueError(
"Please only set 'user_password'. "
"The 'user_pwd' argument is deprecated."
)
else:
warnings.warn(
"Please use 'user_password' instead of 'user_pwd'. "
"The 'user_pwd' argument is deprecated and "
"will be removed in pypdf 4.0.0."
)
user_password = user_pwd
if user_password is None: # deprecated
# user_password is only Optional for due to the deprecated user_pwd
raise ValueError("user_password may not be None")
if owner_pwd is not None: # deprecated
if owner_password is not None:
raise ValueError(
"The argument owner_pwd of encrypt is deprecated. Use owner_password only."
)
else:
old_term = "owner_pwd"
new_term = "owner_password"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
owner_password = owner_pwd
if owner_password is None:
owner_password = user_password
if use_128bit:
V = 2
rev = 3
keylen = int(128 / 8)
else:
V = 1
rev = 2
keylen = int(40 / 8)
P = permissions_flag
O = ByteStringObject(_alg33(owner_password, user_password, rev, keylen)) # type: ignore[arg-type]
ID_1 = ByteStringObject(md5((repr(time.time())).encode("utf8")).digest())
ID_2 = ByteStringObject(md5((repr(random.random())).encode("utf8")).digest())
self._ID = ArrayObject((ID_1, ID_2))
if rev == 2:
U, key = _alg34(user_password, O, P, ID_1)
else:
assert rev == 3
U, key = _alg35(user_password, rev, keylen, O, P, ID_1, False) # type: ignore[arg-type]
encrypt = DictionaryObject()
encrypt[NameObject(SA.FILTER)] = NameObject("/Standard")
encrypt[NameObject("/V")] = NumberObject(V)
if V == 2:
encrypt[NameObject(SA.LENGTH)] = NumberObject(keylen * 8)
encrypt[NameObject(ED.R)] = NumberObject(rev)
encrypt[NameObject(ED.O)] = ByteStringObject(O)
encrypt[NameObject(ED.U)] = ByteStringObject(U)
encrypt[NameObject(ED.P)] = NumberObject(P)
self._encrypt = self._add_object(encrypt)
self._encrypt_key = key
| 24,288 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
write_stream
|
(self, stream: StreamType)
| 1,028 | 1,052 |
def write_stream(self, stream: StreamType) -> None:
if hasattr(stream, "mode") and "b" not in stream.mode:
logger_warning(
f"File <{stream.name}> to write to is not in binary mode. " # type: ignore
"It may not be written to correctly.",
__name__,
)
if not self._root:
self._root = self._add_object(self._root_object)
# PDF objects sometimes have circular references to their /Page objects
# inside their object tree (for example, annotations). Those will be
# indirect references to objects that we've recreated in this PDF. To
# address this problem, PageObject's store their original object
# reference number, and we add it to the external reference map before
# we sweep for indirect references. This forces self-page-referencing
# trees to reference the correct new object location, rather than
# copying in a new copy of the page object.
self._sweep_indirect_references(self._root)
object_positions = self._write_header(stream)
xref_location = self._write_xref_table(stream, object_positions)
self._write_trailer(stream)
stream.write(b_(f"\nstartxref\n{xref_location}\n%%EOF\n"))
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1028-L1052
| 39 |
[
0,
1,
2,
7,
8,
18,
19,
20,
21,
22,
23,
24
] | 48 |
[
9
] | 4 | false | 85.547144 | 25 | 4 | 96 | 0 |
def write_stream(self, stream: StreamType) -> None:
if hasattr(stream, "mode") and "b" not in stream.mode:
logger_warning(
f"File <{stream.name}> to write to is not in binary mode. " # type: ignore
"It may not be written to correctly.",
__name__,
)
if not self._root:
self._root = self._add_object(self._root_object)
# PDF objects sometimes have circular references to their /Page objects
# inside their object tree (for example, annotations). Those will be
# indirect references to objects that we've recreated in this PDF. To
# address this problem, PageObject's store their original object
# reference number, and we add it to the external reference map before
# we sweep for indirect references. This forces self-page-referencing
# trees to reference the correct new object location, rather than
# copying in a new copy of the page object.
self._sweep_indirect_references(self._root)
object_positions = self._write_header(stream)
xref_location = self._write_xref_table(stream, object_positions)
self._write_trailer(stream)
stream.write(b_(f"\nstartxref\n{xref_location}\n%%EOF\n"))
| 24,289 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
write
|
(self, stream: Union[Path, StrByteType])
|
return my_file, stream
|
Write the collection of pages added to this object out as a PDF file.
Args:
stream: An object to write the file to. The object can support
the write method and the tell method, similar to a file object, or
be a file path, just like the fileobj, just named it stream to keep
existing workflow.
Returns:
A tuple (bool, IO)
|
Write the collection of pages added to this object out as a PDF file.
| 1,054 | 1,082 |
def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO]:
"""
Write the collection of pages added to this object out as a PDF file.
Args:
stream: An object to write the file to. The object can support
the write method and the tell method, similar to a file object, or
be a file path, just like the fileobj, just named it stream to keep
existing workflow.
Returns:
A tuple (bool, IO)
"""
my_file = False
if stream == "":
raise ValueError(f"Output(stream={stream}) is empty.")
if isinstance(stream, (str, Path)):
stream = FileIO(stream, "wb")
self.with_as_usage = True #
my_file = True
self.write_stream(stream)
if self.with_as_usage:
stream.close()
return my_file, stream
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1054-L1082
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
17,
18,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28
] | 96.551724 |
[
16
] | 3.448276 | false | 85.547144 | 29 | 4 | 96.551724 | 10 |
def write(self, stream: Union[Path, StrByteType]) -> Tuple[bool, IO]:
my_file = False
if stream == "":
raise ValueError(f"Output(stream={stream}) is empty.")
if isinstance(stream, (str, Path)):
stream = FileIO(stream, "wb")
self.with_as_usage = True #
my_file = True
self.write_stream(stream)
if self.with_as_usage:
stream.close()
return my_file, stream
| 24,290 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_write_header
|
(self, stream: StreamType)
|
return object_positions
| 1,084 | 1,105 |
def _write_header(self, stream: StreamType) -> List[int]:
object_positions = []
stream.write(self.pdf_header + b"\n")
stream.write(b"%\xE2\xE3\xCF\xD3\n")
for i, obj in enumerate(self._objects):
obj = self._objects[i]
# If the obj is None we can't write anything
if obj is not None:
idnum = i + 1
object_positions.append(stream.tell())
stream.write(b_(str(idnum)) + b" 0 obj\n")
key = None
if hasattr(self, "_encrypt") and idnum != self._encrypt.idnum:
pack1 = struct.pack("<i", i + 1)[:3]
pack2 = struct.pack("<i", 0)[:2]
key = self._encrypt_key + pack1 + pack2
assert len(key) == (len(self._encrypt_key) + 5)
md5_hash = md5(key).digest()
key = md5_hash[: min(16, len(self._encrypt_key) + 5)]
obj.write_to_stream(stream, key)
stream.write(b"\nendobj\n")
return object_positions
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1084-L1105
| 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 | 85.547144 | 22 | 6 | 100 | 0 |
def _write_header(self, stream: StreamType) -> List[int]:
object_positions = []
stream.write(self.pdf_header + b"\n")
stream.write(b"%\xE2\xE3\xCF\xD3\n")
for i, obj in enumerate(self._objects):
obj = self._objects[i]
# If the obj is None we can't write anything
if obj is not None:
idnum = i + 1
object_positions.append(stream.tell())
stream.write(b_(str(idnum)) + b" 0 obj\n")
key = None
if hasattr(self, "_encrypt") and idnum != self._encrypt.idnum:
pack1 = struct.pack("<i", i + 1)[:3]
pack2 = struct.pack("<i", 0)[:2]
key = self._encrypt_key + pack1 + pack2
assert len(key) == (len(self._encrypt_key) + 5)
md5_hash = md5(key).digest()
key = md5_hash[: min(16, len(self._encrypt_key) + 5)]
obj.write_to_stream(stream, key)
stream.write(b"\nendobj\n")
return object_positions
| 24,291 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_write_xref_table
|
(self, stream: StreamType, object_positions: List[int])
|
return xref_location
| 1,107 | 1,114 |
def _write_xref_table(self, stream: StreamType, object_positions: List[int]) -> int:
xref_location = stream.tell()
stream.write(b"xref\n")
stream.write(b_(f"0 {len(self._objects) + 1}\n"))
stream.write(b_(f"{0:0>10} {65535:0>5} f \n"))
for offset in object_positions:
stream.write(b_(f"{offset:0>10} {0:0>5} n \n"))
return xref_location
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1107-L1114
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 85.547144 | 8 | 2 | 100 | 0 |
def _write_xref_table(self, stream: StreamType, object_positions: List[int]) -> int:
xref_location = stream.tell()
stream.write(b"xref\n")
stream.write(b_(f"0 {len(self._objects) + 1}\n"))
stream.write(b_(f"{0:0>10} {65535:0>5} f \n"))
for offset in object_positions:
stream.write(b_(f"{offset:0>10} {0:0>5} n \n"))
return xref_location
| 24,292 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_write_trailer
|
(self, stream: StreamType)
| 1,116 | 1,130 |
def _write_trailer(self, stream: StreamType) -> None:
stream.write(b"trailer\n")
trailer = DictionaryObject()
trailer.update(
{
NameObject(TK.SIZE): NumberObject(len(self._objects) + 1),
NameObject(TK.ROOT): self._root,
NameObject(TK.INFO): self._info,
}
)
if hasattr(self, "_ID"):
trailer[NameObject(TK.ID)] = self._ID
if hasattr(self, "_encrypt"):
trailer[NameObject(TK.ENCRYPT)] = self._encrypt
trailer.write_to_stream(stream, None)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1116-L1130
| 39 |
[
0,
1,
2,
3,
10,
11,
12,
13,
14
] | 60 |
[] | 0 | false | 85.547144 | 15 | 3 | 100 | 0 |
def _write_trailer(self, stream: StreamType) -> None:
stream.write(b"trailer\n")
trailer = DictionaryObject()
trailer.update(
{
NameObject(TK.SIZE): NumberObject(len(self._objects) + 1),
NameObject(TK.ROOT): self._root,
NameObject(TK.INFO): self._info,
}
)
if hasattr(self, "_ID"):
trailer[NameObject(TK.ID)] = self._ID
if hasattr(self, "_encrypt"):
trailer[NameObject(TK.ENCRYPT)] = self._encrypt
trailer.write_to_stream(stream, None)
| 24,293 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
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.
|
Add custom metadata to the output.
| 1,132 | 1,143 |
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.
"""
args = {}
for key, value in list(infos.items()):
args[NameObject(key)] = create_string_object(value)
self.get_object(self._info).update(args)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1132-L1143
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 85.547144 | 12 | 2 | 100 | 5 |
def add_metadata(self, infos: Dict[str, Any]) -> None:
args = {}
for key, value in list(infos.items()):
args[NameObject(key)] = create_string_object(value)
self.get_object(self._info).update(args)
| 24,294 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addMetadata
|
(self, infos: Dict[str, Any])
|
.. deprecated:: 1.28.0
Use :meth:`add_metadata` instead.
|
.. deprecated:: 1.28.0
| 1,145 | 1,152 |
def addMetadata(self, infos: Dict[str, Any]) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_metadata` instead.
"""
deprecation_with_replacement("addMetadata", "add_metadata", "3.0.0")
self.add_metadata(infos)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1145-L1152
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def addMetadata(self, infos: Dict[str, Any]) -> None: # deprecated
deprecation_with_replacement("addMetadata", "add_metadata", "3.0.0")
self.add_metadata(infos)
| 24,295 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_sweep_indirect_references
|
(
self,
root: Union[
ArrayObject,
BooleanObject,
DictionaryObject,
FloatObject,
IndirectObject,
NameObject,
PdfObject,
NumberObject,
TextStringObject,
NullObject,
],
)
| 1,154 | 1,233 |
def _sweep_indirect_references(
self,
root: Union[
ArrayObject,
BooleanObject,
DictionaryObject,
FloatObject,
IndirectObject,
NameObject,
PdfObject,
NumberObject,
TextStringObject,
NullObject,
],
) -> None:
stack: Deque[
Tuple[
Any,
Optional[Any],
Any,
List[PdfObject],
]
] = collections.deque()
discovered = []
parent = None
grant_parents: List[PdfObject] = []
key_or_id = None
# Start from root
stack.append((root, parent, key_or_id, grant_parents))
while len(stack):
data, parent, key_or_id, grant_parents = stack.pop()
# Build stack for a processing depth-first
if isinstance(data, (ArrayObject, DictionaryObject)):
for key, value in data.items():
stack.append(
(
value,
data,
key,
grant_parents + [parent] if parent is not None else [],
)
)
elif isinstance(data, IndirectObject):
if data.pdf != self:
data = self._resolve_indirect_object(data)
if str(data) not in discovered:
discovered.append(str(data))
stack.append((data.get_object(), None, None, []))
# Check if data has a parent and if it is a dict or an array update the value
if isinstance(parent, (DictionaryObject, ArrayObject)):
if isinstance(data, StreamObject):
# a dictionary value is a stream. streams must be indirect
# objects, so we need to change this value.
data = self._resolve_indirect_object(self._add_object(data))
update_hashes = []
# Data changed and thus the hash value changed
if parent[key_or_id] != data:
update_hashes = [parent.hash_value()] + [
grant_parent.hash_value() for grant_parent in grant_parents
]
parent[key_or_id] = data
# Update old hash value to new hash value
for old_hash in update_hashes:
indirect_reference = self._idnum_hash.pop(old_hash, None)
if indirect_reference is not None:
indirect_reference_obj = indirect_reference.get_object()
if indirect_reference_obj is not None:
self._idnum_hash[
indirect_reference_obj.hash_value()
] = indirect_reference
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1154-L1233
| 39 |
[
0,
15,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
35,
45,
46,
53,
54
] | 23.75 |
[
36,
37,
47,
49,
50,
51,
55,
58,
60,
63,
64,
67,
70,
71,
73,
74,
76,
77
] | 22.5 | false | 85.547144 | 80 | 14 | 77.5 | 0 |
def _sweep_indirect_references(
self,
root: Union[
ArrayObject,
BooleanObject,
DictionaryObject,
FloatObject,
IndirectObject,
NameObject,
PdfObject,
NumberObject,
TextStringObject,
NullObject,
],
) -> None:
stack: Deque[
Tuple[
Any,
Optional[Any],
Any,
List[PdfObject],
]
] = collections.deque()
discovered = []
parent = None
grant_parents: List[PdfObject] = []
key_or_id = None
# Start from root
stack.append((root, parent, key_or_id, grant_parents))
while len(stack):
data, parent, key_or_id, grant_parents = stack.pop()
# Build stack for a processing depth-first
if isinstance(data, (ArrayObject, DictionaryObject)):
for key, value in data.items():
stack.append(
(
value,
data,
key,
grant_parents + [parent] if parent is not None else [],
)
)
elif isinstance(data, IndirectObject):
if data.pdf != self:
data = self._resolve_indirect_object(data)
if str(data) not in discovered:
discovered.append(str(data))
stack.append((data.get_object(), None, None, []))
# Check if data has a parent and if it is a dict or an array update the value
if isinstance(parent, (DictionaryObject, ArrayObject)):
if isinstance(data, StreamObject):
# a dictionary value is a stream. streams must be indirect
# objects, so we need to change this value.
data = self._resolve_indirect_object(self._add_object(data))
update_hashes = []
# Data changed and thus the hash value changed
if parent[key_or_id] != data:
update_hashes = [parent.hash_value()] + [
grant_parent.hash_value() for grant_parent in grant_parents
]
parent[key_or_id] = data
# Update old hash value to new hash value
for old_hash in update_hashes:
indirect_reference = self._idnum_hash.pop(old_hash, None)
if indirect_reference is not None:
indirect_reference_obj = indirect_reference.get_object()
if indirect_reference_obj is not None:
self._idnum_hash[
indirect_reference_obj.hash_value()
] = indirect_reference
| 24,296 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_resolve_indirect_object
|
(self, data: IndirectObject)
|
return self._idnum_hash[hash_value]
|
Resolves indirect object to this pdf indirect objects.
If it is a new object then it is added to self._objects
and new idnum is given and generation is always 0.
Args:
data:
Returns:
The resolved indirect object
|
Resolves indirect object to this pdf indirect objects.
| 1,235 | 1,277 |
def _resolve_indirect_object(self, data: IndirectObject) -> IndirectObject:
"""
Resolves indirect object to this pdf indirect objects.
If it is a new object then it is added to self._objects
and new idnum is given and generation is always 0.
Args:
data:
Returns:
The resolved indirect object
"""
if hasattr(data.pdf, "stream") and data.pdf.stream.closed:
raise ValueError(f"I/O operation on closed file: {data.pdf.stream.name}")
if data.pdf == self:
return data
# Get real object indirect object
real_obj = data.pdf.get_object(data)
if real_obj is None:
logger_warning(
f"Unable to resolve [{data.__class__.__name__}: {data}], "
"returning NullObject instead",
__name__,
)
real_obj = NullObject()
hash_value = real_obj.hash_value()
# Check if object is handled
if hash_value in self._idnum_hash:
return self._idnum_hash[hash_value]
if data.pdf == self:
self._idnum_hash[hash_value] = IndirectObject(data.idnum, 0, self)
# This is new object in this pdf
else:
self._idnum_hash[hash_value] = self._add_object(real_obj)
return self._idnum_hash[hash_value]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1235-L1277
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12
] | 30.232558 |
[
13,
14,
16,
17,
20,
22,
23,
28,
30,
33,
34,
36,
37,
40,
42
] | 34.883721 | false | 85.547144 | 43 | 7 | 65.116279 | 10 |
def _resolve_indirect_object(self, data: IndirectObject) -> IndirectObject:
if hasattr(data.pdf, "stream") and data.pdf.stream.closed:
raise ValueError(f"I/O operation on closed file: {data.pdf.stream.name}")
if data.pdf == self:
return data
# Get real object indirect object
real_obj = data.pdf.get_object(data)
if real_obj is None:
logger_warning(
f"Unable to resolve [{data.__class__.__name__}: {data}], "
"returning NullObject instead",
__name__,
)
real_obj = NullObject()
hash_value = real_obj.hash_value()
# Check if object is handled
if hash_value in self._idnum_hash:
return self._idnum_hash[hash_value]
if data.pdf == self:
self._idnum_hash[hash_value] = IndirectObject(data.idnum, 0, self)
# This is new object in this pdf
else:
self._idnum_hash[hash_value] = self._add_object(real_obj)
return self._idnum_hash[hash_value]
| 24,297 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_reference
|
(self, obj: PdfObject)
|
return ref
| 1,279 | 1,283 |
def get_reference(self, obj: PdfObject) -> IndirectObject:
idnum = self._objects.index(obj) + 1
ref = IndirectObject(idnum, 0, self)
assert ref.get_object() == obj
return ref
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1279-L1283
| 39 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 85.547144 | 5 | 2 | 100 | 0 |
def get_reference(self, obj: PdfObject) -> IndirectObject:
idnum = self._objects.index(obj) + 1
ref = IndirectObject(idnum, 0, self)
assert ref.get_object() == obj
return ref
| 24,298 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getReference
|
(self, obj: PdfObject)
|
return self.get_reference(obj)
|
.. deprecated:: 1.28.0
Use :meth:`get_reference` instead.
|
.. deprecated:: 1.28.0
| 1,285 | 1,292 |
def getReference(self, obj: PdfObject) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`get_reference` instead.
"""
deprecation_with_replacement("getReference", "get_reference", "3.0.0")
return self.get_reference(obj)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1285-L1292
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getReference(self, obj: PdfObject) -> IndirectObject: # deprecated
deprecation_with_replacement("getReference", "get_reference", "3.0.0")
return self.get_reference(obj)
| 24,299 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_outline_root
|
(self)
|
return outline
| 1,294 | 1,307 |
def get_outline_root(self) -> TreeObject:
if CO.OUTLINES in self._root_object:
# TABLE 3.25 Entries in the catalog dictionary
outline = cast(TreeObject, self._root_object[CO.OUTLINES])
idnum = self._objects.index(outline) + 1
outline_ref = IndirectObject(idnum, 0, self)
assert outline_ref.get_object() == outline
else:
outline = TreeObject()
outline.update({})
outline_ref = self._add_object(outline)
self._root_object[NameObject(CO.OUTLINES)] = outline_ref
return outline
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1294-L1307
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
8,
9,
10,
11,
12,
13
] | 92.857143 |
[] | 0 | false | 85.547144 | 14 | 3 | 100 | 0 |
def get_outline_root(self) -> TreeObject:
if CO.OUTLINES in self._root_object:
# TABLE 3.25 Entries in the catalog dictionary
outline = cast(TreeObject, self._root_object[CO.OUTLINES])
idnum = self._objects.index(outline) + 1
outline_ref = IndirectObject(idnum, 0, self)
assert outline_ref.get_object() == outline
else:
outline = TreeObject()
outline.update({})
outline_ref = self._add_object(outline)
self._root_object[NameObject(CO.OUTLINES)] = outline_ref
return outline
| 24,300 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_threads_root
|
(self)
|
return threads
|
The list of threads.
See §8.3.2 from PDF 1.7 spec.
Returns:
An array (possibly empty) of Dictionaries with ``/F`` and ``/I`` properties.
|
The list of threads.
| 1,309 | 1,324 |
def get_threads_root(self) -> ArrayObject:
"""
The list of threads.
See §8.3.2 from PDF 1.7 spec.
Returns:
An array (possibly empty) of Dictionaries with ``/F`` and ``/I`` properties.
"""
if CO.THREADS in self._root_object:
# TABLE 3.25 Entries in the catalog dictionary
threads = cast(ArrayObject, self._root_object[CO.THREADS])
else:
threads = ArrayObject()
self._root_object[NameObject(CO.THREADS)] = threads
return threads
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1309-L1324
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15
] | 100 |
[] | 0 | true | 85.547144 | 16 | 2 | 100 | 6 |
def get_threads_root(self) -> ArrayObject:
if CO.THREADS in self._root_object:
# TABLE 3.25 Entries in the catalog dictionary
threads = cast(ArrayObject, self._root_object[CO.THREADS])
else:
threads = ArrayObject()
self._root_object[NameObject(CO.THREADS)] = threads
return threads
| 24,301 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
threads
|
(self)
|
return self.get_threads_root()
|
Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec
Each element is a dictionaries with ``/F`` and ``/I`` keys.
|
Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec
| 1,327 | 1,333 |
def threads(self) -> ArrayObject:
"""
Read-only property for the list of threads see §8.3.2 from PDF 1.7 spec
Each element is a dictionaries with ``/F`` and ``/I`` keys.
"""
return self.get_threads_root()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1327-L1333
| 39 |
[
0,
1,
2,
3,
4,
5,
6
] | 100 |
[] | 0 | true | 85.547144 | 7 | 1 | 100 | 3 |
def threads(self) -> ArrayObject:
return self.get_threads_root()
| 24,302 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getOutlineRoot
|
(self)
|
return self.get_outline_root()
|
.. deprecated:: 1.28.0
Use :meth:`get_outline_root` instead.
|
.. deprecated:: 1.28.0
| 1,335 | 1,342 |
def getOutlineRoot(self) -> TreeObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`get_outline_root` instead.
"""
deprecation_with_replacement("getOutlineRoot", "get_outline_root", "3.0.0")
return self.get_outline_root()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1335-L1342
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getOutlineRoot(self) -> TreeObject: # deprecated
deprecation_with_replacement("getOutlineRoot", "get_outline_root", "3.0.0")
return self.get_outline_root()
| 24,303 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
get_named_dest_root
|
(self)
|
return nd
| 1,344 | 1,377 |
def get_named_dest_root(self) -> ArrayObject:
if CA.NAMES in self._root_object and isinstance(
self._root_object[CA.NAMES], DictionaryObject
):
names = cast(DictionaryObject, self._root_object[CA.NAMES])
names_ref = names.indirect_reference
if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject):
# 3.6.3 Name Dictionary (PDF spec 1.7)
dests = cast(DictionaryObject, names[CA.DESTS])
dests_ref = dests.indirect_reference
if CA.NAMES in dests:
# TABLE 3.33 Entries in a name tree node dictionary
nd = cast(ArrayObject, dests[CA.NAMES])
else:
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
else:
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
else:
names = DictionaryObject()
names_ref = self._add_object(names)
self._root_object[NameObject(CA.NAMES)] = names_ref
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
return nd
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1344-L1377
| 39 |
[
0,
1,
4,
5,
6,
7,
8,
9,
10,
11,
12,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33
] | 61.764706 |
[
14,
15,
17,
18,
19,
20,
21
] | 20.588235 | false | 85.547144 | 34 | 6 | 79.411765 | 0 |
def get_named_dest_root(self) -> ArrayObject:
if CA.NAMES in self._root_object and isinstance(
self._root_object[CA.NAMES], DictionaryObject
):
names = cast(DictionaryObject, self._root_object[CA.NAMES])
names_ref = names.indirect_reference
if CA.DESTS in names and isinstance(names[CA.DESTS], DictionaryObject):
# 3.6.3 Name Dictionary (PDF spec 1.7)
dests = cast(DictionaryObject, names[CA.DESTS])
dests_ref = dests.indirect_reference
if CA.NAMES in dests:
# TABLE 3.33 Entries in a name tree node dictionary
nd = cast(ArrayObject, dests[CA.NAMES])
else:
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
else:
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
else:
names = DictionaryObject()
names_ref = self._add_object(names)
self._root_object[NameObject(CA.NAMES)] = names_ref
dests = DictionaryObject()
dests_ref = self._add_object(dests)
names[NameObject(CA.DESTS)] = dests_ref
nd = ArrayObject()
dests[NameObject(CA.NAMES)] = nd
return nd
| 24,304 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getNamedDestRoot
|
(self)
|
return self.get_named_dest_root()
|
.. deprecated:: 1.28.0
Use :meth:`get_named_dest_root` instead.
|
.. deprecated:: 1.28.0
| 1,379 | 1,386 |
def getNamedDestRoot(self) -> ArrayObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`get_named_dest_root` instead.
"""
deprecation_with_replacement("getNamedDestRoot", "get_named_dest_root", "3.0.0")
return self.get_named_dest_root()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1379-L1386
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getNamedDestRoot(self) -> ArrayObject: # deprecated
deprecation_with_replacement("getNamedDestRoot", "get_named_dest_root", "3.0.0")
return self.get_named_dest_root()
| 24,305 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_outline_item_destination
|
(
self,
page_destination: Union[None, PageObject, TreeObject] = None,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
dest: Union[None, PageObject, TreeObject] = None, # deprecated
)
|
return page_destination_ref
| 1,388 | 1,423 |
def add_outline_item_destination(
self,
page_destination: Union[None, PageObject, TreeObject] = None,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
dest: Union[None, PageObject, TreeObject] = None, # deprecated
) -> IndirectObject:
if page_destination is not None and dest is not None: # deprecated
raise ValueError(
"The argument dest of add_outline_item_destination is deprecated. Use page_destination only."
)
if dest is not None: # deprecated
old_term = "dest"
new_term = "page_destination"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_destination = dest
if page_destination is None: # deprecated
# argument is only Optional due to deprecated argument.
raise ValueError("page_destination may not be None")
if parent is None:
parent = self.get_outline_root()
parent = cast(TreeObject, parent.get_object())
page_destination_ref = self._add_object(page_destination)
if before is not None:
before = before.indirect_reference
parent.insert_child(page_destination_ref, before, self)
return page_destination_ref
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1388-L1423
| 39 |
[
25,
26,
27,
28,
29,
30,
31,
33,
34,
35
] | 40 |
[
32
] | 4 | false | 85.547144 | 36 | 7 | 96 | 0 |
def add_outline_item_destination(
self,
page_destination: Union[None, PageObject, TreeObject] = None,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
dest: Union[None, PageObject, TreeObject] = None, # deprecated
) -> IndirectObject:
if page_destination is not None and dest is not None: # deprecated
raise ValueError(
"The argument dest of add_outline_item_destination is deprecated. Use page_destination only."
)
if dest is not None: # deprecated
old_term = "dest"
new_term = "page_destination"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_destination = dest
if page_destination is None: # deprecated
# argument is only Optional due to deprecated argument.
raise ValueError("page_destination may not be None")
if parent is None:
parent = self.get_outline_root()
parent = cast(TreeObject, parent.get_object())
page_destination_ref = self._add_object(page_destination)
if before is not None:
before = before.indirect_reference
parent.insert_child(page_destination_ref, before, self)
return page_destination_ref
| 24,306 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_bookmark_destination
|
(
self,
dest: Union[PageObject, TreeObject],
parent: Union[None, TreeObject, IndirectObject] = None,
)
|
return self.add_outline_item_destination(dest, parent)
|
.. deprecated:: 2.9.0
Use :meth:`add_outline_item_destination` instead.
|
.. deprecated:: 2.9.0
| 1,425 | 1,438 |
def add_bookmark_destination(
self,
dest: Union[PageObject, TreeObject],
parent: Union[None, TreeObject, IndirectObject] = None,
) -> IndirectObject: # deprecated
"""
.. deprecated:: 2.9.0
Use :meth:`add_outline_item_destination` instead.
"""
deprecation_with_replacement(
"add_bookmark_destination", "add_outline_item_destination", "3.0.0"
)
return self.add_outline_item_destination(dest, parent)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1425-L1438
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 14 | 1 | 100 | 3 |
def add_bookmark_destination(
self,
dest: Union[PageObject, TreeObject],
parent: Union[None, TreeObject, IndirectObject] = None,
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"add_bookmark_destination", "add_outline_item_destination", "3.0.0"
)
return self.add_outline_item_destination(dest, parent)
| 24,307 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addBookmarkDestination
|
(
self, dest: PageObject, parent: Optional[TreeObject] = None
)
|
return self.add_outline_item_destination(dest, parent)
|
.. deprecated:: 1.28.0
Use :meth:`add_outline_item_destination` instead.
|
.. deprecated:: 1.28.0
| 1,440 | 1,451 |
def addBookmarkDestination(
self, dest: PageObject, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_outline_item_destination` instead.
"""
deprecation_with_replacement(
"addBookmarkDestination", "add_outline_item_destination", "3.0.0"
)
return self.add_outline_item_destination(dest, parent)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1440-L1451
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def addBookmarkDestination(
self, dest: PageObject, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"addBookmarkDestination", "add_outline_item_destination", "3.0.0"
)
return self.add_outline_item_destination(dest, parent)
| 24,308 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_outline_item_dict
|
(
self,
outline_item: OutlineItemType,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
)
|
return self.add_outline_item_destination(outline_item_object, parent, before)
| 1,454 | 1,473 |
def add_outline_item_dict(
self,
outline_item: OutlineItemType,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
) -> IndirectObject:
outline_item_object = TreeObject()
for k, v in list(outline_item.items()):
outline_item_object[NameObject(str(k))] = v
outline_item_object.update(outline_item)
if "/A" in outline_item:
action = DictionaryObject()
a_dict = cast(DictionaryObject, outline_item["/A"])
for k, v in list(a_dict.items()):
action[NameObject(str(k))] = v
action_ref = self._add_object(action)
outline_item_object[NameObject("/A")] = action_ref
return self.add_outline_item_destination(outline_item_object, parent, before)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1454-L1473
| 39 |
[
0,
6,
7,
8,
9,
10,
11,
12,
13,
14,
15,
16,
17,
18,
19
] | 75 |
[] | 0 | false | 85.547144 | 20 | 4 | 100 | 0 |
def add_outline_item_dict(
self,
outline_item: OutlineItemType,
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
) -> IndirectObject:
outline_item_object = TreeObject()
for k, v in list(outline_item.items()):
outline_item_object[NameObject(str(k))] = v
outline_item_object.update(outline_item)
if "/A" in outline_item:
action = DictionaryObject()
a_dict = cast(DictionaryObject, outline_item["/A"])
for k, v in list(a_dict.items()):
action[NameObject(str(k))] = v
action_ref = self._add_object(action)
outline_item_object[NameObject("/A")] = action_ref
return self.add_outline_item_destination(outline_item_object, parent, before)
| 24,309 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_bookmark_dict
|
(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
)
|
return self.add_outline_item_dict(outline_item, parent)
|
.. deprecated:: 2.9.0
Use :meth:`add_outline_item_dict` instead.
|
.. deprecated:: 2.9.0
| 1,476 | 1,487 |
def add_bookmark_dict(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
"""
.. deprecated:: 2.9.0
Use :meth:`add_outline_item_dict` instead.
"""
deprecation_with_replacement(
"add_bookmark_dict", "add_outline_item_dict", "3.0.0"
)
return self.add_outline_item_dict(outline_item, parent)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1476-L1487
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def add_bookmark_dict(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"add_bookmark_dict", "add_outline_item_dict", "3.0.0"
)
return self.add_outline_item_dict(outline_item, parent)
| 24,310 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addBookmarkDict
|
(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
)
|
return self.add_outline_item_dict(outline_item, parent)
|
.. deprecated:: 1.28.0
Use :meth:`add_outline_item_dict` instead.
|
.. deprecated:: 1.28.0
| 1,490 | 1,501 |
def addBookmarkDict(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_outline_item_dict` instead.
"""
deprecation_with_replacement(
"addBookmarkDict", "add_outline_item_dict", "3.0.0"
)
return self.add_outline_item_dict(outline_item, parent)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1490-L1501
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def addBookmarkDict(
self, outline_item: OutlineItemType, parent: Optional[TreeObject] = None
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"addBookmarkDict", "add_outline_item_dict", "3.0.0"
)
return self.add_outline_item_dict(outline_item, parent)
| 24,311 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_outline_item
|
(
self,
title: str,
page_number: Union[None, PageObject, IndirectObject, int],
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Union[Tuple[float, float, float], str]] = None,
bold: bool = False,
italic: bool = False,
fit: Fit = PAGE_FIT,
pagenum: Optional[int] = None, # deprecated
)
|
return self.add_outline_item_destination(outline_item, parent, before)
|
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.
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 or as a Hex String (#RRGGBB)
bold: Outline item font is bold
italic: Outline item font is italic
fit: The fit of the destination page.
Returns:
The added outline item as an indirect object.
|
Add an outline item (commonly referred to as a "Bookmark") to this PDF file.
| 1,503 | 1,581 |
def add_outline_item(
self,
title: str,
page_number: Union[None, PageObject, IndirectObject, int],
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Union[Tuple[float, float, float], str]] = 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.
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 or as a Hex String (#RRGGBB)
bold: Outline item font is bold
italic: Outline item font is italic
fit: The fit of the destination page.
Returns:
The added outline item as an indirect object.
"""
page_ref: Union[None, NullObject, IndirectObject, NumberObject]
if isinstance(italic, Fit): # it means that we are on the old params
if fit is not None and page_number is None:
page_number = fit # type: ignore
return self.add_outline_item(
title, page_number, parent, None, before, color, bold, italic # type: ignore
)
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 page_number is None:
action_ref = None
else:
if isinstance(page_number, IndirectObject):
page_ref = page_number
elif isinstance(page_number, PageObject):
page_ref = page_number.indirect_reference
elif isinstance(page_number, int):
try:
page_ref = self.pages[page_number].indirect_reference
except IndexError:
page_ref = NumberObject(page_number)
if page_ref is None:
logger_warning(
f"can not find reference of page {page_number}",
__name__,
)
page_ref = NullObject()
dest = Destination(
NameObject("/" + title + " outline item"),
page_ref,
fit,
)
action_ref = self._add_object(
DictionaryObject(
{
NameObject(GoToActionArguments.D): dest.dest_array,
NameObject(GoToActionArguments.S): NameObject("/GoTo"),
}
)
)
outline_item = _create_outline_item(action_ref, title, color, italic, bold)
if parent is None:
parent = self.get_outline_root()
return self.add_outline_item_destination(outline_item, parent, before)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1503-L1581
| 39 |
[
32,
33,
35,
38,
42,
45,
46,
47,
49,
50,
51,
54,
60,
65,
66,
74,
75,
76,
77,
78
] | 25.974026 |
[
34,
43,
48,
52,
53,
55,
59
] | 9.090909 | false | 85.547144 | 79 | 13 | 90.909091 | 17 |
def add_outline_item(
self,
title: str,
page_number: Union[None, PageObject, IndirectObject, int],
parent: Union[None, TreeObject, IndirectObject] = None,
before: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Union[Tuple[float, float, float], str]] = None,
bold: bool = False,
italic: bool = False,
fit: Fit = PAGE_FIT,
pagenum: Optional[int] = None, # deprecated
) -> IndirectObject:
page_ref: Union[None, NullObject, IndirectObject, NumberObject]
if isinstance(italic, Fit): # it means that we are on the old params
if fit is not None and page_number is None:
page_number = fit # type: ignore
return self.add_outline_item(
title, page_number, parent, None, before, color, bold, italic # type: ignore
)
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 page_number is None:
action_ref = None
else:
if isinstance(page_number, IndirectObject):
page_ref = page_number
elif isinstance(page_number, PageObject):
page_ref = page_number.indirect_reference
elif isinstance(page_number, int):
try:
page_ref = self.pages[page_number].indirect_reference
except IndexError:
page_ref = NumberObject(page_number)
if page_ref is None:
logger_warning(
f"can not find reference of page {page_number}",
__name__,
)
page_ref = NullObject()
dest = Destination(
NameObject("/" + title + " outline item"),
page_ref,
fit,
)
action_ref = self._add_object(
DictionaryObject(
{
NameObject(GoToActionArguments.D): dest.dest_array,
NameObject(GoToActionArguments.S): NameObject("/GoTo"),
}
)
)
outline_item = _create_outline_item(action_ref, title, color, italic, bold)
if parent is None:
parent = self.get_outline_root()
return self.add_outline_item_destination(outline_item, parent, before)
| 24,312 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_bookmark
|
(
self,
title: str,
pagenum: int, # deprecated, but the whole method is deprecated
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
)
|
return self.add_outline_item(
title,
pagenum,
parent,
color, # type: ignore
bold, # type: ignore
italic,
Fit(fit_type=fit, fit_args=args), # type: ignore
)
|
.. deprecated:: 2.9.0
Use :meth:`add_outline_item` instead.
|
.. deprecated:: 2.9.0
| 1,583 | 1,608 |
def add_bookmark(
self,
title: str,
pagenum: int, # deprecated, but the whole method is deprecated
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> IndirectObject: # deprecated
"""
.. deprecated:: 2.9.0
Use :meth:`add_outline_item` instead.
"""
deprecation_with_replacement("add_bookmark", "add_outline_item", "3.0.0")
return self.add_outline_item(
title,
pagenum,
parent,
color, # type: ignore
bold, # type: ignore
italic,
Fit(fit_type=fit, fit_args=args), # type: ignore
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1583-L1608
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 26 | 1 | 100 | 3 |
def add_bookmark(
self,
title: str,
pagenum: int, # deprecated, but the whole method is deprecated
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> IndirectObject: # deprecated
deprecation_with_replacement("add_bookmark", "add_outline_item", "3.0.0")
return self.add_outline_item(
title,
pagenum,
parent,
color, # type: ignore
bold, # type: ignore
italic,
Fit(fit_type=fit, fit_args=args), # type: ignore
)
| 24,313 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addBookmark
|
(
self,
title: str,
pagenum: int,
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
)
|
return self.add_outline_item(
title,
pagenum,
parent,
None,
color,
bold,
italic,
Fit(fit_type=fit, fit_args=args),
)
|
.. deprecated:: 1.28.0
Use :meth:`add_outline_item` instead.
|
.. deprecated:: 1.28.0
| 1,610 | 1,636 |
def addBookmark(
self,
title: str,
pagenum: int,
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_outline_item` instead.
"""
deprecation_with_replacement("addBookmark", "add_outline_item", "3.0.0")
return self.add_outline_item(
title,
pagenum,
parent,
None,
color,
bold,
italic,
Fit(fit_type=fit, fit_args=args),
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1610-L1636
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 27 | 1 | 100 | 3 |
def addBookmark(
self,
title: str,
pagenum: int,
parent: Union[None, TreeObject, IndirectObject] = None,
color: Optional[Tuple[float, float, float]] = None,
bold: bool = False,
italic: bool = False,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> IndirectObject: # deprecated
deprecation_with_replacement("addBookmark", "add_outline_item", "3.0.0")
return self.add_outline_item(
title,
pagenum,
parent,
None,
color,
bold,
italic,
Fit(fit_type=fit, fit_args=args),
)
| 24,314 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_named_destination_array
|
(
self, title: TextStringObject, destination: Union[IndirectObject, ArrayObject]
)
|
return
| 1,643 | 1,656 |
def add_named_destination_array(
self, title: TextStringObject, destination: Union[IndirectObject, ArrayObject]
) -> None:
nd = self.get_named_dest_root()
i = 0
while i < len(nd):
if title < nd[i]:
nd.insert(i, destination)
nd.insert(i, TextStringObject(title))
return
else:
i += 2
nd.extend([TextStringObject(title), destination])
return
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1643-L1656
| 39 |
[
0,
3,
4,
5,
6,
7,
8,
9,
11,
12,
13
] | 78.571429 |
[] | 0 | false | 85.547144 | 14 | 3 | 100 | 0 |
def add_named_destination_array(
self, title: TextStringObject, destination: Union[IndirectObject, ArrayObject]
) -> None:
nd = self.get_named_dest_root()
i = 0
while i < len(nd):
if title < nd[i]:
nd.insert(i, destination)
nd.insert(i, TextStringObject(title))
return
else:
i += 2
nd.extend([TextStringObject(title), destination])
return
| 24,315 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_named_destination_object
|
(
self,
page_destination: Optional[PdfObject] = None,
dest: Optional[PdfObject] = None,
)
|
return page_destination_ref
| 1,658 | 1,686 |
def add_named_destination_object(
self,
page_destination: Optional[PdfObject] = None,
dest: Optional[PdfObject] = None,
) -> IndirectObject:
if page_destination is not None and dest is not None:
raise ValueError(
"The argument dest of add_named_destination_object is deprecated. Use page_destination only."
)
if dest is not None: # deprecated
old_term = "dest"
new_term = "page_destination"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_destination = dest
if page_destination is None: # deprecated
raise ValueError("page_destination may not be None")
page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore
self.add_named_destination_array(
cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore
)
return page_destination_ref
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1658-L1686
| 39 |
[
0,
5,
22,
23,
24,
27,
28
] | 33.333333 |
[] | 0 | false | 85.547144 | 29 | 5 | 100 | 0 |
def add_named_destination_object(
self,
page_destination: Optional[PdfObject] = None,
dest: Optional[PdfObject] = None,
) -> IndirectObject:
if page_destination is not None and dest is not None:
raise ValueError(
"The argument dest of add_named_destination_object is deprecated. Use page_destination only."
)
if dest is not None: # deprecated
old_term = "dest"
new_term = "page_destination"
warnings.warn(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_destination = dest
if page_destination is None: # deprecated
raise ValueError("page_destination may not be None")
page_destination_ref = self._add_object(page_destination.dest_array) # type: ignore
self.add_named_destination_array(
cast("TextStringObject", page_destination["/Title"]), page_destination_ref # type: ignore
)
return page_destination_ref
| 24,316 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addNamedDestinationObject
|
(
self, dest: Destination
)
|
return self.add_named_destination_object(dest)
|
.. deprecated:: 1.28.0
Use :meth:`add_named_destination_object` instead.
|
.. deprecated:: 1.28.0
| 1,688 | 1,699 |
def addNamedDestinationObject(
self, dest: Destination
) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_named_destination_object` instead.
"""
deprecation_with_replacement(
"addNamedDestinationObject", "add_named_destination_object", "3.0.0"
)
return self.add_named_destination_object(dest)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1688-L1699
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def addNamedDestinationObject(
self, dest: Destination
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"addNamedDestinationObject", "add_named_destination_object", "3.0.0"
)
return self.add_named_destination_object(dest)
| 24,317 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_named_destination
|
(
self,
title: str,
page_number: Optional[int] = None,
pagenum: Optional[int] = None, # deprecated
)
|
return dest_ref
| 1,701 | 1,740 |
def add_named_destination(
self,
title: str,
page_number: Optional[int] = None,
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(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_number = pagenum
if page_number is None:
raise ValueError("page_number may not be None")
page_ref = self.get_object(self._pages)[PA.KIDS][page_number] # type: ignore
dest = DictionaryObject()
dest.update(
{
NameObject(GoToActionArguments.D): ArrayObject(
[page_ref, NameObject(TypFitArguments.FIT_H), NumberObject(826)]
),
NameObject(GoToActionArguments.S): NameObject("/GoTo"),
}
)
dest_ref = self._add_object(dest)
nd = self.get_named_dest_root()
if not isinstance(title, TextStringObject):
title = TextStringObject(str(title))
nd.extend([title, dest_ref])
return dest_ref
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1701-L1740
| 39 |
[
6,
10,
21,
23,
24,
25,
33,
34,
35,
36,
37,
38,
39
] | 35.135135 |
[
11,
12,
20,
22
] | 10.810811 | false | 85.547144 | 40 | 6 | 89.189189 | 0 |
def add_named_destination(
self,
title: str,
page_number: Optional[int] = None,
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(
message=(
f"{old_term} is deprecated as an argument and will be "
f"removed in pypdf 4.0.0. Use {new_term} instead"
),
category=DeprecationWarning,
)
page_number = pagenum
if page_number is None:
raise ValueError("page_number may not be None")
page_ref = self.get_object(self._pages)[PA.KIDS][page_number] # type: ignore
dest = DictionaryObject()
dest.update(
{
NameObject(GoToActionArguments.D): ArrayObject(
[page_ref, NameObject(TypFitArguments.FIT_H), NumberObject(826)]
),
NameObject(GoToActionArguments.S): NameObject("/GoTo"),
}
)
dest_ref = self._add_object(dest)
nd = self.get_named_dest_root()
if not isinstance(title, TextStringObject):
title = TextStringObject(str(title))
nd.extend([title, dest_ref])
return dest_ref
| 24,318 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addNamedDestination
|
(
self, title: str, pagenum: int
)
|
return self.add_named_destination(title, pagenum)
|
.. deprecated:: 1.28.0
Use :meth:`add_named_destination` instead.
|
.. deprecated:: 1.28.0
| 1,742 | 1,753 |
def addNamedDestination(
self, title: str, pagenum: int
) -> IndirectObject: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_named_destination` instead.
"""
deprecation_with_replacement(
"addNamedDestination", "add_named_destination", "3.0.0"
)
return self.add_named_destination(title, pagenum)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1742-L1753
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 12 | 1 | 100 | 3 |
def addNamedDestination(
self, title: str, pagenum: int
) -> IndirectObject: # deprecated
deprecation_with_replacement(
"addNamedDestination", "add_named_destination", "3.0.0"
)
return self.add_named_destination(title, pagenum)
| 24,319 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
remove_links
|
(self)
|
Remove links and annotations from this output.
|
Remove links and annotations from this output.
| 1,755 | 1,762 |
def remove_links(self) -> None:
"""Remove links and annotations from this output."""
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(ArrayObject, pg_dict[PA.KIDS])
for page in pages:
page_ref = cast(DictionaryObject, self.get_object(page))
if PG.ANNOTS in page_ref:
del page_ref[PG.ANNOTS]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1755-L1762
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 85.547144 | 8 | 3 | 100 | 1 |
def remove_links(self) -> None:
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(ArrayObject, pg_dict[PA.KIDS])
for page in pages:
page_ref = cast(DictionaryObject, self.get_object(page))
if PG.ANNOTS in page_ref:
del page_ref[PG.ANNOTS]
| 24,320 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
removeLinks
|
(self)
|
return self.remove_links()
|
.. deprecated:: 1.28.0
Use :meth:`remove_links` instead.
|
.. deprecated:: 1.28.0
| 1,764 | 1,771 |
def removeLinks(self) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`remove_links` instead.
"""
deprecation_with_replacement("removeLinks", "remove_links", "3.0.0")
return self.remove_links()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1764-L1771
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def removeLinks(self) -> None: # deprecated
deprecation_with_replacement("removeLinks", "remove_links", "3.0.0")
return self.remove_links()
| 24,321 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
remove_images
|
(self, ignore_byte_string_object: bool = False)
|
Remove images from this output.
Args:
ignore_byte_string_object: optional parameter
to ignore ByteString Objects.
|
Remove images from this output.
| 1,773 | 1,849 |
def remove_images(self, ignore_byte_string_object: bool = False) -> None:
"""
Remove images from this output.
Args:
ignore_byte_string_object: optional parameter
to ignore ByteString Objects.
"""
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(ArrayObject, pg_dict[PA.KIDS])
jump_operators = (
b"cm",
b"w",
b"J",
b"j",
b"M",
b"d",
b"ri",
b"i",
b"gs",
b"W",
b"b",
b"s",
b"S",
b"f",
b"F",
b"n",
b"m",
b"l",
b"c",
b"v",
b"y",
b"h",
b"B",
b"Do",
b"sh",
)
for page in pages:
page_ref = cast(DictionaryObject, self.get_object(page))
content = page_ref["/Contents"].get_object()
if not isinstance(content, ContentStream):
content = ContentStream(content, page_ref)
_operations = []
seq_graphics = False
for operands, operator in content.operations:
if operator in [b"Tj", b"'"]:
text = operands[0]
if ignore_byte_string_object and not isinstance(
text, TextStringObject
):
operands[0] = TextStringObject()
elif operator == b'"':
text = operands[2]
if ignore_byte_string_object and not isinstance(
text, TextStringObject
):
operands[2] = TextStringObject()
elif operator == b"TJ":
for i in range(len(operands[0])):
if ignore_byte_string_object and not isinstance(
operands[0][i], TextStringObject
):
operands[0][i] = TextStringObject()
if operator == b"q":
seq_graphics = True
if operator == b"Q":
seq_graphics = False
if seq_graphics and operator in jump_operators:
continue
if operator == b"re":
continue
_operations.append((operands, operator))
content.operations = _operations
page_ref.__setitem__(NameObject("/Contents"), content)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1773-L1849
| 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,
42,
43,
44,
45,
46,
47,
48,
49,
50,
52,
58,
59,
60,
61,
62,
64,
65,
66,
67,
68,
69,
70,
71,
73,
74,
75,
76
] | 89.61039 |
[
51,
53,
54,
57,
63,
72
] | 7.792208 | false | 85.547144 | 77 | 19 | 92.207792 | 5 |
def remove_images(self, ignore_byte_string_object: bool = False) -> None:
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(ArrayObject, pg_dict[PA.KIDS])
jump_operators = (
b"cm",
b"w",
b"J",
b"j",
b"M",
b"d",
b"ri",
b"i",
b"gs",
b"W",
b"b",
b"s",
b"S",
b"f",
b"F",
b"n",
b"m",
b"l",
b"c",
b"v",
b"y",
b"h",
b"B",
b"Do",
b"sh",
)
for page in pages:
page_ref = cast(DictionaryObject, self.get_object(page))
content = page_ref["/Contents"].get_object()
if not isinstance(content, ContentStream):
content = ContentStream(content, page_ref)
_operations = []
seq_graphics = False
for operands, operator in content.operations:
if operator in [b"Tj", b"'"]:
text = operands[0]
if ignore_byte_string_object and not isinstance(
text, TextStringObject
):
operands[0] = TextStringObject()
elif operator == b'"':
text = operands[2]
if ignore_byte_string_object and not isinstance(
text, TextStringObject
):
operands[2] = TextStringObject()
elif operator == b"TJ":
for i in range(len(operands[0])):
if ignore_byte_string_object and not isinstance(
operands[0][i], TextStringObject
):
operands[0][i] = TextStringObject()
if operator == b"q":
seq_graphics = True
if operator == b"Q":
seq_graphics = False
if seq_graphics and operator in jump_operators:
continue
if operator == b"re":
continue
_operations.append((operands, operator))
content.operations = _operations
page_ref.__setitem__(NameObject("/Contents"), content)
| 24,322 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
removeImages
|
(self, ignoreByteStringObject: bool = False)
|
return self.remove_images(ignoreByteStringObject)
|
.. deprecated:: 1.28.0
Use :meth:`remove_images` instead.
|
.. deprecated:: 1.28.0
| 1,851 | 1,858 |
def removeImages(self, ignoreByteStringObject: bool = False) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`remove_images` instead.
"""
deprecation_with_replacement("removeImages", "remove_images", "3.0.0")
return self.remove_images(ignoreByteStringObject)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1851-L1858
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def removeImages(self, ignoreByteStringObject: bool = False) -> None: # deprecated
deprecation_with_replacement("removeImages", "remove_images", "3.0.0")
return self.remove_images(ignoreByteStringObject)
| 24,323 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
remove_text
|
(self, ignore_byte_string_object: bool = False)
|
Remove text from this output.
Args:
ignore_byte_string_object: optional parameter to ignore ByteString Objects.
|
Remove text from this output.
| 1,860 | 1,902 |
def remove_text(self, ignore_byte_string_object: bool = False) -> None:
"""
Remove text from this output.
Args:
ignore_byte_string_object: optional parameter to ignore ByteString Objects.
"""
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(List[IndirectObject], pg_dict[PA.KIDS])
for page in pages:
page_ref = cast(PageObject, self.get_object(page))
content = page_ref["/Contents"].get_object()
if not isinstance(content, ContentStream):
content = ContentStream(content, page_ref)
for operands, operator in content.operations:
if operator in [b"Tj", b"'"]:
text = operands[0]
if not ignore_byte_string_object:
if isinstance(text, TextStringObject):
operands[0] = TextStringObject()
else:
if isinstance(text, (TextStringObject, ByteStringObject)):
operands[0] = TextStringObject()
elif operator == b'"':
text = operands[2]
if not ignore_byte_string_object:
if isinstance(text, TextStringObject):
operands[2] = TextStringObject()
else:
if isinstance(text, (TextStringObject, ByteStringObject)):
operands[2] = TextStringObject()
elif operator == b"TJ":
for i in range(len(operands[0])):
if not ignore_byte_string_object:
if isinstance(operands[0][i], TextStringObject):
operands[0][i] = TextStringObject()
else:
if isinstance(
operands[0][i], (TextStringObject, ByteStringObject)
):
operands[0][i] = TextStringObject()
page_ref.__setitem__(NameObject("/Contents"), content)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1860-L1902
| 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,
42
] | 100 |
[] | 0 | true | 85.547144 | 43 | 17 | 100 | 4 |
def remove_text(self, ignore_byte_string_object: bool = False) -> None:
pg_dict = cast(DictionaryObject, self.get_object(self._pages))
pages = cast(List[IndirectObject], pg_dict[PA.KIDS])
for page in pages:
page_ref = cast(PageObject, self.get_object(page))
content = page_ref["/Contents"].get_object()
if not isinstance(content, ContentStream):
content = ContentStream(content, page_ref)
for operands, operator in content.operations:
if operator in [b"Tj", b"'"]:
text = operands[0]
if not ignore_byte_string_object:
if isinstance(text, TextStringObject):
operands[0] = TextStringObject()
else:
if isinstance(text, (TextStringObject, ByteStringObject)):
operands[0] = TextStringObject()
elif operator == b'"':
text = operands[2]
if not ignore_byte_string_object:
if isinstance(text, TextStringObject):
operands[2] = TextStringObject()
else:
if isinstance(text, (TextStringObject, ByteStringObject)):
operands[2] = TextStringObject()
elif operator == b"TJ":
for i in range(len(operands[0])):
if not ignore_byte_string_object:
if isinstance(operands[0][i], TextStringObject):
operands[0][i] = TextStringObject()
else:
if isinstance(
operands[0][i], (TextStringObject, ByteStringObject)
):
operands[0][i] = TextStringObject()
page_ref.__setitem__(NameObject("/Contents"), content)
| 24,324 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
removeText
|
(self, ignoreByteStringObject: bool = False)
|
return self.remove_text(ignoreByteStringObject)
|
.. deprecated:: 1.28.0
Use :meth:`remove_text` instead.
|
.. deprecated:: 1.28.0
| 1,904 | 1,911 |
def removeText(self, ignoreByteStringObject: bool = False) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`remove_text` instead.
"""
deprecation_with_replacement("removeText", "remove_text", "3.0.0")
return self.remove_text(ignoreByteStringObject)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1904-L1911
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def removeText(self, ignoreByteStringObject: bool = False) -> None: # deprecated
deprecation_with_replacement("removeText", "remove_text", "3.0.0")
return self.remove_text(ignoreByteStringObject)
| 24,325 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_uri
|
(
self,
page_number: int,
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
pagenum: Optional[int] = None,
)
|
Add an URI from a rectangular area to the specified page.
This uses the basic structure of :meth:`add_link`
Args:
page_number: index of the page on which to place the URI action.
uri: URI of resource to link to.
rect: :class:`RectangleObject<pypdf.generic.RectangleObject>` or array of four
integers specifying the clickable rectangular area
``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
border: if provided, an array describing border-drawing
properties. See the PDF spec for details. No border will be
drawn if this argument is omitted.
|
Add an URI from a rectangular area to the specified page.
This uses the basic structure of :meth:`add_link`
| 1,913 | 1,987 |
def add_uri(
self,
page_number: int,
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
pagenum: Optional[int] = None,
) -> None:
"""
Add an URI from a rectangular area to the specified page.
This uses the basic structure of :meth:`add_link`
Args:
page_number: index of the page on which to place the URI action.
uri: URI of resource to link to.
rect: :class:`RectangleObject<pypdf.generic.RectangleObject>` or array of four
integers specifying the clickable rectangular area
``[xLL, yLL, xUR, yUR]``, or string in the form ``"[ xLL yLL xUR yUR ]"``.
border: if provided, an array describing border-drawing
properties. See the PDF spec for details. No border will be
drawn if this argument is omitted.
"""
if pagenum is not None:
warnings.warn(
"The 'pagenum' argument of add_uri is deprecated and will be "
"removed in pypdf 4.0.0. Use 'page_number' instead.",
category=DeprecationWarning,
)
page_number = pagenum
page_link = self.get_object(self._pages)[PA.KIDS][page_number] # type: ignore
page_ref = cast(Dict[str, Any], self.get_object(page_link))
border_arr: BorderArrayType
if border is not None:
border_arr = [NameObject(n) for n in border[:3]]
if len(border) == 4:
dash_pattern = ArrayObject([NameObject(n) for n in border[3]])
border_arr.append(dash_pattern)
else:
border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)]
if isinstance(rect, str):
rect = NameObject(rect)
elif isinstance(rect, RectangleObject):
pass
else:
rect = RectangleObject(rect)
lnk2 = DictionaryObject()
lnk2.update(
{
NameObject("/S"): NameObject("/URI"),
NameObject("/URI"): TextStringObject(uri),
}
)
lnk = DictionaryObject()
lnk.update(
{
NameObject(AnnotationDictionaryAttributes.Type): NameObject(PG.ANNOTS),
NameObject(AnnotationDictionaryAttributes.Subtype): NameObject("/Link"),
NameObject(AnnotationDictionaryAttributes.P): page_link,
NameObject(AnnotationDictionaryAttributes.Rect): rect,
NameObject("/H"): NameObject("/I"),
NameObject(AnnotationDictionaryAttributes.Border): ArrayObject(
border_arr
),
NameObject("/A"): lnk2,
}
)
lnk_ref = self._add_object(lnk)
if PG.ANNOTS in page_ref:
page_ref[PG.ANNOTS].append(lnk_ref)
else:
page_ref[NameObject(PG.ANNOTS)] = ArrayObject([lnk_ref])
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1913-L1987
| 39 |
[
0,
21,
22,
23,
24,
25,
26,
27,
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,
57,
58,
59,
60,
61,
62,
63,
64,
65,
66,
67,
68,
69,
70,
71,
72,
73,
74
] | 72.972973 |
[
28
] | 1.351351 | false | 85.547144 | 75 | 9 | 98.648649 | 12 |
def add_uri(
self,
page_number: int,
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
pagenum: Optional[int] = None,
) -> None:
if pagenum is not None:
warnings.warn(
"The 'pagenum' argument of add_uri is deprecated and will be "
"removed in pypdf 4.0.0. Use 'page_number' instead.",
category=DeprecationWarning,
)
page_number = pagenum
page_link = self.get_object(self._pages)[PA.KIDS][page_number] # type: ignore
page_ref = cast(Dict[str, Any], self.get_object(page_link))
border_arr: BorderArrayType
if border is not None:
border_arr = [NameObject(n) for n in border[:3]]
if len(border) == 4:
dash_pattern = ArrayObject([NameObject(n) for n in border[3]])
border_arr.append(dash_pattern)
else:
border_arr = [NumberObject(2), NumberObject(2), NumberObject(2)]
if isinstance(rect, str):
rect = NameObject(rect)
elif isinstance(rect, RectangleObject):
pass
else:
rect = RectangleObject(rect)
lnk2 = DictionaryObject()
lnk2.update(
{
NameObject("/S"): NameObject("/URI"),
NameObject("/URI"): TextStringObject(uri),
}
)
lnk = DictionaryObject()
lnk.update(
{
NameObject(AnnotationDictionaryAttributes.Type): NameObject(PG.ANNOTS),
NameObject(AnnotationDictionaryAttributes.Subtype): NameObject("/Link"),
NameObject(AnnotationDictionaryAttributes.P): page_link,
NameObject(AnnotationDictionaryAttributes.Rect): rect,
NameObject("/H"): NameObject("/I"),
NameObject(AnnotationDictionaryAttributes.Border): ArrayObject(
border_arr
),
NameObject("/A"): lnk2,
}
)
lnk_ref = self._add_object(lnk)
if PG.ANNOTS in page_ref:
page_ref[PG.ANNOTS].append(lnk_ref)
else:
page_ref[NameObject(PG.ANNOTS)] = ArrayObject([lnk_ref])
| 24,326 |
|
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addURI
|
(
self,
pagenum: int, # deprecated, but method is deprecated already
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
)
|
return self.add_uri(pagenum, uri, rect, border)
|
.. deprecated:: 1.28.0
Use :meth:`add_uri` instead.
|
.. deprecated:: 1.28.0
| 1,989 | 2,002 |
def addURI(
self,
pagenum: int, # deprecated, but method is deprecated already
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_uri` instead.
"""
deprecation_with_replacement("addURI", "add_uri", "3.0.0")
return self.add_uri(pagenum, uri, rect, border)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L1989-L2002
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 14 | 1 | 100 | 3 |
def addURI(
self,
pagenum: int, # deprecated, but method is deprecated already
uri: str,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
) -> None: # deprecated
deprecation_with_replacement("addURI", "add_uri", "3.0.0")
return self.add_uri(pagenum, uri, rect, border)
| 24,327 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
add_link
|
(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
)
|
return self.add_annotation(page_number=pagenum, annotation=annotation)
| 2,004 | 2,033 |
def add_link(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> None:
deprecation_with_replacement(
"add_link", "add_annotation(AnnotationBuilder.link(...))"
)
if isinstance(rect, str):
rect = rect.strip()[1:-1]
rect = RectangleObject(
[float(num) for num in rect.split(" ") if len(num) > 0]
)
elif isinstance(rect, RectangleObject):
pass
else:
rect = RectangleObject(rect)
annotation = AnnotationBuilder.link(
rect=rect,
border=border,
target_page_index=page_destination,
fit=Fit(fit_type=fit, fit_args=args),
)
return self.add_annotation(page_number=pagenum, annotation=annotation)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L2004-L2033
| 39 |
[
9
] | 3.448276 |
[
13,
14,
15,
18,
19,
21,
23,
29
] | 27.586207 | false | 85.547144 | 30 | 4 | 72.413793 | 0 |
def add_link(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> None:
deprecation_with_replacement(
"add_link", "add_annotation(AnnotationBuilder.link(...))"
)
if isinstance(rect, str):
rect = rect.strip()[1:-1]
rect = RectangleObject(
[float(num) for num in rect.split(" ") if len(num) > 0]
)
elif isinstance(rect, RectangleObject):
pass
else:
rect = RectangleObject(rect)
annotation = AnnotationBuilder.link(
rect=rect,
border=border,
target_page_index=page_destination,
fit=Fit(fit_type=fit, fit_args=args),
)
return self.add_annotation(page_number=pagenum, annotation=annotation)
| 24,328 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
addLink
|
(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
)
|
return self.add_link(pagenum, page_destination, rect, border, fit, *args)
|
.. deprecated:: 1.28.0
Use :meth:`add_link` instead.
|
.. deprecated:: 1.28.0
| 2,035 | 2,052 |
def addLink(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> None: # deprecated
"""
.. deprecated:: 1.28.0
Use :meth:`add_link` instead.
"""
deprecate_with_replacement(
"addLink", "add_annotation(AnnotationBuilder.link(...))", "4.0.0"
)
return self.add_link(pagenum, page_destination, rect, border, fit, *args)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L2035-L2052
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 18 | 1 | 100 | 3 |
def addLink(
self,
pagenum: int, # deprecated, but method is deprecated already
page_destination: int,
rect: RectangleObject,
border: Optional[ArrayObject] = None,
fit: FitType = "/Fit",
*args: ZoomArgType,
) -> None: # deprecated
deprecate_with_replacement(
"addLink", "add_annotation(AnnotationBuilder.link(...))", "4.0.0"
)
return self.add_link(pagenum, page_destination, rect, border, fit, *args)
| 24,329 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
_get_page_layout
|
(self)
| 2,064 | 2,068 |
def _get_page_layout(self) -> Optional[LayoutType]:
try:
return cast(LayoutType, self._root_object["/PageLayout"])
except KeyError:
return None
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L2064-L2068
| 39 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 85.547144 | 5 | 2 | 100 | 0 |
def _get_page_layout(self) -> Optional[LayoutType]:
try:
return cast(LayoutType, self._root_object["/PageLayout"])
except KeyError:
return None
| 24,330 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_writer.py
|
getPageLayout
|
(self)
|
return self._get_page_layout()
|
.. deprecated:: 1.28.0
Use :py:attr:`page_layout` instead.
|
.. deprecated:: 1.28.0
| 2,070 | 2,077 |
def getPageLayout(self) -> Optional[LayoutType]: # deprecated
"""
.. deprecated:: 1.28.0
Use :py:attr:`page_layout` instead.
"""
deprecation_with_replacement("getPageLayout", "page_layout", "3.0.0")
return self._get_page_layout()
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_writer.py#L2070-L2077
| 39 |
[] | 0 |
[] | 0 | false | 85.547144 | 8 | 1 | 100 | 3 |
def getPageLayout(self) -> Optional[LayoutType]: # deprecated
deprecation_with_replacement("getPageLayout", "page_layout", "3.0.0")
return self._get_page_layout()
| 24,331 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
convert_to_int
|
(d: bytes, size: int)
|
return struct.unpack(">q", d)[0]
| 105 | 110 |
def convert_to_int(d: bytes, size: int) -> Union[int, Tuple[Any, ...]]:
if size > 8:
raise PdfReadError("invalid size in convert_to_int")
d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
d = d[-8:]
return struct.unpack(">q", d)[0]
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L105-L110
| 39 |
[
0,
1,
2,
3,
4,
5
] | 100 |
[] | 0 | true | 91.582229 | 6 | 2 | 100 | 0 |
def convert_to_int(d: bytes, size: int) -> Union[int, Tuple[Any, ...]]:
if size > 8:
raise PdfReadError("invalid size in convert_to_int")
d = b"\x00\x00\x00\x00\x00\x00\x00\x00" + d
d = d[-8:]
return struct.unpack(">q", d)[0]
| 24,332 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
convertToInt
|
(d: bytes, size: int)
|
return convert_to_int(d, size)
| 113 | 115 |
def convertToInt(d: bytes, size: int) -> Union[int, Tuple[Any, ...]]: # deprecated
deprecation_with_replacement("convertToInt", "convert_to_int")
return convert_to_int(d, size)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L113-L115
| 39 |
[] | 0 |
[] | 0 | false | 91.582229 | 3 | 1 | 100 | 0 |
def convertToInt(d: bytes, size: int) -> Union[int, Tuple[Any, ...]]: # deprecated
deprecation_with_replacement("convertToInt", "convert_to_int")
return convert_to_int(d, size)
| 24,333 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.__init__
|
(self)
| 132 | 133 |
def __init__(self) -> None:
DictionaryObject.__init__(self)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L132-L133
| 39 |
[
0,
1
] | 100 |
[] | 0 | true | 91.582229 | 2 | 1 | 100 | 0 |
def __init__(self) -> None:
DictionaryObject.__init__(self)
| 24,334 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation._get_text
|
(self, key: str)
|
return None
| 135 | 139 |
def _get_text(self, key: str) -> Optional[str]:
retval = self.get(key, None)
if isinstance(retval, TextStringObject):
return retval
return None
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L135-L139
| 39 |
[
0,
1,
2,
3,
4
] | 100 |
[] | 0 | true | 91.582229 | 5 | 2 | 100 | 0 |
def _get_text(self, key: str) -> Optional[str]:
retval = self.get(key, None)
if isinstance(retval, TextStringObject):
return retval
return None
| 24,335 |
||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.getText
|
(self, key: str)
|
return self._get_text(key)
|
The text value of the specified key or None.
.. deprecated:: 1.28.0
Use the attributes (e.g. :py:attr:`title` / :py:attr:`author`).
|
The text value of the specified key or None.
| 141 | 150 |
def getText(self, key: str) -> Optional[str]: # deprecated
"""
The text value of the specified key or None.
.. deprecated:: 1.28.0
Use the attributes (e.g. :py:attr:`title` / :py:attr:`author`).
"""
deprecation_no_replacement("getText", "3.0.0")
return self._get_text(key)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L141-L150
| 39 |
[] | 0 |
[] | 0 | false | 91.582229 | 10 | 1 | 100 | 5 |
def getText(self, key: str) -> Optional[str]: # deprecated
deprecation_no_replacement("getText", "3.0.0")
return self._get_text(key)
| 24,336 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.title
|
(self)
|
return (
self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore
if self.get(DI.TITLE)
else None
)
|
Read-only property accessing the document's **title**.
Returns a unicode string (``TextStringObject``) or ``None``
if the title is not specified.
|
Read-only property accessing the document's **title**.
| 153 | 164 |
def title(self) -> Optional[str]:
"""
Read-only property accessing the document's **title**.
Returns a unicode string (``TextStringObject``) or ``None``
if the title is not specified.
"""
return (
self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore
if self.get(DI.TITLE)
else None
)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L153-L164
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11
] | 100 |
[] | 0 | true | 91.582229 | 12 | 2 | 100 | 4 |
def title(self) -> Optional[str]:
return (
self._get_text(DI.TITLE) or self.get(DI.TITLE).get_object() # type: ignore
if self.get(DI.TITLE)
else None
)
| 24,337 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.title_raw
|
(self)
|
return self.get(DI.TITLE)
|
The "raw" version of title; can return a ``ByteStringObject``.
|
The "raw" version of title; can return a ``ByteStringObject``.
| 167 | 169 |
def title_raw(self) -> Optional[str]:
"""The "raw" version of title; can return a ``ByteStringObject``."""
return self.get(DI.TITLE)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L167-L169
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.582229 | 3 | 1 | 100 | 1 |
def title_raw(self) -> Optional[str]:
return self.get(DI.TITLE)
| 24,338 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.author
|
(self)
|
return self._get_text(DI.AUTHOR)
|
Read-only property accessing the document's **author**.
Returns a unicode string (``TextStringObject``) or ``None``
if the author is not specified.
|
Read-only property accessing the document's **author**.
| 172 | 179 |
def author(self) -> Optional[str]:
"""
Read-only property accessing the document's **author**.
Returns a unicode string (``TextStringObject``) or ``None``
if the author is not specified.
"""
return self._get_text(DI.AUTHOR)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L172-L179
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 91.582229 | 8 | 1 | 100 | 4 |
def author(self) -> Optional[str]:
return self._get_text(DI.AUTHOR)
| 24,339 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.author_raw
|
(self)
|
return self.get(DI.AUTHOR)
|
The "raw" version of author; can return a ``ByteStringObject``.
|
The "raw" version of author; can return a ``ByteStringObject``.
| 182 | 184 |
def author_raw(self) -> Optional[str]:
"""The "raw" version of author; can return a ``ByteStringObject``."""
return self.get(DI.AUTHOR)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L182-L184
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.582229 | 3 | 1 | 100 | 1 |
def author_raw(self) -> Optional[str]:
return self.get(DI.AUTHOR)
| 24,340 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.subject
|
(self)
|
return self._get_text(DI.SUBJECT)
|
Read-only property accessing the document's **subject**.
Returns a unicode string (``TextStringObject``) or ``None``
if the subject is not specified.
|
Read-only property accessing the document's **subject**.
| 187 | 194 |
def subject(self) -> Optional[str]:
"""
Read-only property accessing the document's **subject**.
Returns a unicode string (``TextStringObject``) or ``None``
if the subject is not specified.
"""
return self._get_text(DI.SUBJECT)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L187-L194
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 91.582229 | 8 | 1 | 100 | 4 |
def subject(self) -> Optional[str]:
return self._get_text(DI.SUBJECT)
| 24,341 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.subject_raw
|
(self)
|
return self.get(DI.SUBJECT)
|
The "raw" version of subject; can return a ``ByteStringObject``.
|
The "raw" version of subject; can return a ``ByteStringObject``.
| 197 | 199 |
def subject_raw(self) -> Optional[str]:
"""The "raw" version of subject; can return a ``ByteStringObject``."""
return self.get(DI.SUBJECT)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L197-L199
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.582229 | 3 | 1 | 100 | 1 |
def subject_raw(self) -> Optional[str]:
return self.get(DI.SUBJECT)
| 24,342 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.creator
|
(self)
|
return self._get_text(DI.CREATOR)
|
Read-only property accessing the document's **creator**.
If the document was converted to PDF from another format, this is the
name of the application (e.g. OpenOffice) that created the original
document from which it was converted. Returns a unicode string
(``TextStringObject``) or ``None`` if the creator is not specified.
|
Read-only property accessing the document's **creator**.
| 202 | 211 |
def creator(self) -> Optional[str]:
"""
Read-only property accessing the document's **creator**.
If the document was converted to PDF from another format, this is the
name of the application (e.g. OpenOffice) that created the original
document from which it was converted. Returns a unicode string
(``TextStringObject``) or ``None`` if the creator is not specified.
"""
return self._get_text(DI.CREATOR)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L202-L211
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 91.582229 | 10 | 1 | 100 | 6 |
def creator(self) -> Optional[str]:
return self._get_text(DI.CREATOR)
| 24,343 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.creator_raw
|
(self)
|
return self.get(DI.CREATOR)
|
The "raw" version of creator; can return a ``ByteStringObject``.
|
The "raw" version of creator; can return a ``ByteStringObject``.
| 214 | 216 |
def creator_raw(self) -> Optional[str]:
"""The "raw" version of creator; can return a ``ByteStringObject``."""
return self.get(DI.CREATOR)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L214-L216
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.582229 | 3 | 1 | 100 | 1 |
def creator_raw(self) -> Optional[str]:
return self.get(DI.CREATOR)
| 24,344 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.producer
|
(self)
|
return self._get_text(DI.PRODUCER)
|
Read-only property accessing the document's **producer**.
If the document was converted to PDF from another format, this is
the name of the application (for example, OSX Quartz) that converted
it to PDF. Returns a unicode string (``TextStringObject``)
or ``None`` if the producer is not specified.
|
Read-only property accessing the document's **producer**.
| 219 | 228 |
def producer(self) -> Optional[str]:
"""
Read-only property accessing the document's **producer**.
If the document was converted to PDF from another format, this is
the name of the application (for example, OSX Quartz) that converted
it to PDF. Returns a unicode string (``TextStringObject``)
or ``None`` if the producer is not specified.
"""
return self._get_text(DI.PRODUCER)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L219-L228
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 91.582229 | 10 | 1 | 100 | 6 |
def producer(self) -> Optional[str]:
return self._get_text(DI.PRODUCER)
| 24,345 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.producer_raw
|
(self)
|
return self.get(DI.PRODUCER)
|
The "raw" version of producer; can return a ``ByteStringObject``.
|
The "raw" version of producer; can return a ``ByteStringObject``.
| 231 | 233 |
def producer_raw(self) -> Optional[str]:
"""The "raw" version of producer; can return a ``ByteStringObject``."""
return self.get(DI.PRODUCER)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L231-L233
| 39 |
[
0,
1,
2
] | 100 |
[] | 0 | true | 91.582229 | 3 | 1 | 100 | 1 |
def producer_raw(self) -> Optional[str]:
return self.get(DI.PRODUCER)
| 24,346 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.creation_date
|
(self)
|
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
|
Read-only property accessing the document's **creation date**.
|
Read-only property accessing the document's **creation date**.
| 236 | 243 |
def creation_date(self) -> Optional[datetime]:
"""
Read-only property accessing the document's **creation date**.
"""
text = self._get_text(DI.CREATION_DATE)
if text is None:
return None
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L236-L243
| 39 |
[
0,
1,
2,
3,
4,
5,
7
] | 87.5 |
[
6
] | 12.5 | false | 91.582229 | 8 | 2 | 87.5 | 1 |
def creation_date(self) -> Optional[datetime]:
text = self._get_text(DI.CREATION_DATE)
if text is None:
return None
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
| 24,347 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.creation_date_raw
|
(self)
|
return self.get(DI.CREATION_DATE)
|
The "raw" version of creation date; can return a ``ByteStringObject``.
Typically in the format D:YYYYMMDDhhmmss[+-]hh'mm where the suffix is the
offset from UTC.
|
The "raw" version of creation date; can return a ``ByteStringObject``.
| 246 | 253 |
def creation_date_raw(self) -> Optional[str]:
"""
The "raw" version of creation date; can return a ``ByteStringObject``.
Typically in the format D:YYYYMMDDhhmmss[+-]hh'mm where the suffix is the
offset from UTC.
"""
return self.get(DI.CREATION_DATE)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L246-L253
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 91.582229 | 8 | 1 | 100 | 4 |
def creation_date_raw(self) -> Optional[str]:
return self.get(DI.CREATION_DATE)
| 24,348 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.modification_date
|
(self)
|
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
|
Read-only property accessing the document's **modification date**.
The date and time the document was most recently modified.
|
Read-only property accessing the document's **modification date**.
| 256 | 265 |
def modification_date(self) -> Optional[datetime]:
"""
Read-only property accessing the document's **modification date**.
The date and time the document was most recently modified.
"""
text = self._get_text(DI.MOD_DATE)
if text is None:
return None
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L256-L265
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9
] | 100 |
[] | 0 | true | 91.582229 | 10 | 2 | 100 | 3 |
def modification_date(self) -> Optional[datetime]:
text = self._get_text(DI.MOD_DATE)
if text is None:
return None
return datetime.strptime(text.replace("'", ""), "D:%Y%m%d%H%M%S%z")
| 24,349 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
DocumentInformation.modification_date_raw
|
(self)
|
return self.get(DI.MOD_DATE)
|
The "raw" version of modification date; can return a ``ByteStringObject``.
Typically in the format D:YYYYMMDDhhmmss[+-]hh'mm where the suffix is the
offset from UTC.
|
The "raw" version of modification date; can return a ``ByteStringObject``.
| 268 | 275 |
def modification_date_raw(self) -> Optional[str]:
"""
The "raw" version of modification date; can return a ``ByteStringObject``.
Typically in the format D:YYYYMMDDhhmmss[+-]hh'mm where the suffix is the
offset from UTC.
"""
return self.get(DI.MOD_DATE)
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L268-L275
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7
] | 100 |
[] | 0 | true | 91.582229 | 8 | 1 | 100 | 4 |
def modification_date_raw(self) -> Optional[str]:
return self.get(DI.MOD_DATE)
| 24,350 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
PdfReader.__init__
|
(
self,
stream: Union[StrByteType, Path],
strict: bool = False,
password: Union[None, str, bytes] = None,
)
| 297 | 347 |
def __init__(
self,
stream: Union[StrByteType, Path],
strict: bool = False,
password: Union[None, str, bytes] = None,
) -> None:
self.strict = strict
self.flattened_pages: Optional[List[PageObject]] = None
self.resolved_objects: Dict[Tuple[Any, Any], Optional[PdfObject]] = {}
self.xref_index = 0
self._page_id2num: Optional[
Dict[Any, Any]
] = None # map page indirect_reference number to Page Number
if hasattr(stream, "mode") and "b" not in stream.mode: # type: ignore
logger_warning(
"PdfReader stream/file object is not in binary mode. "
"It may not be read correctly.",
__name__,
)
if isinstance(stream, (str, Path)):
with open(stream, "rb") as fh:
stream = BytesIO(fh.read())
self.read(stream)
self.stream = stream
self._override_encryption = False
self._encryption: Optional[Encryption] = None
if self.is_encrypted:
self._override_encryption = True
# Some documents may not have a /ID, use two empty
# byte strings instead. Solves
# https://github.com/py-pdf/pypdf/issues/608
id_entry = self.trailer.get(TK.ID)
id1_entry = id_entry[0].get_object().original_bytes if id_entry else b""
encrypt_entry = cast(
DictionaryObject, self.trailer[TK.ENCRYPT].get_object()
)
self._encryption = Encryption.read(encrypt_entry, id1_entry)
# try empty password if no password provided
pwd = password if password is not None else b""
if (
self._encryption.verify(pwd) == PasswordType.NOT_DECRYPTED
and password is not None
):
# raise if password provided
raise WrongPasswordError("Wrong password")
self._override_encryption = False
else:
if password is not None:
raise PdfReadError("Not encrypted file")
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L297-L347
| 39 |
[
0,
6,
7,
8,
9,
10,
13,
14,
19,
20,
21,
22,
23,
24,
25,
26,
27,
28,
29,
30,
31,
32,
33,
34,
37,
38,
39,
40,
41,
45,
46,
47,
49,
50
] | 66.666667 |
[] | 0 | false | 91.582229 | 51 | 9 | 100 | 0 |
def __init__(
self,
stream: Union[StrByteType, Path],
strict: bool = False,
password: Union[None, str, bytes] = None,
) -> None:
self.strict = strict
self.flattened_pages: Optional[List[PageObject]] = None
self.resolved_objects: Dict[Tuple[Any, Any], Optional[PdfObject]] = {}
self.xref_index = 0
self._page_id2num: Optional[
Dict[Any, Any]
] = None # map page indirect_reference number to Page Number
if hasattr(stream, "mode") and "b" not in stream.mode: # type: ignore
logger_warning(
"PdfReader stream/file object is not in binary mode. "
"It may not be read correctly.",
__name__,
)
if isinstance(stream, (str, Path)):
with open(stream, "rb") as fh:
stream = BytesIO(fh.read())
self.read(stream)
self.stream = stream
self._override_encryption = False
self._encryption: Optional[Encryption] = None
if self.is_encrypted:
self._override_encryption = True
# Some documents may not have a /ID, use two empty
# byte strings instead. Solves
# https://github.com/py-pdf/pypdf/issues/608
id_entry = self.trailer.get(TK.ID)
id1_entry = id_entry[0].get_object().original_bytes if id_entry else b""
encrypt_entry = cast(
DictionaryObject, self.trailer[TK.ENCRYPT].get_object()
)
self._encryption = Encryption.read(encrypt_entry, id1_entry)
# try empty password if no password provided
pwd = password if password is not None else b""
if (
self._encryption.verify(pwd) == PasswordType.NOT_DECRYPTED
and password is not None
):
# raise if password provided
raise WrongPasswordError("Wrong password")
self._override_encryption = False
else:
if password is not None:
raise PdfReadError("Not encrypted file")
| 24,351 |
|||
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
PdfReader.pdf_header
|
(self)
|
return pdf_file_version
|
The first 8 bytes of the file.
This is typically something like ``'%PDF-1.6'`` and can be used to
detect if the file is actually a PDF file and which version it is.
|
The first 8 bytes of the file.
| 350 | 363 |
def pdf_header(self) -> str:
"""
The first 8 bytes of the file.
This is typically something like ``'%PDF-1.6'`` and can be used to
detect if the file is actually a PDF file and which version it is.
"""
# TODO: Make this return a bytes object for consistency
# but that needs a deprecation
loc = self.stream.tell()
self.stream.seek(0, 0)
pdf_file_version = self.stream.read(8).decode("utf-8")
self.stream.seek(loc, 0) # return to where it was
return pdf_file_version
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L350-L363
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
12,
13
] | 100 |
[] | 0 | true | 91.582229 | 14 | 1 | 100 | 4 |
def pdf_header(self) -> str:
# TODO: Make this return a bytes object for consistency
# but that needs a deprecation
loc = self.stream.tell()
self.stream.seek(0, 0)
pdf_file_version = self.stream.read(8).decode("utf-8")
self.stream.seek(loc, 0) # return to where it was
return pdf_file_version
| 24,352 |
py-pdf/pypdf
|
d942a49074de9fb89ea374cd7f36f6d74a4a3451
|
pypdf/_reader.py
|
PdfReader.metadata
|
(self)
|
return retval
|
Retrieve the PDF file's document information dictionary, if it exists.
Note that some PDF files use metadata streams instead of docinfo
dictionaries, and these metadata streams will not be accessed by this
function.
|
Retrieve the PDF file's document information dictionary, if it exists.
Note that some PDF files use metadata streams instead of docinfo
dictionaries, and these metadata streams will not be accessed by this
function.
| 366 | 382 |
def metadata(self) -> Optional[DocumentInformation]:
"""
Retrieve the PDF file's document information dictionary, if it exists.
Note that some PDF files use metadata streams instead of docinfo
dictionaries, and these metadata streams will not be accessed by this
function.
"""
if TK.INFO not in self.trailer:
return None
obj = self.trailer[TK.INFO]
retval = DocumentInformation()
if isinstance(obj, type(None)):
raise PdfReadError(
"trailer not found or does not point to document information directory"
)
retval.update(obj) # type: ignore
return retval
|
https://github.com/py-pdf/pypdf/blob/d942a49074de9fb89ea374cd7f36f6d74a4a3451/project39/pypdf/_reader.py#L366-L382
| 39 |
[
0,
1,
2,
3,
4,
5,
6,
7,
8,
9,
10,
11,
14,
15,
16
] | 88.235294 |
[
12
] | 5.882353 | false | 91.582229 | 17 | 3 | 94.117647 | 4 |
def metadata(self) -> Optional[DocumentInformation]:
if TK.INFO not in self.trailer:
return None
obj = self.trailer[TK.INFO]
retval = DocumentInformation()
if isinstance(obj, type(None)):
raise PdfReadError(
"trailer not found or does not point to document information directory"
)
retval.update(obj) # type: ignore
return retval
| 24,353 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.