stable version

This commit is contained in:
ari committed 2020-10-30 19:13:25 -04:00
1 parent df50637e70
commit 3f5bac98b3
8 files changed
+50 -62

No files matched your search

@@ -16,11 +16,3 @@ class PDFDocumentCatalog(NamedTuple):
metadata: Optional[PDFDictionary]
raw: Dict[str, Any] # for other properties
# def _get_version(buffer: BufferStream) -> Optional[str]:
# with buffer.get_window():
# token = next(iter_tokens(buffer))
# if isinstance(token, TokenComment):
# return token.value.decode()
# return None
+30 -3
View File
@@ -1,8 +1,6 @@
from pathlib import Path
from typing import Any, BinaryIO, Dict, Optional, Tuple, Type, TypeVar
from typing import Any, BinaryIO, Dict, Optional, Set, Tuple, Type, TypeVar
from pdfmajor.document.catalog import PDFDocumentCatalog
from pdfmajor.document.exceptions import InvalidCatalogObj, MissingCatalogObj
from pdfmajor.healthlog import PDFHealthReport
from pdfmajor.parser.objects.base import PDFObject
from pdfmajor.parser.objects.collections import PDFArray, PDFDictionary
@@ -14,6 +12,9 @@ from pdfmajor.xref.exceptions import InvalidNumberOfRoots, NotRootElement
from pdfmajor.xref.trailer import get_root_obj
from pdfmajor.xref.xrefdb import XRefDB
from .exceptions import InvalidCatalogObj, MissingCatalogObj, TooManyInfoObj
from .PDFDocumentCatalog import PDFDocumentCatalog
class PDFParsingContext:
"""A utility class to encapsulate various interactions with the raw document stream"""
@@ -85,6 +86,17 @@ class PDFParsingContext:
self.health_report.write_error(err)
return out
def get_info(self) -> Optional[PDFObject]:
"""get a Parsed version of the PDF Info object if it exists (see PDF spec 1.7 section 14.3.3 for more detail)"""
with self.buffer.get_window():
info_obj = _find_indirect_obj_for_info(
self.xrefdb, self.buffer, self.health_report
)
if info_obj is None:
return None
else:
return info_obj.get_object()
def get_catalog(self) -> PDFDocumentCatalog:
"""Gets the catalog for a document
@@ -155,3 +167,18 @@ def _find_indirect_obj_for_root(
except StopIteration:
raise MissingCatalogObj()
return root_element
def _find_indirect_obj_for_info(
xrefdb: XRefDB, buffer: BufferStream, health_report: PDFHealthReport
) -> Optional[IndirectObject]:
elements: Set[ObjectRef] = set()
for trailer in xrefdb.trailers:
if trailer.info is not None:
elements.add(trailer.info)
if len(elements) > 1:
health_report.write_error(TooManyInfoObj(elements))
elif len(elements) == 0:
return None
ref = next(iter(elements))
return xrefdb.get_obj(ref.obj_num, ref.gen_num, buffer)
+9
View File
@@ -1,4 +1,7 @@
from typing import Set
from pdfmajor.exceptions import BrokenFile, PDFMajorException
from pdfmajor.parser.objects.indirect import ObjectRef
class PDFDocumentError(PDFMajorException):
@@ -11,3 +14,9 @@ class MissingCatalogObj(PDFDocumentError, BrokenFile):
class InvalidCatalogObj(PDFDocumentError, BrokenFile):
pass
class TooManyInfoObj(PDFDocumentError, BrokenFile):
def __init__(self, elms: Set[ObjectRef]) -> None:
super().__init__(f"Too many info elements found | total={elms}")
self.elms = elms
-38
View File
@@ -1,38 +0,0 @@
from datetime import datetime
from typing import Any, Dict, NamedTuple, Optional, Tuple
from pdfmajor.lexer import iter_tokens
from pdfmajor.lexer.token import TokenComment
from pdfmajor.streambuffer import BufferStream
class PDFDocumentParsedMetadata(NamedTuple):
"""A Parsed version of the PDF Metadata object (see PDF spec 1.7 section 14.3.3 for more detail)
Args:
NamedTuple ([type]): [description]
"""
title: str
author: str
subject: str
keywords: str
creator: str
producer: str
creation_date: datetime
mod_date: datetime
trapped: str
mediabox: Tuple[int, int, int, int]
raw_metadata: Dict[str, Any]
@classmethod
def from_bufferstream(cls, buffer: BufferStream):
version = _get_version(buffer)
def _get_version(buffer: BufferStream) -> Optional[str]:
with buffer.get_window():
token = next(iter_tokens(buffer))
if isinstance(token, TokenComment):
return token.value.decode()
return None
+2 -6
View File
@@ -38,10 +38,6 @@ class PDFPrimitiveObject(PDFObject, Generic[T]):
)
class PDFString(PDFPrimitiveObject[bytes]):
pass
class PDFName(PDFPrimitiveObject[str]):
def to_python(self):
return "/" + self.value
@@ -51,7 +47,7 @@ class PDFBoolean(PDFPrimitiveObject[bool]):
pass
class PDFHexString(PDFPrimitiveObject[bytes]):
class PDFString(PDFPrimitiveObject[bytes]):
pass
@@ -74,7 +70,7 @@ _token_to_obj_map: Dict[Type[Token], Type[PDFPrimitiveObject]] = {
TokenName: PDFName,
TokenString: PDFString,
TokenBoolean: PDFBoolean,
TokenHexString: PDFHexString,
TokenHexString: PDFString,
TokenInteger: PDFInteger,
TokenReal: PDFReal,
}
+5 -4
View File
@@ -8,6 +8,7 @@ from pdfmajor.parser.objects.collections import PDFArray, PDFDictionary
from pdfmajor.parser.objects.indirect import ObjectRef
from pdfmajor.parser.objects.primitives import PDFInteger
from pdfmajor.streambuffer import BufferStream
from pdfmajor.util import validate_object_or_none
from .exceptions import BrokenFile, InvalidNumberOfRoots, NotRootElement
@@ -42,8 +43,8 @@ class PDFFileTrailer(NamedTuple):
size: PDFInteger
root: Optional[ObjectRef]
prev: Optional[PDFObject]
info: Optional[PDFObject]
prev: Optional[PDFInteger]
info: Optional[ObjectRef]
encrypt: Optional[PDFObject]
encrypt_id: Optional[PDFArray]
@@ -71,8 +72,8 @@ class PDFFileTrailer(NamedTuple):
return cls(
size=size,
root=root,
prev=pdfdict.get("Prev", None),
info=pdfdict.get("Info", None),
prev=validate_object_or_none(pdfdict.get("Prev", None), PDFInteger),
info=validate_object_or_none(pdfdict.get("Info", None), ObjectRef),
encrypt=encrypt,
encrypt_id=encrypt_id, # type: ignore
)
+2 -1
View File
@@ -1,6 +1,6 @@
from unittest import TestCase
from pdfmajor.document.catalog import PDFDocumentCatalog
from pdfmajor.document.PDFDocumentCatalog import PDFDocumentCatalog
from pdfmajor.document.PDFParsingContext import PDFParsingContext
from pdfmajor.parser.objects.indirect import ObjectRef
from pdfmajor.parser.objects.primitives import (
@@ -76,3 +76,4 @@ class Catalog(TestCase):
parser = PDFParsingContext(buffer)
parser.get_catalog()
self.assertEqual(len(parser.health_report), 0)
parser.get_info()
+2 -2
View File
@@ -8,7 +8,7 @@ from pdfmajor.parser.objects.base import PDFObject
from pdfmajor.parser.objects.collections import PDFArray, PDFDictionary
from pdfmajor.parser.objects.comment import PDFComment
from pdfmajor.parser.objects.indirect import IndirectObject, ObjectRef
from pdfmajor.parser.objects.primitives import PDFHexString, PDFInteger, PDFString
from pdfmajor.parser.objects.primitives import PDFInteger, PDFString
from pdfmajor.parser.stream.PDFStream import PDFStream
from pdfmajor.streambuffer import BufferStream
@@ -146,7 +146,7 @@ class IndirectObjects(TestCase):
""",
expected=[
IndirectObject(12, 1, 18, PDFString(b"Bring", 0, 0)),
IndirectObject(100, 0, 55, PDFHexString(b"3", 0, 0)),
IndirectObject(100, 0, 55, PDFString(b"3", 0, 0)),
IndirectObject(
13,
8,