From 18cb345e0db4821e274644c7a9f6424ecb6598a8 Mon Sep 17 00:00:00 2001 From: Ari Sosnovsky Date: Sun, 15 Nov 2020 17:22:14 -0500 Subject: [PATCH] added some more fonts --- README.md | 1 + pdfmajor/document/page_parser/resources.py | 18 ++++++---- pdfmajor/document/parsers/resources.py | 35 ++++++++++++++++++++ pdfmajor/fonts/__init__.py | 29 +++++++++++++++- pdfmajor/fonts/base.py | 14 ++------ pdfmajor/fonts/cidfont.py | 12 +++++++ pdfmajor/fonts/exceptions.py | 10 ++++++ pdfmajor/fonts/{type1.py => simple_fonts.py} | 10 ++++-- pdfmajor/fonts/type0.py | 12 +++++++ pdfmajor/fonts/type3.py | 12 +++++++ pdfmajor/util.py | 15 ++++++++- tests/test_fonts.py | 8 ++--- 12 files changed, 148 insertions(+), 28 deletions(-) create mode 100644 pdfmajor/document/parsers/resources.py create mode 100644 pdfmajor/fonts/cidfont.py create mode 100644 pdfmajor/fonts/exceptions.py rename pdfmajor/fonts/{type1.py => simple_fonts.py} (89%) create mode 100644 pdfmajor/fonts/type0.py create mode 100644 pdfmajor/fonts/type3.py diff --git a/README.md b/README.md index b4a2c48..1c7fb52 100644 --- a/README.md +++ b/README.md @@ -6,6 +6,7 @@ - [ ] Encryption - [ ] Support all stream filters - [ ] Font support +- [ ] Type 3 fond support - [ ] Color spacing diff --git a/pdfmajor/document/page_parser/resources.py b/pdfmajor/document/page_parser/resources.py index aa4051a..78ef75b 100644 --- a/pdfmajor/document/page_parser/resources.py +++ b/pdfmajor/document/page_parser/resources.py @@ -1,14 +1,18 @@ -from typing import Any, Dict, List, NamedTuple, Union +from typing import Any, Dict, List, NamedTuple, Union # noqa from pdfmajor.fonts import PDFFont class PDFResources(NamedTuple): """A class storing PDF Resources as described in PDF spec 1.7. section 7.8.3""" - extgstate: Dict[str, Any] - color_space: Dict[str, Union[str, List[str]]] - pattern: Dict[str, Any] - shading: Dict[str, Any] - xobject: Dict[str, Any] font: Dict[str, PDFFont] - procset: Dict[str, Any] + + # TODO: the rest + # extgstate: Dict[str, Any] + # color_space: Dict[str, Union[str, List[str]]] + # pattern: Dict[str, Any] + # shading: Dict[str, Any] + # xobject: Dict[str, Any] + # procset: Dict[str, Any] + + raw: Dict[str, Any] diff --git a/pdfmajor/document/parsers/resources.py b/pdfmajor/document/parsers/resources.py new file mode 100644 index 0000000..76bec4f --- /dev/null +++ b/pdfmajor/document/parsers/resources.py @@ -0,0 +1,35 @@ +from pdfmajor.document.exceptions import BrokenFilePDF +from pdfmajor.pdf_parser.objects.ref import ObjectRef +from pdfmajor.fonts import PDFFont, PDFFontType1 +from typing import Dict, Iterator, Tuple +from pdfmajor.pdf_parser import PDFDictionary +from ..page_parser.resources import PDFResources +from ..parse_context import PDFParsingContext + + +def get_resources( + pctx: PDFParsingContext, resource_pdfdict: PDFDictionary +) -> PDFResources: + fonts_obj = resource_pdfdict.get("Font", PDFDictionary()) + if not isinstance(fonts_obj, PDFDictionary): + raise BrokenFilePDF(f"Invalid font obj {fonts_obj}") + fonts: Dict[str, PDFFont] = dict(_parse_out_fonts(pctx, fonts_obj)) + + return PDFResources(font=fonts, raw=resource_pdfdict) + + +def _parse_out_fonts( + pctx: PDFParsingContext, font_pdfdict: PDFDictionary +) -> Iterator[Tuple[str, PDFFont]]: + for font_alias, font_ref in font_pdfdict.items(): + if isinstance(font_ref, ObjectRef): + font_obj = pctx.get_object_from_ref(font_ref).get_object() + if not isinstance(font_obj, PDFDictionary): + raise BrokenFilePDF(f"Invalid font {font_obj}") + elif isinstance(font_ref, PDFDictionary): + font_obj = font_ref + else: + raise BrokenFilePDF(f"Invalid font {font_ref}") + subtype = font_obj["Subtype"] + if subtype.to_python() in ["/Type1", "/MMType1"]: + yield font_alias, PDFFontType1.from_dict(font_obj) diff --git a/pdfmajor/fonts/__init__.py b/pdfmajor/fonts/__init__.py index 77cb7e9..7c996b5 100644 --- a/pdfmajor/fonts/__init__.py +++ b/pdfmajor/fonts/__init__.py @@ -1,3 +1,30 @@ +from pdfmajor.fonts.exceptions import InvalidFont +from typing import Any, Dict from .base import PDFFont -from .type1 import PDFFontType1 +from .type3 import PDFType3Font +from .simple_fonts import PDFSimpleFont +from .cidfont import PDFCIDFont +from .type0 import PDFType0Font from . import standard14 + + +def make_font(spec: Dict[str, Any]) -> PDFFont: + subtype = str(spec["Subtype"]) + if subtype in ("Type1", "MMType1", "TrueType"): + return PDFSimpleFont.from_dict(spec) + elif subtype == "Type3": + return PDFType3Font.from_dict(spec) + elif subtype in ("CIDFontType0", "CIDFontType2"): + return PDFCIDFont.from_dict(spec) + elif subtype == "Type0": + return PDFType0Font.from_dict(spec) + # Type0 Font + # dfonts = list_value(spec["DescendantFonts"]) + # assert dfonts + # subspec = dict_value(dfonts[0]).copy() + # for k in ("Encoding", "ToUnicode"): + # if k in spec: + # subspec[k] = resolve1(spec[k]) + # font = get_font(None, subspec, cached_fonts) + else: + raise InvalidFont(subtype) diff --git a/pdfmajor/fonts/base.py b/pdfmajor/fonts/base.py index f4cdf0c..ca0294b 100644 --- a/pdfmajor/fonts/base.py +++ b/pdfmajor/fonts/base.py @@ -1,21 +1,11 @@ from abc import ABCMeta, abstractclassmethod -from typing import Any, Dict, Literal, Union - -FontType = Union[ - Literal["Type0"], - Literal["Type1"], - Literal["MMType1"], - Literal["Type3"], - Literal["TrueType"], - Literal["CIDFontType0"], - Literal["CIDFontType2"], -] +from typing import Any, Dict class PDFFont(metaclass=ABCMeta): """an object reprsenting a PDF Font as decribed in PDF Spec 1.7 section 9.5""" - def __init__(self, subtype: FontType, **kwrg: Any) -> None: + def __init__(self, subtype: str, **kwrg: Any) -> None: self.subtype = subtype self.raw = kwrg diff --git a/pdfmajor/fonts/cidfont.py b/pdfmajor/fonts/cidfont.py new file mode 100644 index 0000000..eb67140 --- /dev/null +++ b/pdfmajor/fonts/cidfont.py @@ -0,0 +1,12 @@ +from typing import Any, Dict +from .base import PDFFont + + +class PDFCIDFont(PDFFont): + """PDF Type 3 object see PDF spec 1.7 section 9.7.2 + TODO: finish this + """ + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "PDFCIDFont": + return cls("Type3", **d) diff --git a/pdfmajor/fonts/exceptions.py b/pdfmajor/fonts/exceptions.py new file mode 100644 index 0000000..e9aa716 --- /dev/null +++ b/pdfmajor/fonts/exceptions.py @@ -0,0 +1,10 @@ +from pdfmajor.exceptions import PDFMajorException + + +class PDFFontError(PDFMajorException): + pass + + +class InvalidFont(PDFFontError): + def __init__(self, subtype: str) -> None: + super().__init__(f"The font {subtype} is invalid") diff --git a/pdfmajor/fonts/type1.py b/pdfmajor/fonts/simple_fonts.py similarity index 89% rename from pdfmajor/fonts/type1.py rename to pdfmajor/fonts/simple_fonts.py index eda879b..a70af3e 100644 --- a/pdfmajor/fonts/type1.py +++ b/pdfmajor/fonts/simple_fonts.py @@ -4,11 +4,12 @@ from .base import PDFFont from . import standard14 -class PDFFontType1(PDFFont): +class PDFSimpleFont(PDFFont): """A standard font in the PDF, as is defined by PDF spec 1.7 section 9.6.2""" def __init__( self, + subtype: str, base_font: str, widths: Dict[int, int], font_descriptor: Dict[str, int], @@ -17,7 +18,7 @@ class PDFFontType1(PDFFont): ) -> None: PDFFont.__init__( self, - "Type1", + subtype, base_font=base_font, widths=widths, font_descriptor=font_descriptor, @@ -31,13 +32,15 @@ class PDFFontType1(PDFFont): self.to_unicode = to_unicode @classmethod - def from_dict(cls, d: Dict[str, Any]) -> "PDFFontType1": + def from_dict(cls, d: Dict[str, Any]) -> "PDFSimpleFont": + subtype = str(d["Subtype"]) base_font = str(d["BaseFont"]) stnd_font = standard14.get_ifexists(base_font) encoding = d.get("Encoding", None) to_unicode = d.get("ToUnicode", None) if stnd_font is not None: return cls( + subtype=subtype, base_font=base_font, widths={k: v for k, v in zip(stnd_font.char_codes, stnd_font.widths)}, font_descriptor=stnd_font.descriptor, @@ -53,6 +56,7 @@ class PDFFontType1(PDFFont): widths_array = (0 for _ in range((last_char - first_char + 1))) font_descriptor = dict(d["FontDescriptor"]) # type: Any return cls( + subtype=subtype, base_font=base_font, widths={(i + first_char): w for (i, w) in enumerate(widths_array)}, font_descriptor=font_descriptor, diff --git a/pdfmajor/fonts/type0.py b/pdfmajor/fonts/type0.py new file mode 100644 index 0000000..487ebd3 --- /dev/null +++ b/pdfmajor/fonts/type0.py @@ -0,0 +1,12 @@ +from typing import Any, Dict +from .base import PDFFont + + +class PDFType0Font(PDFFont): + """PDF Type 30 object see PDF spec 1.7 section 9.6 + TODO: finish this + """ + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "PDFType0Font": + return cls("Type3", **d) diff --git a/pdfmajor/fonts/type3.py b/pdfmajor/fonts/type3.py new file mode 100644 index 0000000..6a6b9b3 --- /dev/null +++ b/pdfmajor/fonts/type3.py @@ -0,0 +1,12 @@ +from typing import Any, Dict +from .base import PDFFont + + +class PDFType3Font(PDFFont): + """PDF Type 3 object see PDF spec 1.7 section 9.6.5 + TODO: finish this + """ + + @classmethod + def from_dict(cls, d: Dict[str, Any]) -> "PDFType3Font": + return cls("Type3", **d) diff --git a/pdfmajor/util.py b/pdfmajor/util.py index ff729e7..16a9309 100644 --- a/pdfmajor/util.py +++ b/pdfmajor/util.py @@ -1,4 +1,4 @@ -from typing import List, Optional, TypeVar, Union +from typing import Any, Dict, List, Optional, TypeVar, Union T = TypeVar("T") @@ -10,3 +10,16 @@ def get_single_or_list(obj: Optional[Union[List[T], T]]) -> List[T]: return obj else: return [obj] + + +D = TypeVar("D", bound=Dict) + + +def deep_copy(dst: D, src: D): + for (k, v) in src.items(): + if isinstance(v, dict): + d: Any = {} + dst[k] = d + deep_copy(d, v) + else: + dst[k] = v diff --git a/tests/test_fonts.py b/tests/test_fonts.py index 41e608c..dabfb25 100644 --- a/tests/test_fonts.py +++ b/tests/test_fonts.py @@ -1,5 +1,5 @@ from unittest import TestCase -from pdfmajor.fonts import standard14, PDFFontType1 +from pdfmajor.fonts import standard14, PDFSimpleFont class Standard14(TestCase): @@ -159,7 +159,7 @@ class Parser(TestCase): 333, ], } - font = PDFFontType1.from_dict(raw) + font = PDFSimpleFont.from_dict(raw) self.assertEqual(font.subtype, "Type1") self.assertEqual(font.base_font, "TimesNewRomanPS-ItalicMT") self.assertEqual(font.encoding, "WinAnsiEncoding") @@ -174,8 +174,8 @@ class Parser(TestCase): ) def test_type1_known(self): - raw = {"BaseFont": "Symbol", "Encoding": "WinAnsiEncoding"} - font = PDFFontType1.from_dict(raw) + raw = {"BaseFont": "Symbol", "Encoding": "WinAnsiEncoding", "Subtype": "Type1"} + font = PDFSimpleFont.from_dict(raw) self.assertEqual(font.subtype, "Type1") self.assertEqual(font.base_font, "Symbol") self.assertEqual(font.encoding, "WinAnsiEncoding")