From 087012dd81ed489a34200cfc5a1b3cd45ec6b3a0 Mon Sep 17 00:00:00 2001 From: Ariel Sosnovsky Date: Thu, 19 Dec 2019 20:08:06 -0500 Subject: [PATCH] all errors caught in one location --- pdfmajor/converters/__init__.py | 5 +- pdfmajor/converters/writers/html.py | 5 +- pdfmajor/converters/writers/json.py | 7 +- pdfmajor/converters/writers/xml.py | 4 +- pdfmajor/converters/writers/yaml.py | 4 +- pdfmajor/execptions.py | 90 ++++++++++++++++++- pdfmajor/interpreter/__init__.py | 6 +- pdfmajor/interpreter/commands/PDFCommands.py | 5 +- pdfmajor/interpreter/commands/__init__.py | 3 +- pdfmajor/interpreter/commands/commands.py | 21 ++--- .../state/PDFTextState/PDFFont/PDFFont.py | 7 +- .../PDFTextState/PDFFont/TrueTypeFont.py | 7 +- .../state/PDFTextState/PDFFont/__init__.py | 8 +- .../state/PDFTextState/PDFFont/execptions.py | 4 - .../state/PDFTextState/PDFFont/fonts.py | 20 ++--- .../commands/state/PDFTextState/__init__.py | 6 +- .../commands/state/layout/_base.py | 2 +- pdfmajor/interpreter/exceptions.py | 3 - pdfmajor/parser/PDFContentParser.py | 6 +- pdfmajor/parser/PDFDocument/PDFXRef.py | 5 +- pdfmajor/parser/PDFDocument/__init__.py | 10 ++- pdfmajor/parser/PDFPage.py | 2 + pdfmajor/parser/PDFParser.py | 7 +- pdfmajor/parser/PDFStream/ccitt.py | 26 ++---- pdfmajor/parser/PSStackParser/PSBaseParser.py | 3 +- pdfmajor/parser/PSStackParser/__init__.py | 16 ++-- pdfmajor/parser/PSStackParser/exceptions.py | 18 ---- pdfmajor/parser/cmapdb/__init__.py | 17 ++-- 28 files changed, 190 insertions(+), 127 deletions(-) delete mode 100644 pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/execptions.py delete mode 100644 pdfmajor/interpreter/exceptions.py diff --git a/pdfmajor/converters/__init__.py b/pdfmajor/converters/__init__.py index 47347cc..f5ac0ef 100644 --- a/pdfmajor/converters/__init__.py +++ b/pdfmajor/converters/__init__.py @@ -10,6 +10,7 @@ from .json import convert_to_json from .text import convert_to_text from .yaml import convert_to_yaml from ..utils import logging +from ..execptions import ConverterException def convert_file( input_file: str, @@ -34,7 +35,7 @@ def convert_file( ) ) if re.search(re.escape(out_type) + r'$', output_file ) is None: - raise Exception("Please make sure that the file name and output type match!") + raise ConverterException("Please make sure that the file name and output type match!") if out_type == 'html': return convert_to_html( input_file_path=input_file, @@ -110,4 +111,4 @@ def convert_file( dont_export_images=dont_export_images, debug_level=debug_level, ) - else: raise Exception("Please specify out_type as 'html' or 'xml' or 'json' or 'text' or 'yaml'") \ No newline at end of file + else: raise ConverterException("Please specify out_type as 'html' or 'xml' or 'json' or 'text' or 'yaml'") \ No newline at end of file diff --git a/pdfmajor/converters/writers/html.py b/pdfmajor/converters/writers/html.py index 78438b0..89961e6 100644 --- a/pdfmajor/converters/writers/html.py +++ b/pdfmajor/converters/writers/html.py @@ -2,8 +2,9 @@ from typing import Optional from io import TextIOWrapper from contextlib import contextmanager +from pdfmajor.execptions import FileAccessException + class HTMLMaker: - class AccessError(Exception): pass def __init__(self, file_path: str, codec: str = 'utf-8'): self.file_path = file_path self.codec = codec @@ -23,7 +24,7 @@ class HTMLMaker: text = text.encode(self.codec) self.outfile.write(text) else: - raise self.AccessError("Attempting to write to file without an open connection") + raise FileAccessException("Attempting to write to file without an open connection") def write(self, text: str, lineend: str = '\n', deep_space: str = ' '): text = deep_space*self.__levels_deep + text + lineend diff --git a/pdfmajor/converters/writers/json.py b/pdfmajor/converters/writers/json.py index 6fd6aec..90ff2ff 100644 --- a/pdfmajor/converters/writers/json.py +++ b/pdfmajor/converters/writers/json.py @@ -2,6 +2,7 @@ from typing import Set from json import dumps as json_dump from io import TextIOWrapper from contextlib import contextmanager +from pdfmajor.execptions import FileAccessException @contextmanager def JSONMaker(file_path: str, codec: str = 'utf-8'): @@ -10,7 +11,6 @@ def JSONMaker(file_path: str, codec: str = 'utf-8'): yield obj class JSONMakerObject: - class AccessError(Exception): pass def __init__(self, outfile: TextIOWrapper, codec: str = 'utf-8', levels_deep: int = 0): self.outfile: TextIOWrapper = outfile self.codec = codec @@ -32,7 +32,7 @@ class JSONMakerObject: text = text.encode(self.codec) self.outfile.write(text) else: - raise self.AccessError("Attempting to write to file without an open connection") + raise FileAccessException("Attempting to write to file without an open connection") def write(self, text: str, deep_space: str = ' ', prefix:str = ''): text = prefix + (deep_space*self.levels_deep) + text @@ -71,7 +71,6 @@ class JSONMakerObject: class JSONMakerArray: - class AccessError(Exception): pass def __init__(self, outfile: TextIOWrapper, codec: str = 'utf-8', levels_deep: int = 0): self.outfile: TextIOWrapper = outfile self.codec = codec @@ -93,7 +92,7 @@ class JSONMakerArray: text = text.encode(self.codec) self.outfile.write(text) else: - raise self.AccessError("Attempting to write to file without an open connection") + raise FileAccessException("Attempting to write to file without an open connection") def write(self, text: str, deep_space: str = ' ', prefix:str = ''): text = prefix + (deep_space*self.levels_deep) + text diff --git a/pdfmajor/converters/writers/xml.py b/pdfmajor/converters/writers/xml.py index e41b153..4d71dc1 100644 --- a/pdfmajor/converters/writers/xml.py +++ b/pdfmajor/converters/writers/xml.py @@ -1,8 +1,8 @@ from io import TextIOWrapper from contextlib import contextmanager +from pdfmajor.execptions import FileAccessException class XMLMaker: - class AccessError(Exception): pass def __init__(self, file_path: str, codec: str = 'utf-8'): self.file_path = file_path self.codec = codec @@ -25,7 +25,7 @@ class XMLMaker: text = text.encode(self.codec) self.outfile.write(text) else: - raise self.AccessError("Attempting to write to file without an open connection") + raise FileAccessException("Attempting to write to file without an open connection") def write(self, text: str, lineend: str = '\n', deep_space: str = ' '): text = deep_space*self.__levels_deep + text + lineend diff --git a/pdfmajor/converters/writers/yaml.py b/pdfmajor/converters/writers/yaml.py index b3ba657..6bdfefc 100644 --- a/pdfmajor/converters/writers/yaml.py +++ b/pdfmajor/converters/writers/yaml.py @@ -1,6 +1,7 @@ from json import dumps as json_dump from io import TextIOWrapper from contextlib import contextmanager +from pdfmajor.execptions import FileAccessException @contextmanager def YAMLMaker(file_path: str, codec: str = 'utf-8'): @@ -9,7 +10,6 @@ def YAMLMaker(file_path: str, codec: str = 'utf-8'): yield obj class YAMLMakerWriter: - class AccessError(Exception): pass def __init__(self, outfile: TextIOWrapper, codec: str = 'utf-8', levels_deep: int = -1): self.outfile: TextIOWrapper = outfile self.codec = codec @@ -30,7 +30,7 @@ class YAMLMakerWriter: text = text.encode(self.codec) self.outfile.write(text) else: - raise self.AccessError("Attempting to write to file without an open connection") + raise FileAccessException("Attempting to write to file without an open connection") def _write(self, text: str, append_deep: bool = True, deep_space: str = ' ', prefix:str = ''): if not append_deep: diff --git a/pdfmajor/execptions.py b/pdfmajor/execptions.py index a9ecf0d..632a512 100644 --- a/pdfmajor/execptions.py +++ b/pdfmajor/execptions.py @@ -1,2 +1,88 @@ -import pdfmajor.parser.exceptions as parser -import pdfmajor.interpreter.exceptions as interpreter \ No newline at end of file + + +class PDFMajorException(Exception): + pass + +# Interpreter Errors +class InterpreterError(PDFMajorException): + pass + +class EmptyDocumentError(InterpreterError): + pass + +class CommandProcessorError(InterpreterError): + pass + +class InvalidOperation(CommandProcessorError): + pass + +class RepeatedCommand(CommandProcessorError): + pass + +class FontError(InterpreterError): + pass + +class UnicodeNotDefined(FontError): + pass + +class MissingFont(FontError): + pass + + +# Parser Errors +class ParserError(PDFMajorException): + pass + +class PDFNoOutlines(ParserError): + pass + +class PDFDestinationNotFound(ParserError): + pass + +class PDFNoValidXRef(ParserError): + pass + +class CMapNotFound(ParserError): + pass + +class PSException(ParserError): + pass + + +class PSEOF(PSException): + pass + + +class PSSyntaxError(PSException): + pass + + +class PSTypeError(PSException): + pass + + +class PSValueError(PSException): + pass + +class CCITTExeception(ParserError): + pass + +class EOFB(CCITTExeception): + pass + +class InvalidData(CCITTExeception): + pass + +class ByteSkip(ExceptCCITTExeceptionion): + pass + +class PDFTextExtractionNotAllowed(ParserError): + pass + +# converter error + +class ConverterException(PDFMajorException): + pass + +class FileAccessException(ConverterException): + pass \ No newline at end of file diff --git a/pdfmajor/interpreter/__init__.py b/pdfmajor/interpreter/__init__.py index 89c175f..dcb4d32 100644 --- a/pdfmajor/interpreter/__init__.py +++ b/pdfmajor/interpreter/__init__.py @@ -1,5 +1,7 @@ from typing import List +from pdfmajor.execptions import EmptyDocumentError + from ..parser.PDFPage import PDFPage from ..utils import set_log_level, get_logger, logging from .commands.state import PDFStateStack, PDFColorSpace, PREDEFINED_COLORSPACE @@ -13,7 +15,6 @@ from .PageInterpreter import PageInterpreter log = get_logger(__name__) class PDFInterpreter: - class AccessError(Exception): pass def __init__(self, input_file_path: str, @@ -58,8 +59,9 @@ class PDFInterpreter: yield self.__pages[-1] log.info(f"Done Reading {len(self.__pages)} pages.") set_log_level(logging.WARNING) + if len(self.__pages) == 0: - raise self.AccessError("No pages found in pdf-file") + raise EmptyDocumentError("No pages found in pdf-file") def __iter__(self): if len(self.__pages) > 0: diff --git a/pdfmajor/interpreter/commands/PDFCommands.py b/pdfmajor/interpreter/commands/PDFCommands.py index c7260b2..1483c43 100644 --- a/pdfmajor/interpreter/commands/PDFCommands.py +++ b/pdfmajor/interpreter/commands/PDFCommands.py @@ -1,5 +1,6 @@ from typing import List +from pdfmajor.execptions import RepeatedCommand from pdfmajor.utils import MATRIX_IDENTITY, mult_matrix from pdfmajor.parser.PSStackParser import literal_name from pdfmajor.parser.PDFStream import PDFStream, list_value, dict_value @@ -7,8 +8,6 @@ from pdfmajor.parser.constants import LITERAL_FORM, LITERAL_IMAGE from .state import PDFStateStack, PDFColorSpace from .state.Curves import CurveMethod, CurvePath, CurvePoint -class PDFCommandsInvalidOperation(Exception): pass -class PDFCommandsRepeatedCommand(Exception): pass class PDFCommands: commands = {} @@ -18,7 +17,7 @@ class PDFCommands: if not (cmd_name in cls.commands.keys()): cls.commands[cmd_name] = cmd return cmd - raise PDFCommandsRepeatedCommand(cmd_name) + raise RepeatedCommand(cmd_name) @classmethod def add(cls, *cmd_names: List[str]): diff --git a/pdfmajor/interpreter/commands/__init__.py b/pdfmajor/interpreter/commands/__init__.py index 531e986..8eb3c73 100644 --- a/pdfmajor/interpreter/commands/__init__.py +++ b/pdfmajor/interpreter/commands/__init__.py @@ -1,5 +1,6 @@ from typing import List +from pdfmajor.execptions import CommandProcessorError from pdfmajor.parser.PDFContentParser import PDFContentParser, PDFStream from pdfmajor.parser.PSStackParser import PSKeyword, keyword_name from pdfmajor.utils import get_logger @@ -17,8 +18,6 @@ from .utils import init_resources log = get_logger('process_command_stream') -class CommandProcessorError(Exception): pass - def process_command_stream(streams: List[PDFStream], font_cache: dict = None, state: PDFStateStack = None): if font_cache is None: font_cache = {} diff --git a/pdfmajor/interpreter/commands/commands.py b/pdfmajor/interpreter/commands/commands.py index 5468198..cb6838f 100644 --- a/pdfmajor/interpreter/commands/commands.py +++ b/pdfmajor/interpreter/commands/commands.py @@ -1,9 +1,10 @@ +from pdfmajor.execptions import InvalidOperation from pdfmajor.utils import mult_matrix, MATRIX_IDENTITY, apply_matrix_pt, get_logger from pdfmajor.parser.PSStackParser import literal_name from pdfmajor.parser.PDFStream import PDFStream, list_value, dict_value from pdfmajor.parser.constants import LITERAL_FORM, LITERAL_IMAGE -from .PDFCommands import PDFCommands, PDFCommandsInvalidOperation, PDFCommandsRepeatedCommand +from .PDFCommands import PDFCommands from .state import PDFStateStack, PDFGraphicState, LTTextBlock from .state.Curves import CurveMethod, CurvePath, CurvePoint # from .state.PDFItem import PDFImage, PDFShape, PDFText, PDFXObject @@ -253,7 +254,7 @@ def set_stroke_colorspace(stack: PDFStateStack, name: str) -> PDFStateStack: stack.graphics.scolspace = stack.colorspace_map[literal_name(name)] return stack except KeyError: - raise PDFCommandsInvalidOperation('Undefined ColorSpace: %r' % name) + raise InvalidOperation('Undefined ColorSpace: %r' % name) # setcolorspace-non-strokine @PDFCommands.add('cs') @@ -262,7 +263,7 @@ def set_nonstroke_colorspace(stack: PDFStateStack, name: str) -> PDFStateStack: stack.graphics.ncolspace = stack.colorspace_map[literal_name(name)] return stack except KeyError: - raise PDFCommandsInvalidOperation('Undefined ColorSpace: %r' % name) + raise InvalidOperation('Undefined ColorSpace: %r' % name) # setgray-stroking @PDFCommands.add('G') @@ -326,7 +327,7 @@ def set_nonstroke_cmyk(stack: PDFStateStack, c, m, y, k) -> PDFStateStack: @PDFCommands.add('SCN','SC') def set_stroke_colorspace_custom(stack: PDFStateStack) -> PDFStateStack: if stack.graphics.scolspace is None: - raise PDFCommandsInvalidOperation('No colorspace specified!') + raise InvalidOperation('No colorspace specified!') components = stack.pop(stack.graphics.scolspace.ncomponents) stack.graphics.set_stroke_color( stack.graphics.scolspace, @@ -337,7 +338,7 @@ def set_stroke_colorspace_custom(stack: PDFStateStack) -> PDFStateStack: @PDFCommands.add('scn','sc') def set_nonstroke_colorspace_custom(stack: PDFStateStack) -> PDFStateStack: if stack.graphics.ncolspace is None: - raise PDFCommandsInvalidOperation('No colorspace specified!') + raise InvalidOperation('No colorspace specified!') components = stack.pop(stack.graphics.ncolspace.ncomponents) stack.graphics.set_nostroke_color( stack.graphics.ncolspace, @@ -353,7 +354,7 @@ def begin_text(stack: PDFStateStack) -> PDFStateStack: if stack.current_textblock is None: stack.current_textblock = LTTextBlock() else: - raise PDFCommandsInvalidOperation("Last TextBlock did not clear") + raise InvalidOperation("Last TextBlock did not clear") return stack @PDFCommands.add('ET') @@ -394,7 +395,7 @@ def set_font(stack: PDFStateStack, fontid, fontsize) -> PDFStateStack: stack.text.font = stack.fontmap[literal_name(fontid)] return stack except KeyError: - raise PDFCommandsInvalidOperation('Undefined Font id: %r' % fontid) + raise InvalidOperation('Undefined Font id: %r' % fontid) # setrendering @PDFCommands.add('Tr') @@ -444,9 +445,9 @@ def nextline(stack: PDFStateStack) -> PDFStateStack: @PDFCommands.add('TJ') def add_char_blocks(stack: PDFStateStack, seq: bytearray) -> PDFStateStack: if stack.text.font is None: - raise PDFCommandsInvalidOperation("No Font Specified") + raise InvalidOperation("No Font Specified") if stack.current_textblock is None: - raise PDFCommandsInvalidOperation("No TextBlock initilized") + raise InvalidOperation("No TextBlock initilized") stack.current_textblock.add_char_block( seq, stack.t_matrix, @@ -487,7 +488,7 @@ def insert_xobject(stack: PDFStateStack, xobjid) -> PDFStateStack: try: xobj = PDFStream.validated_stream(stack.xobjmap[xobjid]) except KeyError: - raise PDFCommandsInvalidOperation('Undefined xobject id: %r' % xobjid) + raise InvalidOperation('Undefined xobject id: %r' % xobjid) # log.info('Processing xobj: %r', xobj) subtype = xobj.get('Subtype') if subtype is LITERAL_FORM and 'BBox' in xobj: diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/PDFFont.py b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/PDFFont.py index 65d1717..341add3 100644 --- a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/PDFFont.py +++ b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/PDFFont.py @@ -2,6 +2,7 @@ from abc import abstractmethod from io import BytesIO +from pdfmajor.execptions import UnicodeNotDefined from pdfmajor.parser.EncodingDB import EncodingDB from pdfmajor.parser.PSStackParser import LIT from pdfmajor.parser.PSStackParser import PSLiteral @@ -13,7 +14,7 @@ from pdfmajor.parser.PDFStream import list_value from pdfmajor.parser.PDFStream import PDFStream from pdfmajor.parser.cmapdb import FileUnicodeMap from pdfmajor.parser.cmapdb import CMapParser -from .execptions import PDFFontError, PDFUnicodeNotDefined + ## Literals ## @@ -75,7 +76,7 @@ class PDFFont(object): except KeyError: try: return self.widths[self.to_unichr(cid)] * self.hscale - except (KeyError, PDFUnicodeNotDefined): + except (KeyError, UnicodeNotDefined): return self.default_width * self.hscale def char_disp(self, cid): @@ -135,4 +136,4 @@ class PDFSimpleFont(PDFFont): try: return self.cid2unicode[cid] except KeyError: - raise PDFUnicodeNotDefined(None, cid) + raise UnicodeNotDefined(None, cid) diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/TrueTypeFont.py b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/TrueTypeFont.py index 26bf7cd..55548a9 100644 --- a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/TrueTypeFont.py +++ b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/TrueTypeFont.py @@ -1,13 +1,10 @@ ## TrueTypeFont ## import struct +from pdfmajor.execptions import CMapNotFound from pdfmajor.parser.cmapdb import FileUnicodeMap - class TrueTypeFont(object): - class CMapNotFound(Exception): - pass - def __init__(self, name, fp): self.name = name self.fp = fp @@ -27,7 +24,7 @@ class TrueTypeFont(object): def create_unicode_map(self): if 'cmap' not in self.tables: - raise TrueTypeFont.CMapNotFound + raise CMapNotFound (base_offset, _) = self.tables['cmap'] fp = self.fp fp.seek(base_offset) diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/__init__.py b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/__init__.py index e530401..4ef00d7 100644 --- a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/__init__.py +++ b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/__init__.py @@ -1,10 +1,10 @@ +from pdfmajor.execptions import FontError from pdfmajor.utils import get_logger, settings from pdfmajor.parser.PSStackParser import literal_name from pdfmajor.parser.PDFStream import list_value from pdfmajor.parser.PDFStream import dict_value from pdfmajor.parser.PDFStream import resolve1 from pdfmajor.parser.constants import LITERAL_FONT -from .execptions import PDFFontError from .fonts import PDFType1Font, PDFTrueTypeFont, PDFType3Font, PDFCIDFont, PDFFont @@ -17,13 +17,13 @@ def get_font(objid: int, spec: dict, cached_fonts: dict = {}): log.debug('get_font: create: objid=%r, spec=%r', objid, spec) if settings.STRICT: if spec['Type'] is not LITERAL_FONT: - raise PDFFontError('Type is not /Font') + raise FontError('Type is not /Font') # Create a Font object. if 'Subtype' in spec: subtype = literal_name(spec['Subtype']) else: if settings.STRICT: - raise PDFFontError('Font Subtype is not specified.') + raise FontError('Font Subtype is not specified.') subtype = 'Type1' if subtype in ('Type1', 'MMType1'): # Type1 Font @@ -48,7 +48,7 @@ def get_font(objid: int, spec: dict, cached_fonts: dict = {}): font = get_font(None, subspec, cached_fonts) else: if settings.STRICT: - raise PDFFontError('Invalid Font spec: %r' % spec) + raise FontError('Invalid Font spec: %r' % spec) font = PDFType1Font(spec) # this is so wrong! if objid: cached_fonts[objid] = font diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/execptions.py b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/execptions.py deleted file mode 100644 index d4c4a67..0000000 --- a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/execptions.py +++ /dev/null @@ -1,4 +0,0 @@ -from pdfmajor.parser.PDFStream import PDFException - -class PDFFontError(PDFException): pass -class PDFUnicodeNotDefined(PDFFontError): pass diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/fonts.py b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/fonts.py index dbd94f1..51b66a2 100644 --- a/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/fonts.py +++ b/pdfmajor/interpreter/commands/state/PDFTextState/PDFFont/fonts.py @@ -1,5 +1,6 @@ from io import BytesIO +from pdfmajor.execptions import FontError, UnicodeNotDefined, CMapNotFound from pdfmajor.parser.PSStackParser import literal_name from pdfmajor.parser.PDFStream import int_value from pdfmajor.parser.PDFStream import num_value @@ -15,7 +16,6 @@ from .PDFFont import PDFFont, PDFSimpleFont from .util import FontMetricsDB, get_widths, get_widths2 from .Type1FontHeaderParser import Type1FontHeaderParser from .TrueTypeFont import TrueTypeFont -from .execptions import PDFFontError, PDFUnicodeNotDefined # PDFType1Font class PDFType1Font(PDFSimpleFont): @@ -25,7 +25,7 @@ class PDFType1Font(PDFSimpleFont): self.basefont = literal_name(spec['BaseFont']) except KeyError: if settings.STRICT: - raise PDFFontError('BaseFont is missing') + raise FontError('BaseFont is missing') self.basefont = 'unknown' try: (descriptor, widths) = FontMetricsDB.get_metrics(self.basefont) @@ -87,7 +87,7 @@ class PDFCIDFont(PDFFont): self.basefont = literal_name(spec['BaseFont']) except KeyError: if strict: - raise PDFFontError('BaseFont is missing') + raise FontError('BaseFont is missing') self.basefont = 'unknown' self.cidsysteminfo = dict_value(spec.get('CIDSystemInfo', {})) self.cidcoding = '%s-%s' % (resolve1(self.cidsysteminfo.get('Registry', b'unknown')).decode("latin1"), @@ -96,19 +96,19 @@ class PDFCIDFont(PDFFont): name = literal_name(spec['Encoding']) except KeyError: if strict: - raise PDFFontError('Encoding is unspecified') + raise FontError('Encoding is unspecified') name = 'unknown' try: self.cmap = CMapDB.get_cmap(name) - except CMapDB.CMapNotFound as e: + except CMapNotFound as e: if strict: - raise PDFFontError(e) + raise FontError(e) self.cmap = CMap() try: descriptor = dict_value(spec['FontDescriptor']) except KeyError: if strict: - raise PDFFontError('FontDescriptor is missing') + raise FontError('FontDescriptor is missing') descriptor = {} ttf = None if 'FontFile2' in descriptor: @@ -124,12 +124,12 @@ class PDFCIDFont(PDFFont): if ttf: try: self.unicode_map = ttf.create_unicode_map() - except TrueTypeFont.CMapNotFound: + except CMapNotFound: pass else: try: self.unicode_map = CMapDB.get_unicode_map(self.cidcoding, self.cmap.is_vertical()) - except CMapDB.CMapNotFound as e: + except CMapNotFound as e: pass self.vertical = self.cmap.is_vertical() @@ -172,4 +172,4 @@ class PDFCIDFont(PDFFont): raise KeyError(cid) return self.unicode_map.get_unichr(cid) except KeyError: - raise PDFUnicodeNotDefined(self.cidcoding, cid) + raise UnicodeNotDefined(self.cidcoding, cid) diff --git a/pdfmajor/interpreter/commands/state/PDFTextState/__init__.py b/pdfmajor/interpreter/commands/state/PDFTextState/__init__.py index 1d1a5e5..bdc3811 100644 --- a/pdfmajor/interpreter/commands/state/PDFTextState/__init__.py +++ b/pdfmajor/interpreter/commands/state/PDFTextState/__init__.py @@ -1,6 +1,6 @@ +from pdfmajor.execptions import MissingFont, UnicodeNotDefined from pdfmajor.utils import MATRIX_IDENTITY from .PDFFont import PDFFont, get_font -from .PDFFont.execptions import PDFUnicodeNotDefined, PDFFontError ## PDFTextState ## @@ -29,10 +29,10 @@ class PDFTextState(object): def to_unichr(self, cid: int) -> str: if self.font is None: - raise PDFFontError("Missing font") + raise MissingFont try: return self.font.to_unichr(cid) - except PDFUnicodeNotDefined as e: + except UnicodeNotDefined as e: if self.ignore_bad_chars: return "" else: diff --git a/pdfmajor/interpreter/commands/state/layout/_base.py b/pdfmajor/interpreter/commands/state/layout/_base.py index 7491fa8..76f4799 100644 --- a/pdfmajor/interpreter/commands/state/layout/_base.py +++ b/pdfmajor/interpreter/commands/state/layout/_base.py @@ -13,7 +13,7 @@ class LTComponent(LTItem): if isinstance(bbox, Bbox): self.bbox = bbox else: - raise Exception("Invalid BBox") + raise AssertionError("Expected a BBox") def __repr__(self): return ('<%s %s>' % diff --git a/pdfmajor/interpreter/exceptions.py b/pdfmajor/interpreter/exceptions.py deleted file mode 100644 index 252f13b..0000000 --- a/pdfmajor/interpreter/exceptions.py +++ /dev/null @@ -1,3 +0,0 @@ -from .commands import CommandProcessorError -from .commands.PDFCommands import PDFCommandsRepeatedCommand, PDFCommandsInvalidOperation -from .commands.state.PDFTextState.PDFFont.execptions import * \ No newline at end of file diff --git a/pdfmajor/parser/PDFContentParser.py b/pdfmajor/parser/PDFContentParser.py index ee35737..98ef0da 100644 --- a/pdfmajor/parser/PDFContentParser.py +++ b/pdfmajor/parser/PDFContentParser.py @@ -4,11 +4,11 @@ import operator from typing import List from io import BytesIO +from pdfmajor.execptions import PSEOF, PSTypeError from ..utils import int2byte, choplist, settings from .PSStackParser import literal_name from .PSStackParser import PSStackParser -from .PSStackParser import PSEOF, PSTypeError from .PSStackParser import KWD from .PDFStream import PDFStream @@ -101,9 +101,9 @@ class PDFContentParser(PSStackParser): obj = PDFStream(d, data) self.push((pos, obj)) self.push((pos, self.KEYWORD_EI)) - except PSTypeError: + except PSTypeError as e: if settings.STRICT: - raise + raise e else: self.push((pos, token)) return diff --git a/pdfmajor/parser/PDFDocument/PDFXRef.py b/pdfmajor/parser/PDFDocument/PDFXRef.py index 36c7aea..ad3414b 100644 --- a/pdfmajor/parser/PDFDocument/PDFXRef.py +++ b/pdfmajor/parser/PDFDocument/PDFXRef.py @@ -2,8 +2,9 @@ import re from logging import getLogger from typing import Tuple, Optional, Dict +from pdfmajor.execptions import PSEOF + from ...utils import settings, choplist, nunpack -from ..PSStackParser import PSEOF from ..PSStackParser import KWD from ..PDFParser import PDFStreamParser from ..PDFStream import PDFStream @@ -105,7 +106,7 @@ class PDFXRef(PDFBaseXRef): try: return self.offsets[objid] except KeyError: - raise + raise PDFSyntaxError ## PDFXRefFallback diff --git a/pdfmajor/parser/PDFDocument/__init__.py b/pdfmajor/parser/PDFDocument/__init__.py index d3eaa0d..4130649 100644 --- a/pdfmajor/parser/PDFDocument/__init__.py +++ b/pdfmajor/parser/PDFDocument/__init__.py @@ -4,6 +4,13 @@ from Crypto.Cipher import ARC4, AES from Crypto.Hash import SHA256 from logging import getLogger +from pdfmajor.execptions import ( + ParserError, + PDFNoOutlines, + PDFDestinationNotFound, + PDFNoValidXRef +) + from ...utils import settings, choplist, decode_text from ..PSStackParser import KWD from ..PSStackParser import literal_name @@ -12,7 +19,6 @@ from ..PDFStream import int_value, str_value, dict_value, list_value, decipher_a from ..PDFStream import PDFObjectNotFound, PDFTypeError from ..PDFParser import PDFStreamParser, PDFStream, PDFSyntaxError -from .exceptions import * from .PDFSecurityHandler import PDFStandardSecurityHandler from .PDFSecurityHandler import PDFStandardSecurityHandlerV4 from .PDFSecurityHandler import PDFStandardSecurityHandlerV5 @@ -181,7 +187,7 @@ class PDFDocument(object): def getobj(self, objid): assert objid != 0 if not self.xrefs: - raise PDFException('PDFDocument is not initialized') + raise ParserError('PDFDocument is not initialized') log.debug('getobj: objid=%r', objid) if objid in self._cached_objs: (obj, genno) = self._cached_objs[objid] diff --git a/pdfmajor/parser/PDFPage.py b/pdfmajor/parser/PDFPage.py index cb47b52..60980aa 100644 --- a/pdfmajor/parser/PDFPage.py +++ b/pdfmajor/parser/PDFPage.py @@ -1,5 +1,7 @@ import logging + +from ..execptions import PDFTextExtractionNotAllowed from ..utils import settings from .constants import LIT from .PDFStream import PDFObjectNotFound diff --git a/pdfmajor/parser/PDFParser.py b/pdfmajor/parser/PDFParser.py index cdcf219..0610dd1 100644 --- a/pdfmajor/parser/PDFParser.py +++ b/pdfmajor/parser/PDFParser.py @@ -2,10 +2,11 @@ import logging from io import BytesIO, TextIOWrapper from ..utils import settings - +from pdfmajor.execptions import ( + PSSyntaxError, + PSEOF, +) from .PSStackParser import PSStackParser -from .PSStackParser import PSSyntaxError -from .PSStackParser import PSEOF from .PSStackParser import KWD from .PDFStream import PDFException from .PDFStream import PDFStream diff --git a/pdfmajor/parser/PDFStream/ccitt.py b/pdfmajor/parser/PDFStream/ccitt.py index 5f31687..e1d47b9 100644 --- a/pdfmajor/parser/PDFStream/ccitt.py +++ b/pdfmajor/parser/PDFStream/ccitt.py @@ -12,6 +12,7 @@ import sys import array +from pdfmajor.execptions import EOFB, InvalidData, ByteSkip from abc import abstractmethod def get_bytes(data): @@ -319,15 +320,6 @@ class CCITTG4Parser(BitParser): BitParser.add(UNCOMPRESSED, 'T00000', '00000000011') BitParser.add(UNCOMPRESSED, 'T10000', '00000000010') - class EOFB(Exception): - pass - - class InvalidData(Exception): - pass - - class ByteSkip(Exception): - pass - def __init__(self, width, bytealign=False): BitParser.__init__(self) self.width = width @@ -340,10 +332,10 @@ class CCITTG4Parser(BitParser): try: for m in (128, 64, 32, 16, 8, 4, 2, 1): self._parse_bit(byte & m) - except self.ByteSkip: + except ByteSkip: self._accept = self._parse_mode self._state = self.MODE - except self.EOFB: + except EOFB: break return @@ -363,17 +355,17 @@ class CCITTG4Parser(BitParser): self._accept = self._parse_uncompressed return self.UNCOMPRESSED elif mode == 'e': - raise self.EOFB + raise EOFB elif isinstance(mode, int): self._do_vertical(mode) self._flush_line() return self.MODE else: - raise self.InvalidData(mode) + raise InvalidData(mode) def _parse_horiz1(self, n): if n is None: - raise self.InvalidData + raise InvalidData self._n1 += n if n < 64: self._n2 = 0 @@ -386,7 +378,7 @@ class CCITTG4Parser(BitParser): def _parse_horiz2(self, n): if n is None: - raise self.InvalidData + raise InvalidData self._n2 += n if n < 64: self._color = 1-self._color @@ -401,7 +393,7 @@ class CCITTG4Parser(BitParser): def _parse_uncompressed(self, bits): if not bits: - raise self.InvalidData + raise InvalidData if bits.startswith('T'): self._accept = self._parse_mode self._color = int(bits[1]) @@ -449,7 +441,7 @@ class CCITTG4Parser(BitParser): self._y += 1 self._reset_line() if self.bytealign: - raise self.ByteSkip + raise ByteSkip return def _do_vertical(self, dx): diff --git a/pdfmajor/parser/PSStackParser/PSBaseParser.py b/pdfmajor/parser/PSStackParser/PSBaseParser.py index 314aa55..707e575 100644 --- a/pdfmajor/parser/PSStackParser/PSBaseParser.py +++ b/pdfmajor/parser/PSStackParser/PSBaseParser.py @@ -4,9 +4,10 @@ log = logging.getLogger(__name__) from io import TextIOWrapper from typing import List, Tuple, Union + +from pdfmajor.execptions import PSEOF from ...utils import int2byte -from .exceptions import PSEOF from .constants import EOL, NONSPC, KWD, END_LITERAL, LIT, HEX from .constants import SPC, HEX_PAIR from .constants import END_NUMBER, END_STRING, END_KEYWORD, END_HEX_STRING diff --git a/pdfmajor/parser/PSStackParser/__init__.py b/pdfmajor/parser/PSStackParser/__init__.py index d41e5fe..e741357 100644 --- a/pdfmajor/parser/PSStackParser/__init__.py +++ b/pdfmajor/parser/PSStackParser/__init__.py @@ -1,6 +1,8 @@ import logging from io import TextIOWrapper +from pdfmajor.execptions import PSSyntaxError, PSTypeError + from ...utils import choplist, settings from .PSBaseParser import PSBaseParser @@ -121,9 +123,9 @@ class PSStackParser(PSBaseParser): # end array try: self.push(self.end_type('a')) - except PSTypeError: + except PSTypeError as e: if settings.STRICT: - raise + raise e elif token == KEYWORD_DICT_BEGIN: # begin dictionary self.start_type(pos, 'd') @@ -136,9 +138,9 @@ class PSStackParser(PSBaseParser): # construct a Python dictionary. d = dict((literal_name(k), v) for (k, v) in choplist(2, objs) if v is not None) self.push((pos, d)) - except PSTypeError: + except PSTypeError as e: if settings.STRICT: - raise + raise e elif token == KEYWORD_PROC_BEGIN: # begin proc self.start_type(pos, 'p') @@ -146,16 +148,16 @@ class PSStackParser(PSBaseParser): # end proc try: self.push(self.end_type('p')) - except PSTypeError: + except PSTypeError as e: if settings.STRICT: - raise + raise e elif isinstance(token,PSKeyword): log.debug('do_keyword: pos=%r, token=%r, stack=%r', pos, token, self.curstack) self.do_keyword(pos, token) else: log.error('unknown token: pos=%r, token=%r, stack=%r', pos, token, self.curstack) self.do_keyword(pos, token) - raise Exception("unknown tokens") + raise PSSyntaxError("unknown tokens") if self.context: continue else: diff --git a/pdfmajor/parser/PSStackParser/exceptions.py b/pdfmajor/parser/PSStackParser/exceptions.py index 75c3fba..91025dc 100644 --- a/pdfmajor/parser/PSStackParser/exceptions.py +++ b/pdfmajor/parser/PSStackParser/exceptions.py @@ -1,20 +1,2 @@ ## PS Exceptions ## -class PSException(Exception): - pass - - -class PSEOF(PSException): - pass - - -class PSSyntaxError(PSException): - pass - - -class PSTypeError(PSException): - pass - - -class PSValueError(PSException): - pass \ No newline at end of file diff --git a/pdfmajor/parser/cmapdb/__init__.py b/pdfmajor/parser/cmapdb/__init__.py index 8f8b20e..68d9cff 100644 --- a/pdfmajor/parser/cmapdb/__init__.py +++ b/pdfmajor/parser/cmapdb/__init__.py @@ -19,10 +19,13 @@ import pickle as pickle import struct import logging +from pdfmajor.execptions import ( + CMapNotFound, + PSEOF, + PSSyntaxError, +) from ...utils import choplist, nunpack, name2unicode from ..PSStackParser import PSStackParser -from ..PSStackParser import PSSyntaxError -from ..PSStackParser import PSEOF from ..PSStackParser import PSLiteral from ..PSStackParser import KWD from ..PSStackParser import literal_name @@ -30,9 +33,6 @@ from ..PSStackParser import literal_name log = logging.getLogger(__name__) -class CMapError(Exception): - pass - ## CMapBase ## @@ -219,9 +219,6 @@ class CMapDB(object): _cmap_cache = {} _umap_cache = {} - class CMapNotFound(CMapError): - pass - @classmethod def _load_data(klass, name): name = name.replace("\0", "") @@ -238,7 +235,7 @@ class CMapDB(object): finally: gzfile.close() else: - raise CMapDB.CMapNotFound(name) + raise CMapNotFound(name) @classmethod def get_cmap(klass, name): @@ -325,7 +322,7 @@ class CMapParser(PSStackParser): self.cmap.use_cmap(CMapDB.get_cmap(literal_name(cmapname))) except PSSyntaxError: pass - except CMapDB.CMapNotFound: + except CMapNotFound: pass return