Compare commits
110
Commits
1.3.12
...
feature/v2
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
c383d992a1 | ||
|
|
18cb345e0d | ||
|
|
9dfde10c39 | ||
|
|
96ba7f25cd | ||
|
|
6bd957921b | ||
|
|
a545692c20 | ||
|
|
00d8fe72d8 | ||
|
|
69d562ce19 | ||
|
|
188c97c469 | ||
|
|
e823f939cf | ||
|
|
3a7cffb10b | ||
|
|
11e466cd5d | ||
|
|
0ba835d577 | ||
|
|
14df0a1600 | ||
|
|
e47475b95f | ||
|
|
6e43a92517 | ||
|
|
8813532b83 | ||
|
|
14cb2e31d5 | ||
|
|
3bb668a705 | ||
|
|
3e81a6c910 | ||
|
|
50d52cda47 | ||
|
|
54179b7dd1 | ||
|
|
f6b3252088 | ||
|
|
76d64a2f20 | ||
|
|
b48d635ec7 | ||
|
|
ffb7b843ea | ||
|
|
da6e7a7a28 | ||
|
|
e33d13a3e1 | ||
|
|
3f5bac98b3 | ||
|
|
df50637e70 | ||
|
|
1829277245 | ||
|
|
44ad73a44c | ||
|
|
e8b31ebee0 | ||
|
|
d40da248de | ||
|
|
838ed91c5f | ||
|
|
3b82f4c309 | ||
|
|
68dd42fea1 | ||
|
|
343a0ae4de | ||
|
|
b40d2bf6e5 | ||
|
|
ee011a5da0 | ||
|
|
4e3b3e10b7 | ||
|
|
78175d3a64 | ||
|
|
5af06a3f1e | ||
|
|
4653b53a6c | ||
|
|
3d39bd575f | ||
|
|
087c1c2fe9 | ||
|
|
e2a92517cd | ||
|
|
cfc2dfca47 | ||
|
|
754e248aac | ||
|
|
b1edcbe51d | ||
|
|
37e567a352 | ||
|
|
39501b174b | ||
|
|
cb7219a152 | ||
|
|
f587a4389f | ||
|
|
4d1e0f2389 | ||
|
|
5fd03d1250 | ||
|
|
77b3754ff4 | ||
|
|
07244aaf11 | ||
|
|
b802f782fa | ||
|
|
6e7c1f3888 | ||
|
|
cc0f802a10 | ||
|
|
43ed8b4019 | ||
|
|
c7d618284b | ||
|
|
3fec7a1747 | ||
|
|
3a5f8f44a3 | ||
|
|
adf04aa50c | ||
|
|
0f147bb66a | ||
|
|
4f8bcf1fff | ||
|
|
6d9a57c722 | ||
|
|
039f06c396 | ||
|
|
71a37477ae | ||
|
|
01ace1c57d | ||
|
|
7ee8254edb | ||
|
|
4e1f45e205 | ||
|
|
da936e6a48 | ||
|
|
472942867b | ||
|
|
24b9c99ea1 | ||
|
|
fa9e936f4a | ||
|
|
a03857d0f7 | ||
|
|
c752346638 | ||
|
|
0eb5e4b8fc | ||
|
|
370a1b40a1 | ||
|
|
faaf7925bf | ||
|
|
a2d2b7808d | ||
|
|
1acd59c008 | ||
|
|
052a3a071e | ||
|
|
81c664ae86 | ||
|
|
28110c9a0e | ||
|
|
af927e86ec | ||
|
|
4a6b0608a0 | ||
|
|
5f19f71c4d | ||
|
|
96d68cdf68 | ||
|
|
d8be2885b8 | ||
|
|
be2778bffc | ||
|
|
9e6422e0eb | ||
|
|
0e0a28154d | ||
|
|
e1e644cc38 | ||
|
|
c430c57fe0 | ||
|
|
ab657deda4 | ||
|
|
a0cc862804 | ||
|
|
da066edaf5 | ||
|
|
460d213700 | ||
|
|
fe9fd304ab | ||
|
|
5b9bbcacbf | ||
|
|
7e24c64b5b | ||
|
|
cdcd2eabe2 | ||
|
|
fdd2fbd85a | ||
|
|
087012dd81 | ||
|
|
630b3b2418 | ||
|
|
441abc3f55 |
No files matched your search
+1
-1
@@ -6,4 +6,4 @@ indent_size = 4
|
||||
end_of_line = lf
|
||||
charset = utf-8
|
||||
trim_trailing_whitespace = false
|
||||
insert_final_newline = false
|
||||
insert_final_newline = true
|
||||
+6
-2
@@ -8,10 +8,14 @@ docs/_build
|
||||
tests/*.xml
|
||||
tests/*.txt
|
||||
.idea/
|
||||
.vscode
|
||||
tests/samples/output
|
||||
./samples
|
||||
**__pycache**\
|
||||
.mypy_cache
|
||||
.ipynb_checkpoints
|
||||
venv
|
||||
venv
|
||||
oldpdfmajor
|
||||
.tmp*
|
||||
/_*py
|
||||
*.profile
|
||||
*.calltree
|
||||
Vendored
+15
@@ -0,0 +1,15 @@
|
||||
{
|
||||
"python.pythonPath": "venv/bin/python",
|
||||
"python.formatting.provider": "black",
|
||||
"editor.tabSize": 2,
|
||||
"python.testing.unittestArgs": [
|
||||
"-v",
|
||||
"-s",
|
||||
"./tests",
|
||||
"-p",
|
||||
"test_*.py"
|
||||
],
|
||||
"python.testing.pytestEnabled": false,
|
||||
"python.testing.nosetestsEnabled": false,
|
||||
"python.testing.unittestEnabled": true
|
||||
}
|
||||
@@ -0,0 +1,33 @@
|
||||
|
||||
install-development:
|
||||
python3 -m venv venv
|
||||
./venv/bin/pip install -e .[dev]
|
||||
|
||||
clean:
|
||||
rm -rf venv
|
||||
rm -rf build
|
||||
rm -rf dist
|
||||
rm -rf *.egg-info
|
||||
|
||||
lint:
|
||||
autoflake --remove-all-unused-imports --ignore-init-module-imports --remove-duplicate-keys --remove-unused-variables -r -i pdfmajor
|
||||
autoflake --remove-all-unused-imports --ignore-init-module-imports --remove-duplicate-keys --remove-unused-variables -r -i tests
|
||||
isort pdfmajor
|
||||
black pdfmajor
|
||||
isort tests
|
||||
black tests
|
||||
mypy pdfmajor
|
||||
mypy tests
|
||||
bandit -r pdfmajor
|
||||
|
||||
test:
|
||||
./venv/bin/python -m unittest discover tests
|
||||
|
||||
build-docs:
|
||||
mkdocs build
|
||||
|
||||
deploy:
|
||||
python setup.py sdist bdist_wheel
|
||||
git tag $(cat .version)
|
||||
git push -u origin $(cat .version)
|
||||
twine upload dist/*
|
||||
@@ -1,3 +1,19 @@
|
||||
|
||||
# TODO:
|
||||
|
||||
|
||||
- [ ] Re-write docs
|
||||
- [ ] Encryption
|
||||
- [ ] Support all stream filters
|
||||
- [ ] Font support
|
||||
- [ ] Add Type 3/0/CID support
|
||||
- [ ] Color spacing
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
|
||||
# PDFMajor
|
||||
|
||||
<table>
|
||||
|
||||
@@ -1,7 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Get working dir (this will make sure that the script will work the same anywhere you run it)
|
||||
WK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
cd $WK_DIR
|
||||
cd ..
|
||||
|
||||
mkdocs build
|
||||
@@ -1,9 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Get working dir (this will make sure that the script will work the same anywhere you run it)
|
||||
WK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
cd $WK_DIR
|
||||
cd ..
|
||||
|
||||
rm build -rf
|
||||
rm dist -rf
|
||||
rm pdfmajor.egg-info -rf
|
||||
@@ -1,23 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Get working dir (this will make sure that the script will work the same anywhere you run it)
|
||||
WK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
cd $WK_DIR
|
||||
cd ..
|
||||
|
||||
./bin/clean.sh
|
||||
|
||||
|
||||
if ./bin/run_tests.sh; then
|
||||
python setup.py sdist bdist_wheel
|
||||
|
||||
git add .
|
||||
git commit
|
||||
git push
|
||||
|
||||
git tag $(cat .version)
|
||||
git push -u origin $(cat .version)
|
||||
|
||||
twine upload dist/*
|
||||
else
|
||||
echo ">>> Stopped due to test failure!"
|
||||
fi
|
||||
@@ -1,19 +0,0 @@
|
||||
#!/bin/bash
|
||||
# Get working dir (this will make sure that the script will work the same anywhere you run it)
|
||||
WK_DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
|
||||
cd $WK_DIR
|
||||
cd ..
|
||||
|
||||
# for filename in ./tests/test*.py; do
|
||||
# if python $filename ; then
|
||||
# echo woohoo
|
||||
# else
|
||||
# exit 1
|
||||
# fi
|
||||
# done
|
||||
|
||||
if python ./test.py ; then
|
||||
echo "PASSED TESTS"
|
||||
else
|
||||
exit 1
|
||||
fi
|
||||
+6
-105
@@ -2,111 +2,12 @@
|
||||
|
||||
The library is constructed from 4 base modules:
|
||||
|
||||
* **parser**: contains low-level classes for extracting fundamental data-structures from the documents
|
||||
* **interpreter**: a interpreter of the pdf-standard commands
|
||||
* **converters**: contains high-level functions for conversion of the fundamental pdf structures to other formats
|
||||
* **imagewriter**: contains a simple implementation for converting PDF Image Streams to png/bmp/img formats
|
||||
|
||||
## parser
|
||||
|
||||
WIP
|
||||
|
||||
## interpreter
|
||||
a interpreter of the pdf-standard commands
|
||||
|
||||
### Example
|
||||
```py
|
||||
from pdfmajor.interpreter import PDFInterpreter
|
||||
|
||||
for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
print("page start", page.page_num)
|
||||
for item in page:
|
||||
print(" >", item)
|
||||
print("page end", page.page_num)
|
||||
```
|
||||
|
||||
### interpreter.PDFInterpreter
|
||||
|
||||
This generator-function yields individual pages which contain their respected items.
|
||||
|
||||
#### Arguments
|
||||
|
||||
- `input_file_path`: [str](#)
|
||||
- `preload`: [bool](#) defaults to False
|
||||
- `maxpages`: [int](#) defaults to 0
|
||||
- `password`: [str](#) defaults to None
|
||||
- `caching`: [bool](#) defaults to True
|
||||
- `check_extractable`: [bool](#) defaults to True
|
||||
- `ignore_bad_chars`: [bool](#) defaults to False
|
||||
- `pagenos`: [List[int]](#) defaults to None
|
||||
- `debug_level`: [logging.levels](#https://docs.python.org/3/library/logging.html#levels) defaults logging.WARNING
|
||||
|
||||
#### Yield Value
|
||||
This function returns a generator that yields [PDFInterpreter](#interpreterpageinterpreter).
|
||||
|
||||
### interpreter.PageInterpreter
|
||||
|
||||
This generator-function-class yields individual [layout items](#layout-items).
|
||||
### Layout Items
|
||||
|
||||
All layout items extend the `LTItem` class. There are two kinds of layout items:
|
||||
|
||||
- LTComponent: extends the base `LTItem` class, this class will have additional values such as boundary boxes, height and width
|
||||
- LTContainer: extends the `LTComponent` class, this class is used to contain elements of the pdf that would have child elements. Iterating on this element will output its child elements.
|
||||
* **lexer**: contains low-level classes for tokenization
|
||||
* **pdf_parser**: a parser based on the tokens that attempts to map pdf values to python values
|
||||
* **xref**: a database for caching indirect objects in memory
|
||||
* **filters**: a decryption module for decoding pdf-streams
|
||||
* **fonts**: a font's database and evaluation module
|
||||
* **document**: top-level abstraction to be used by end users
|
||||
|
||||
|
||||
#### Layout Containers
|
||||
All of these classes extend the LTContainer class.
|
||||
|
||||
- LTXObject: a layout item containing other additional layout items
|
||||
- LTCharBlock: a layout item containing LTChars, this corresponds to whenever a `TJ` or `Tj` operators is issued within a text object.
|
||||
- LTTextBlock: a layout item containing LTCharBlocks, note that this directly corresponds to the `BT` and `ET` operators pair in the pdf standard
|
||||
|
||||
#### Layout Components
|
||||
All of these classes extend the LTComponent class.
|
||||
|
||||
- LTChar: an individual character
|
||||
- LTCurves: represents a collection of svg-paths (available under `self.paths`)
|
||||
- LTImage: a component containing information regarding an image
|
||||
|
||||
## converters
|
||||
|
||||
Contains high-level functions for conversion of the fundamental pdf structures to other formats. This library includes 4 high-level conversion cases:
|
||||
|
||||
- HTML
|
||||
- JSON
|
||||
- XML
|
||||
- Text
|
||||
|
||||
These formats are all generated using the [PageInterpreter](#PDFInterpreter). To use them simply call the static method [parse_file](#converterspdfconverter).
|
||||
|
||||
### Example
|
||||
|
||||
```py
|
||||
from pdfmajor.converters import convert_file
|
||||
|
||||
convert_file(
|
||||
"path/to/input/file.pdf",
|
||||
"path/to/output/file.html",
|
||||
out_type="html"
|
||||
)
|
||||
```
|
||||
|
||||
### converters.convert_file
|
||||
|
||||
A high-level abstraction for the conversion classes.
|
||||
|
||||
- `input_file`: [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper)
|
||||
- `output_file`: [TextIOWrapper](https://docs.python.org/3/library/io.html#io.TextIOWrapper)
|
||||
- `image_folder_path`: [str](#) defaults to None
|
||||
- `codec`: [str](#) defaults to 'utf-8'
|
||||
- `maxpages`: [int](#) defaults to 0
|
||||
- `password`: [str](#) defaults to None
|
||||
- `caching`: [bool](#) defaults to True
|
||||
- `check_extractable`: [bool](#) defaults to True
|
||||
- `pagenos`: [List[int]](#) defaults to None
|
||||
- `out_type`: [str](#) defaults to 'html'
|
||||
|
||||
## imagewriter
|
||||
|
||||
WIP
|
||||
@@ -0,0 +1,5 @@
|
||||
[mypy]
|
||||
python_version = 3.7
|
||||
warn_return_any = True
|
||||
warn_unused_configs = True
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
|
||||
import struct
|
||||
from io import BytesIO
|
||||
|
||||
from ..parser.PDFStream import LITERALS_DCT_DECODE, PDFStream
|
||||
|
||||
def align32(x):
|
||||
return ((x+3)//4)*4
|
||||
|
||||
## BMPWriter
|
||||
##
|
||||
class BMPWriter(object):
|
||||
|
||||
@classmethod
|
||||
def write_all(cls, fp, stream: PDFStream, bits: int, width: float, height: float, step: float):
|
||||
bmp = cls(fp, 1, width, height)
|
||||
data = stream.get_data()
|
||||
i = 0
|
||||
for y in range(height):
|
||||
bmp.write_line(y, data[i:i+step])
|
||||
i += step
|
||||
|
||||
def __init__(self, fp, bits, width, height):
|
||||
self.fp = fp
|
||||
self.bits = bits
|
||||
self.width = width
|
||||
self.height = height
|
||||
if bits == 1:
|
||||
ncols = 2
|
||||
elif bits == 8:
|
||||
ncols = 256
|
||||
elif bits == 24:
|
||||
ncols = 0
|
||||
else:
|
||||
raise ValueError(bits)
|
||||
self.linesize = align32((self.width*self.bits+7)//8)
|
||||
self.datasize = self.linesize * self.height
|
||||
headersize = 14+40+ncols*4
|
||||
info = struct.pack('<IiiHHIIIIII', 40, self.width, self.height, 1, self.bits, 0, self.datasize, 0, 0, ncols, 0)
|
||||
assert len(info) == 40, str(len(info))
|
||||
header = struct.pack('<ccIHHI', b'B', b'M', headersize+self.datasize, 0, 0, headersize)
|
||||
assert len(header) == 14, str(len(header))
|
||||
self.fp.write(header)
|
||||
self.fp.write(info)
|
||||
if ncols == 2:
|
||||
# B&W color table
|
||||
for i in (0, 255):
|
||||
self.fp.write(struct.pack('BBBx', i, i, i))
|
||||
elif ncols == 256:
|
||||
# grayscale color table
|
||||
for i in range(256):
|
||||
self.fp.write(struct.pack('BBBx', i, i, i))
|
||||
self.pos0 = self.fp.tell()
|
||||
self.pos1 = self.pos0 + self.datasize
|
||||
return
|
||||
|
||||
def write_line(self, y, data):
|
||||
self.fp.seek(self.pos1 - (y+1)*self.linesize)
|
||||
self.fp.write(data)
|
||||
return
|
||||
@@ -1,7 +1,6 @@
|
||||
|
||||
#
|
||||
#
|
||||
# DO NOT EDIT THIS PAGE
|
||||
#
|
||||
#
|
||||
"""
|
||||
# PDFMajor
|
||||
|
||||
@@ -97,10 +96,8 @@ OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
|
||||
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
|
||||
"""
|
||||
__version__ = (1, 3, 11)
|
||||
__version__ = (1, 3, 13)
|
||||
|
||||
if __name__ == '__main__':
|
||||
print(
|
||||
"PDFMajor v" + '.'.join(map(str, __version__))
|
||||
)
|
||||
if __name__ == "__main__":
|
||||
print("PDFMajor v" + ".".join(map(str, __version__)))
|
||||
print(__doc__)
|
||||
@@ -1,113 +0,0 @@
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
|
||||
from typing import List, Optional
|
||||
|
||||
from .html import convert_to_html
|
||||
from .xml import convert_to_xml
|
||||
from .json import convert_to_json
|
||||
from .text import convert_to_text
|
||||
from .yaml import convert_to_yaml
|
||||
from ..utils import logging
|
||||
|
||||
def convert_file(
|
||||
input_file: str,
|
||||
output_file: Optional[str] = None,
|
||||
image_folder_path: Optional[str] = None,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: Optional[str] = None,
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
pagenos: Optional[List[int]] = None,
|
||||
dont_export_images: bool = False,
|
||||
ignore_bad_chars: bool = False,
|
||||
debug_level: int = logging.WARNING,
|
||||
out_type: str = 'html',
|
||||
):
|
||||
if output_file is None:
|
||||
output_file = os.path.join(
|
||||
os.path.dirname(input_file),
|
||||
os.path.basename(
|
||||
re.sub(r"\.\w+$", "."+out_type, input_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!")
|
||||
if out_type == 'html':
|
||||
return convert_to_html(
|
||||
input_file_path=input_file,
|
||||
output_file_path=output_file,
|
||||
image_folder_path=image_folder_path,
|
||||
dont_export_images=dont_export_images,
|
||||
codec=codec,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level,
|
||||
)
|
||||
elif out_type == 'xml':
|
||||
return convert_to_xml(
|
||||
input_file_path=input_file,
|
||||
output_file_path=output_file,
|
||||
image_folder_path=image_folder_path,
|
||||
codec=codec,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
pagenos=pagenos,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
dont_export_images=dont_export_images,
|
||||
debug_level=debug_level,
|
||||
)
|
||||
elif out_type == 'json':
|
||||
return convert_to_json(
|
||||
input_file_path=input_file,
|
||||
output_file_path=output_file,
|
||||
image_folder_path=image_folder_path,
|
||||
codec=codec,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
pagenos=pagenos,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
dont_export_images=dont_export_images,
|
||||
debug_level=debug_level,
|
||||
)
|
||||
elif out_type == 'yaml' or out_type == 'yml':
|
||||
return convert_to_yaml(
|
||||
input_file_path=input_file,
|
||||
output_file_path=output_file,
|
||||
image_folder_path=image_folder_path,
|
||||
codec=codec,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
pagenos=pagenos,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
dont_export_images=dont_export_images,
|
||||
debug_level=debug_level,
|
||||
)
|
||||
elif out_type == 'text':
|
||||
return convert_to_text(
|
||||
input_file_path=input_file,
|
||||
output_file_path=output_file,
|
||||
image_folder_path=image_folder_path,
|
||||
codec=codec,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
pagenos=pagenos,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
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'")
|
||||
@@ -1,226 +0,0 @@
|
||||
from typing import List, Optional
|
||||
from .writers.html import HTMLMaker
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, LTTextBlock, LTCharBlock, LTChar, LTCurve, LTXObject
|
||||
from ..interpreter.commands import LTItem
|
||||
from ..interpreter.commands.state import CurvePath, PDFColor
|
||||
|
||||
INF = (1<<31) - 1
|
||||
|
||||
def convert_to_html(
|
||||
input_file_path: str,
|
||||
output_file_path: str,
|
||||
image_folder_path: Optional[str] = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: Optional[str] = None,
|
||||
caching: bool = True,
|
||||
ignore_bad_chars: bool = False,
|
||||
check_extractable: bool = True,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level
|
||||
)
|
||||
with HTMLMaker(output_file_path, codec=codec) as html:
|
||||
with html.elm("html", nolineend=True):
|
||||
with html.elm("head"):
|
||||
meta_attr = {
|
||||
'http-equiv': "Content-Type",
|
||||
'content': "text/html",
|
||||
}
|
||||
if html.codec:
|
||||
meta_attr['charset'] = html.codec
|
||||
html.singleton("meta", meta_attr)
|
||||
with html.elm('style'):
|
||||
html.write('''.page { position: relative; overflow: hidden;border: 1px black solid;}''')
|
||||
with html.elm("body"):
|
||||
for page in intepreter:
|
||||
render_page(html, page)
|
||||
|
||||
def render_page(html: HTMLMaker, ltpage: PageInterpreter):
|
||||
def render(item: LTItem, block = True):
|
||||
if isinstance(item, LTCurve):
|
||||
render_curve(html, ltpage, item)
|
||||
elif isinstance(item, LTXObject):
|
||||
with html.elm('div', { "class": 'xobject' }, {
|
||||
# 'position': 'absolute',
|
||||
'left': f'{item.x0}px',
|
||||
'right': f'{item.x1}px',
|
||||
'bottom': f'{item.y0}px',
|
||||
'top': f'{item.y1}px',
|
||||
'width': f'{item.width}px',
|
||||
'height': f'{item.height}px',
|
||||
}):
|
||||
for child in item:
|
||||
render(child, False)
|
||||
elif isinstance(item, LTImage):
|
||||
name = item.name
|
||||
# if html.imagewriter is not None:
|
||||
# name = html.imagewriter.export_image(item)
|
||||
html.singleton('img', attrs={
|
||||
'src': name,
|
||||
'background': 'red',
|
||||
'width': f"{item.width}px",
|
||||
'height': f"{item.height}px",
|
||||
})
|
||||
elif isinstance(item, LTChar):
|
||||
with html.elm('span', { 'class': 'char' }, {
|
||||
'width': str(item.width) + "px",
|
||||
'min-width': str(item.width) + "px",
|
||||
'max-width': str(item.width) + "px",
|
||||
'height': str(item.height) + "px",
|
||||
'min-height': str(item.height) + "px",
|
||||
'max-height': str(item.height) + "px",
|
||||
}):
|
||||
html.write(item.get_text())
|
||||
elif isinstance(item, LTTextBlock):
|
||||
with html.elm('span', {'class': 'text-block'}):
|
||||
for char in item:
|
||||
render(char)
|
||||
elif isinstance(item, LTCharBlock):
|
||||
with html.elm('span', { 'class': 'char-block' }, {
|
||||
'position': 'absolute',
|
||||
'left': f'{item.x0}',
|
||||
'bottom': f'{item.y0}',
|
||||
'font-size': f'{item.size}px',
|
||||
'font-family': item.fontname,
|
||||
'font-weight': item.font.font_weight,
|
||||
'color': get_color(item.color, default="black"),
|
||||
'width': str(item.width) + "px",
|
||||
'min-width': str(item.width) + "px",
|
||||
'max-width': str(item.width) + "px",
|
||||
'height': str(item.height) + "px",
|
||||
'min-height': str(item.height) + "px",
|
||||
'max-height': str(item.height) + "px",
|
||||
'transform': f'skew({item.font.italic_angle}deg, 0deg)',
|
||||
'text-align': 'center',
|
||||
'display': 'flex',
|
||||
'flex-flow': 'row nowrap',
|
||||
'justify-content': 'space-between',
|
||||
# 'padding-left': item.font.leading
|
||||
}):
|
||||
for char in item:
|
||||
render(char)
|
||||
|
||||
with html.elm('div', { "class": 'page', "id": f"page-{ltpage.page_num}" }, {
|
||||
'width': f'{ltpage.width}px',
|
||||
'height': f'{ltpage.height}px'
|
||||
}):
|
||||
for child in ltpage:
|
||||
render(child)
|
||||
|
||||
def get_color(col: PDFColor, default: str = ""):
|
||||
if col.color_space is not None:
|
||||
if col.color_space.ncomponents == 1:
|
||||
if type(col.values[0]) in [float, int]:
|
||||
return f"rgba(0,0,0,{1 - float(col.values[0])})"
|
||||
elif col.color_space.ncomponents == 3:
|
||||
return f"rgb({','.join(map(str, col.values))})"
|
||||
elif col.color_space.ncomponents == 4:
|
||||
return f"cmyk({','.join(map(str, col.values))})"
|
||||
return f"{col.color_space.name}({','.join(map(str, col.values))})"
|
||||
else:
|
||||
return default
|
||||
|
||||
def render_curve(html: HTMLMaker, ltpage: PageInterpreter, item: LTCurve):
|
||||
path, svg_attr = create_svg_path(item)
|
||||
|
||||
stroke_col = get_color(item.stroke)
|
||||
fill_col = get_color(item.fill)
|
||||
path_css = {}
|
||||
if fill_col:
|
||||
path_css['fill'] = fill_col
|
||||
if stroke_col:
|
||||
path_css['stroke'] = stroke_col
|
||||
|
||||
with html.elm('svg', svg_attr, css={
|
||||
'border': '1px solid black',
|
||||
'position': 'absolute',
|
||||
'left': f'{item.x0}px',
|
||||
'bottom': f'{ltpage.height - item.y0}px',
|
||||
'top': f'{ltpage.height - item.y1}px',
|
||||
'right': f'{item.x1}px',
|
||||
'width': f'{item.width}px',
|
||||
'height': f'{item.height}px',
|
||||
}):
|
||||
html.singleton('path', {
|
||||
"d": path,
|
||||
**path_css
|
||||
}, {
|
||||
**path_css
|
||||
})
|
||||
|
||||
def create_svg_path(item: LTCurve):
|
||||
path = ""
|
||||
svg_attr = {
|
||||
'class': 'curve',
|
||||
'z-index': 2
|
||||
}
|
||||
|
||||
if item.height > 0:
|
||||
dy = 1.0/item.height
|
||||
dx = (item.width/item.height)/max([(item.x1-item.x0),0.01])
|
||||
svg_attr.update({
|
||||
"viewBox": "0 0 %s %s" % ( item.width/item.height, 1 )
|
||||
})
|
||||
else:
|
||||
dx = 1.0/(item.x1-item.x0)
|
||||
dy = 1.0
|
||||
svg_attr.update({
|
||||
"viewBox": "0 0 1 1"
|
||||
})
|
||||
|
||||
if item.height > 1:
|
||||
svg_attr.update({
|
||||
'height': f'{item.height}px',
|
||||
})
|
||||
else:
|
||||
svg_attr.update({
|
||||
'height': '1px',
|
||||
})
|
||||
|
||||
if item.width > 1:
|
||||
svg_attr.update({
|
||||
'width': f'{item.width}px',
|
||||
})
|
||||
else:
|
||||
svg_attr.update({
|
||||
'width': '1px',
|
||||
})
|
||||
|
||||
def pX(val: float) -> float:
|
||||
return ( val-item.x0 )*dx
|
||||
def pY(val: float) -> float:
|
||||
return ( item.height- (val-item.y0) )*dy
|
||||
|
||||
for p in item.paths:
|
||||
if p.method == CurvePath.METHOD.MOVE_TO:
|
||||
path += f'M{" ".join( f"{pX(p.x)} {pY(p.y)}" for p in p.points )} '
|
||||
elif p.method == CurvePath.METHOD.LINE_TO:
|
||||
path += f'L{" ".join( f"{pX(p.x)} {pY(p.y)}" for p in p.points )} '
|
||||
elif p.method == CurvePath.METHOD.CLOSE_PATH:
|
||||
path += 'Z'
|
||||
elif p.method == CurvePath.METHOD.CURVE_BOTH_TO:
|
||||
path += f'C{" ".join( f"{pX(pt.x)} {pY(pt.y)}" for pt in p.points )} '
|
||||
|
||||
return path, svg_attr
|
||||
|
||||
# def render_textblock(html: HTMLMaker, ltpage: PageInterpreter, item: LTTextBlock):
|
||||
# (x0, y0, x1, y1) = (INF, INF, -INF, -INF)
|
||||
|
||||
# for c_block in item:
|
||||
# x0 = min(x0, c_block.x0)
|
||||
# y0 = min(y0, c_block.y0)
|
||||
# x1 = max(x1, c_block.x1)
|
||||
# y1 = max(y1, c_block.y1)
|
||||
|
||||
# with html.elm('span')
|
||||
@@ -1,146 +0,0 @@
|
||||
from typing import List, Optional
|
||||
|
||||
from .writers.json import JSONMaker, JSONMakerObject, JSONMakerArray
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, LTTextBlock, LTCharBlock, LTCurve, LTXObject
|
||||
from ..interpreter.commands import LTItem
|
||||
from ..interpreter.commands import LTRect, LTLine
|
||||
from ..interpreter.commands.state import CurvePath, PDFColor
|
||||
from ..parser.PSStackParser import PSLiteral
|
||||
from ..utils import enc
|
||||
|
||||
def normalize_color_values(values: list):
|
||||
ret = []
|
||||
for v in values:
|
||||
if isinstance(v, PSLiteral):
|
||||
ret.append( enc(str(v.name)).decode() )
|
||||
else:
|
||||
ret.append( enc(str(v)).decode() )
|
||||
return ret
|
||||
|
||||
def convert_to_json(
|
||||
input_file_path: str,
|
||||
output_file_path: str,
|
||||
image_folder_path: Optional[str] = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = Optional[None],
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
ignore_bad_chars: bool = False,
|
||||
pagenos: Optional[List[int]] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level
|
||||
)
|
||||
with JSONMaker(output_file_path, codec=codec) as json:
|
||||
with json.array("pages") as arr:
|
||||
for page in intepreter:
|
||||
with arr.object() as page_obj:
|
||||
render_page(page_obj, page)
|
||||
|
||||
def render_page(json: JSONMakerObject, ltpage: PageInterpreter):
|
||||
json.number("id", ltpage.page_num)
|
||||
json.number("width", ltpage.width)
|
||||
json.number("height", ltpage.height)
|
||||
with json.array("children") as chil_arr:
|
||||
for child in ltpage:
|
||||
with chil_arr.object() as chil_obj:
|
||||
render(chil_obj, child)
|
||||
|
||||
def render(json: JSONMakerObject, item: LTItem):
|
||||
if isinstance(item, LTCurve):
|
||||
place_curve(json, item)
|
||||
elif isinstance(item, LTXObject):
|
||||
json.string("type", 'xobject')
|
||||
json.number("x0", item.x0)
|
||||
json.number("x1", item.x1)
|
||||
json.number("y0", item.y0)
|
||||
json.number("y1", item.y1)
|
||||
with json.array("children") as chil_arr:
|
||||
for child in item:
|
||||
with chil_arr.object() as chil_obj:
|
||||
render(chil_obj, child)
|
||||
elif isinstance(item, LTImage):
|
||||
# if json.imagewriter is not None:
|
||||
# name = json.imagewriter.export_image(item)
|
||||
json.string("type", 'img')
|
||||
json.string("src", enc(item.name, None))
|
||||
json.number("x0", item.x0)
|
||||
json.number("x1", item.x1)
|
||||
json.number("y0", item.y0)
|
||||
json.number("y1", item.y1)
|
||||
elif isinstance(item, LTTextBlock):
|
||||
place_text_block(json, item)
|
||||
|
||||
def place_text_block(json: JSONMakerObject, text_block: LTTextBlock):
|
||||
json.string("type", 'text-block')
|
||||
json.number("x0", text_block.x0)
|
||||
json.number("x1", text_block.x1)
|
||||
json.number("y0", text_block.y0)
|
||||
json.number("y1", text_block.y1)
|
||||
with json.array("char_blocks") as cb_arr:
|
||||
for cb in text_block:
|
||||
with cb_arr.object() as cb_obj:
|
||||
place_char_block(cb_obj, cb)
|
||||
|
||||
def place_char_block(json: JSONMakerObject, char_block: LTCharBlock):
|
||||
json.number("size", char_block.size)
|
||||
json.number("x0", char_block.x0)
|
||||
json.number("x1", char_block.x1)
|
||||
json.number("y0", char_block.y0)
|
||||
json.number("y1", char_block.y1)
|
||||
if char_block.color.color_space is not None:
|
||||
json.place_object("color", {
|
||||
"type": enc(char_block.color.color_space.name).decode(),
|
||||
"value": normalize_color_values(char_block.color.values)
|
||||
})
|
||||
for key, value in char_block.font.descriptor.items():
|
||||
if key != "Type" and "FontFile" not in key:
|
||||
json.string(key, value)
|
||||
json.string("text",
|
||||
"".join([
|
||||
char.get_text()
|
||||
for char in char_block
|
||||
])
|
||||
)
|
||||
|
||||
def place_curve(json: JSONMakerObject, item: LTCurve):
|
||||
json.number("x0", item.x0)
|
||||
json.number("x1", item.x1)
|
||||
json.number("y0", item.y0)
|
||||
json.number("y1", item.y1)
|
||||
if item.fill.color_space is not None:
|
||||
json.place_object("fill", {
|
||||
"type": enc(item.fill.color_space.name).decode(),
|
||||
"value": normalize_color_values(item.fill.values)
|
||||
})
|
||||
if item.stroke.color_space is not None:
|
||||
json.place_object("stroke", {
|
||||
"type": enc(item.stroke.color_space.name).decode(),
|
||||
"value": normalize_color_values(item.stroke.values)
|
||||
})
|
||||
|
||||
if isinstance(item, LTRect):
|
||||
json.string("type", 'rect')
|
||||
elif isinstance(item, LTLine):
|
||||
json.string("type", 'line')
|
||||
else:
|
||||
json.string("type", 'curve')
|
||||
with json.array('paths') as paths_arr:
|
||||
for path in item.paths:
|
||||
paths_arr.place_object({
|
||||
"type": path.method.name,
|
||||
"points": [
|
||||
{"x": point.x, "y": point.y}
|
||||
for point in path.points
|
||||
]
|
||||
})
|
||||
@@ -1,42 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTTextBlock, LTXObject
|
||||
|
||||
|
||||
def convert_to_text(
|
||||
input_file_path: str,
|
||||
output_file_path: str,
|
||||
image_folder_path: str = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = None,
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
ignore_bad_chars: bool = False,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level
|
||||
)
|
||||
with open(output_file_path, 'wb') as outfp:
|
||||
def process_container(container: LTXObject):
|
||||
for item in container:
|
||||
if isinstance(item, LTTextBlock):
|
||||
for text in item:
|
||||
for char in text:
|
||||
outfp.write(char.get_text().encode(codec))
|
||||
elif isinstance(item, LTXObject):
|
||||
process_container(item)
|
||||
for page in intepreter:
|
||||
outfp.write(f"========== [ page {page.page_num} ] ==========\n".encode(codec))
|
||||
process_container(page)
|
||||
outfp.write('\n'.encode(codec))
|
||||
@@ -1,62 +0,0 @@
|
||||
from typing import Optional
|
||||
from io import TextIOWrapper
|
||||
from contextlib import contextmanager
|
||||
|
||||
class HTMLMaker:
|
||||
class AccessError(Exception): pass
|
||||
def __init__(self, file_path: str, codec: str = 'utf-8'):
|
||||
self.file_path = file_path
|
||||
self.codec = codec
|
||||
self.outfile: Optional[TextIOWrapper] = None
|
||||
|
||||
def __enter__(self):
|
||||
self.outfile = open(self.file_path, 'wb')
|
||||
self.__levels_deep = 0
|
||||
return self
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.outfile.close()
|
||||
self.outfile = None
|
||||
|
||||
def write_raw(self, text):
|
||||
if self.outfile is not None:
|
||||
if self.codec:
|
||||
text = text.encode(self.codec)
|
||||
self.outfile.write(text)
|
||||
else:
|
||||
raise self.AccessError("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
|
||||
self.write_raw(text)
|
||||
|
||||
@contextmanager
|
||||
def elm(self, tag_name: str, attrs: dict = None, css: dict = None, nolineend: bool = False, no_additional_char: bool = False, singleton: bool = False):
|
||||
lineend = '\n'
|
||||
deep_space = ' '
|
||||
if no_additional_char:
|
||||
lineend = ''
|
||||
deep_space = ''
|
||||
if attrs is None:
|
||||
attrs = {}
|
||||
if css is not None:
|
||||
attrs['style'] = ";".join([
|
||||
f'{name}: {value}'
|
||||
for name, value in css.items()
|
||||
])
|
||||
attrs_str = " ".join([
|
||||
f'{name}="{value}"'
|
||||
for name, value in attrs.items()
|
||||
])
|
||||
if not singleton:
|
||||
self.write(f"<{tag_name} {attrs_str}>", lineend=lineend)
|
||||
self.__levels_deep += 1
|
||||
yield
|
||||
self.__levels_deep -= 1
|
||||
self.write(f"</{tag_name}>", deep_space=deep_space, lineend='\n' if not nolineend else '')
|
||||
else:
|
||||
self.write(f"<{tag_name} {attrs_str} />", lineend=lineend, deep_space=deep_space)
|
||||
yield
|
||||
|
||||
def singleton(self, tag_name: str, attrs: dict = None, css: dict = None, singleton: bool = True):
|
||||
with self.elm(tag_name, attrs, css, singleton=singleton):
|
||||
pass
|
||||
@@ -1,131 +0,0 @@
|
||||
from typing import Set
|
||||
from json import dumps as json_dump
|
||||
from io import TextIOWrapper
|
||||
from contextlib import contextmanager
|
||||
|
||||
@contextmanager
|
||||
def JSONMaker(file_path: str, codec: str = 'utf-8'):
|
||||
with open(file_path, 'wb') as outf:
|
||||
with JSONMakerObject(outf, codec=codec) as obj:
|
||||
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
|
||||
self.levels_deep = levels_deep
|
||||
self.keys: Set[str] = set()
|
||||
|
||||
def __enter__(self):
|
||||
self.write_raw('{')
|
||||
self.levels_deep += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.levels_deep -= 1
|
||||
self.write('}', prefix='\n')
|
||||
|
||||
def write_raw(self, text):
|
||||
if self.outfile is not None:
|
||||
if self.codec:
|
||||
text = text.encode(self.codec)
|
||||
self.outfile.write(text)
|
||||
else:
|
||||
raise self.AccessError("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
|
||||
self.write_raw(text)
|
||||
|
||||
def write_prop(self, key: str, val: str = ""):
|
||||
if key not in self.keys:
|
||||
self.keys.add(key)
|
||||
if len(self.keys) > 1:
|
||||
self.write(f'"{key}": {val}', prefix=',\n')
|
||||
else:
|
||||
self.write(f'"{key}": {val}', prefix='\n')
|
||||
|
||||
def number(self, key: str, val: float or int):
|
||||
self.write_prop(key, val)
|
||||
|
||||
def string(self, key: str, val: str):
|
||||
val_sant = str(val).replace('"', '\\"')
|
||||
self.write_prop(key, f'"{val_sant}"')
|
||||
|
||||
@contextmanager
|
||||
def object(self, key: str):
|
||||
self.write_prop(key)
|
||||
with JSONMakerObject(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as child:
|
||||
yield child
|
||||
|
||||
@contextmanager
|
||||
def array(self, key: str):
|
||||
self.write_prop(key)
|
||||
with JSONMakerArray(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as child:
|
||||
yield child
|
||||
|
||||
def place_object(self, key: str, obj: dict):
|
||||
self.write_prop(key, json_dump(obj))
|
||||
|
||||
|
||||
|
||||
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
|
||||
self.levels_deep = levels_deep
|
||||
self.childrencount = 0
|
||||
|
||||
def __enter__(self):
|
||||
self.write_raw('[')
|
||||
self.levels_deep += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.levels_deep -= 1
|
||||
self.write(']', prefix='\n')
|
||||
|
||||
def write_raw(self, text):
|
||||
if self.outfile is not None:
|
||||
if self.codec:
|
||||
text = text.encode(self.codec)
|
||||
self.outfile.write(text)
|
||||
else:
|
||||
raise self.AccessError("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
|
||||
self.write_raw(text)
|
||||
|
||||
def write_prop(self, val: str = ""):
|
||||
self.childrencount += 1
|
||||
if self.childrencount > 1:
|
||||
self.write(f'{val}', prefix=',\n')
|
||||
else:
|
||||
self.write(f'{val}', prefix='\n')
|
||||
|
||||
def number(self, val: float or int):
|
||||
self.write_prop(val)
|
||||
|
||||
def string(self, val: str):
|
||||
val_sant = str(val).replace('"', '\\"')
|
||||
self.write_prop(f'"{val_sant}"')
|
||||
|
||||
@contextmanager
|
||||
def object(self):
|
||||
self.write_prop()
|
||||
with JSONMakerObject(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as child:
|
||||
yield child
|
||||
|
||||
@contextmanager
|
||||
def array(self):
|
||||
self.write_prop()
|
||||
with JSONMakerArray(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as child:
|
||||
yield child
|
||||
|
||||
def place_object(self, obj: dict):
|
||||
self.write_prop(json_dump(obj))
|
||||
|
||||
|
||||
@@ -1,60 +0,0 @@
|
||||
from io import TextIOWrapper
|
||||
from contextlib import contextmanager
|
||||
|
||||
class XMLMaker:
|
||||
class AccessError(Exception): pass
|
||||
def __init__(self, file_path: str, codec: str = 'utf-8'):
|
||||
self.file_path = file_path
|
||||
self.codec = codec
|
||||
self.outfile: TextIOWrapper = None
|
||||
def __enter__(self):
|
||||
self.outfile = open(self.file_path, 'wb')
|
||||
if self.codec:
|
||||
self.write_raw(f'<?xml version="1.0.0" encoding="{self.codec}" ?>')
|
||||
else:
|
||||
self.write_raw(f'<?xml version="1.0.0" ?>')
|
||||
self.__levels_deep = 0
|
||||
return self
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.outfile.close()
|
||||
self.outfile = None
|
||||
|
||||
def write_raw(self, text):
|
||||
if self.outfile is not None:
|
||||
if self.codec:
|
||||
text = text.encode(self.codec)
|
||||
self.outfile.write(text)
|
||||
else:
|
||||
raise self.AccessError("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
|
||||
self.write_raw(text)
|
||||
|
||||
@contextmanager
|
||||
def elm(self, tag_name: str, attrs: dict = None, nolineend: bool = False, no_additional_char: bool = False, singleton: bool = False):
|
||||
lineend = '\n'
|
||||
deep_space = ' '
|
||||
if no_additional_char:
|
||||
lineend = ''
|
||||
deep_space = ''
|
||||
if attrs is None:
|
||||
attrs = {}
|
||||
attrs = " ".join([
|
||||
f'{name}="{value}"'
|
||||
for name, value in attrs.items()
|
||||
])
|
||||
if not singleton:
|
||||
self.write(f"<{tag_name} {attrs}>", lineend=lineend)
|
||||
self.__levels_deep += 1
|
||||
yield
|
||||
self.__levels_deep -= 1
|
||||
self.write(f"</{tag_name}>", deep_space=deep_space, lineend='\n' if not nolineend else '')
|
||||
else:
|
||||
self.write(f"<{tag_name} {attrs} />", lineend=lineend, deep_space=deep_space)
|
||||
yield
|
||||
|
||||
def singleton(self, tag_name: str, attrs: dict = None):
|
||||
with self.elm(tag_name, attrs, singleton=True):
|
||||
pass
|
||||
|
||||
@@ -1,117 +0,0 @@
|
||||
from json import dumps as json_dump
|
||||
from io import TextIOWrapper
|
||||
from contextlib import contextmanager
|
||||
|
||||
@contextmanager
|
||||
def YAMLMaker(file_path: str, codec: str = 'utf-8'):
|
||||
with open(file_path, 'wb') as outf:
|
||||
with YAMLMakerObject(outf, codec=codec) as obj:
|
||||
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
|
||||
self.levels_deep = levels_deep
|
||||
|
||||
def __enter__(self):
|
||||
if self.levels_deep > 0:
|
||||
self.__write_raw('')
|
||||
self.levels_deep += 1
|
||||
return self
|
||||
|
||||
def __exit__(self, exc_type, exc_val, exc_tb):
|
||||
self.levels_deep -= 1
|
||||
|
||||
def __write_raw(self, text):
|
||||
if self.outfile is not None:
|
||||
if self.codec:
|
||||
text = text.encode(self.codec)
|
||||
self.outfile.write(text)
|
||||
else:
|
||||
raise self.AccessError("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:
|
||||
deep_space = ""
|
||||
text = prefix + (deep_space*self.levels_deep) + text
|
||||
self.__write_raw(text)
|
||||
|
||||
class YAMLMakerObject(YAMLMakerWriter):
|
||||
def __init__(self, outfile: TextIOWrapper, codec: str = 'utf-8', levels_deep: int = -1, parent_is_array: bool = False):
|
||||
YAMLMakerWriter.__init__(self, outfile, codec, levels_deep)
|
||||
self.keys = set()
|
||||
self.parent_is_array = parent_is_array
|
||||
|
||||
def write(self, key: str, value: str):
|
||||
if key not in self.keys:
|
||||
self.keys.add(key)
|
||||
if len(self.keys) > 1:
|
||||
self._write(f'{key}: {value}', prefix='\n')
|
||||
else:
|
||||
self._write(f'{key}: {value}', prefix='',
|
||||
append_deep=not self.parent_is_array
|
||||
)
|
||||
|
||||
@contextmanager
|
||||
def object(self, key: str):
|
||||
if key not in self.keys:
|
||||
self.keys.add(key)
|
||||
if len(self.keys) > 1:
|
||||
self._write(f'{key}:\n', prefix='\n')
|
||||
else:
|
||||
self._write(f'{key}:\n', prefix='', append_deep=False)
|
||||
with YAMLMakerObject(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as obj:
|
||||
yield obj
|
||||
|
||||
@contextmanager
|
||||
def array(self, key: str):
|
||||
if key not in self.keys:
|
||||
self.keys.add(key)
|
||||
if len(self.keys) > 1:
|
||||
self._write(f'{key}:\n', prefix='\n')
|
||||
else:
|
||||
self._write(f'{key}:\n', prefix='')
|
||||
with YAMLMakerArray(self.outfile, codec=self.codec, levels_deep=self.levels_deep) as obj:
|
||||
yield obj
|
||||
|
||||
def place_object(self, key: str, obj: dict):
|
||||
with self.object(key) as child:
|
||||
for key, val in obj.items():
|
||||
child.write(key, val)
|
||||
|
||||
def place_array(self, key: str, arr: list):
|
||||
with self.array(key) as child:
|
||||
for val in arr:
|
||||
child.write(val)
|
||||
|
||||
|
||||
class YAMLMakerArray(YAMLMakerWriter):
|
||||
def __init__(self, outfile: TextIOWrapper, codec: str = 'utf-8', levels_deep: int = -1):
|
||||
YAMLMakerWriter.__init__(self, outfile, codec, levels_deep)
|
||||
self.childrencount = 0
|
||||
|
||||
def write(self, value: str = ""):
|
||||
self.childrencount += 1
|
||||
if self.childrencount > 1:
|
||||
self._write(f'- {value}', prefix='\n')
|
||||
else:
|
||||
self._write(f'- {value}', prefix='')
|
||||
|
||||
@contextmanager
|
||||
def object(self):
|
||||
self.childrencount += 1
|
||||
if self.childrencount > 1:
|
||||
self._write(f'- ', prefix='\n')
|
||||
else:
|
||||
self._write(f'- ', prefix='')
|
||||
with YAMLMakerObject(self.outfile, codec=self.codec, levels_deep=self.levels_deep, parent_is_array=True) as obj:
|
||||
yield obj
|
||||
|
||||
def place_object(self, obj: dict):
|
||||
with self.object() as child:
|
||||
for key, val in obj.items():
|
||||
child.write(key, val)
|
||||
|
||||
|
||||
@@ -1,155 +0,0 @@
|
||||
import re
|
||||
from typing import List
|
||||
from xml.sax import saxutils
|
||||
|
||||
from .writers.xml import XMLMaker
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, LTTextBlock, LTCharBlock, LTChar, LTCurve, LTXObject
|
||||
from ..interpreter.commands import LTItem
|
||||
from ..interpreter.commands import LTRect, LTLine
|
||||
from ..interpreter.commands.state import CurvePath, PDFColor
|
||||
from ..parser.PSStackParser import PSLiteral
|
||||
from ..utils import enc
|
||||
|
||||
FIRST_CAP_RE = re.compile('(.)([A-Z][a-z]+)')
|
||||
ALL_CAP_RE = re.compile('([a-z0-9])([A-Z])')
|
||||
def convert_capcase_to_snakecase(text: str) -> str:
|
||||
s1 = FIRST_CAP_RE.sub(r'\1-\2', text)
|
||||
return ALL_CAP_RE.sub(r'\1-\2', s1).lower()
|
||||
|
||||
def normalize_color_values(values: list):
|
||||
ret = ""
|
||||
for i,v in enumerate(values):
|
||||
if i > 0:
|
||||
ret += ','
|
||||
if isinstance(v, PSLiteral):
|
||||
ret += enc(str(v.name)).decode()
|
||||
else:
|
||||
ret += enc(str(v)).decode()
|
||||
return ret
|
||||
|
||||
def get_color(col: PDFColor, prefix: str = 'color', codec = 'utf-8'):
|
||||
if col.color_space is not None:
|
||||
return {
|
||||
f"{prefix}-type": enc(col.color_space.name).decode(),
|
||||
f"{prefix}-values": normalize_color_values(col.values)
|
||||
}
|
||||
return {}
|
||||
|
||||
def convert_to_xml(
|
||||
input_file_path: str,
|
||||
output_file_path: str,
|
||||
image_folder_path: str = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = None,
|
||||
caching: bool = True,
|
||||
ignore_bad_chars: bool = False,
|
||||
check_extractable: bool = True,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level
|
||||
)
|
||||
with XMLMaker(output_file_path, codec=codec) as xml:
|
||||
with xml.elm("pages"):
|
||||
for page in intepreter:
|
||||
render_page(xml, page)
|
||||
|
||||
def render_page(xml: XMLMaker, ltpage: PageInterpreter):
|
||||
def render(item: LTItem):
|
||||
if isinstance(item, LTCurve):
|
||||
place_curve(xml, item)
|
||||
elif isinstance(item, LTXObject):
|
||||
with xml.elm('xobject', {
|
||||
"x0": item.x0,
|
||||
"x1": item.x1,
|
||||
"y0": item.y0,
|
||||
"y1": item.y1,
|
||||
}):
|
||||
for child in item:
|
||||
render(child)
|
||||
elif isinstance(item, LTImage):
|
||||
name = item.name
|
||||
# if xml.imagewriter is not None:
|
||||
# name = xml.imagewriter.export_image(item)
|
||||
xml.singleton('img', attrs={
|
||||
'src': enc(name, None),
|
||||
"x0": item.x0,
|
||||
"x1": item.x1,
|
||||
"y0": item.y0,
|
||||
"y1": item.y1,
|
||||
})
|
||||
elif isinstance(item, LTTextBlock):
|
||||
place_text_block(xml, item)
|
||||
with xml.elm('page', {
|
||||
"id": ltpage.page_num,
|
||||
"width": ltpage.width,
|
||||
"height": ltpage.height,
|
||||
}):
|
||||
for child in ltpage:
|
||||
render(child)
|
||||
|
||||
def place_char(xml: XMLMaker, char: LTChar):
|
||||
with xml.elm('char', {
|
||||
'x0': char.x0,
|
||||
'x1': char.x1,
|
||||
'y0': char.y0,
|
||||
'y1': char.y1,
|
||||
}, no_additional_char=True):
|
||||
xml.write(saxutils.escape(char.get_text()), lineend='', deep_space="")
|
||||
|
||||
def place_char_block(xml: XMLMaker, char_block: LTCharBlock):
|
||||
attr = {
|
||||
'size': char_block.size,
|
||||
"x0": char_block.x0,
|
||||
"x1": char_block.x1,
|
||||
"y0": char_block.y0,
|
||||
"y1": char_block.y1,
|
||||
**get_color(char_block.color, codec=xml.codec),
|
||||
}
|
||||
for key, value in char_block.font.descriptor.items():
|
||||
if key != "Type" and "FontFile" not in key:
|
||||
attr[convert_capcase_to_snakecase(key)] = value
|
||||
with xml.elm("char-block", attr):
|
||||
for char in char_block:
|
||||
place_char(xml, char)
|
||||
|
||||
def place_text_block(xml: XMLMaker, text_block: LTCharBlock):
|
||||
attr = {
|
||||
"x0": text_block.x0,
|
||||
"x1": text_block.x1,
|
||||
"y0": text_block.y0,
|
||||
"y1": text_block.y1,
|
||||
}
|
||||
with xml.elm("text-block", attr):
|
||||
for char_block in text_block:
|
||||
place_char_block(xml, char_block)
|
||||
|
||||
def place_curve(xml: XMLMaker, item: LTCurve):
|
||||
attr = {
|
||||
"x0": item.x0,
|
||||
"x1": item.x1,
|
||||
"y0": item.y0,
|
||||
"y1": item.y1,
|
||||
**get_color(item.stroke, "stroke", codec=xml.codec),
|
||||
**get_color(item.fill, "fill", codec=xml.codec),
|
||||
}
|
||||
if isinstance(item, LTRect):
|
||||
return xml.singleton('rect', attr)
|
||||
elif isinstance(item, LTLine):
|
||||
return xml.singleton('line', attr)
|
||||
|
||||
with xml.elm('curve', attr):
|
||||
for path in item.paths:
|
||||
with xml.elm('path', { "type": path.method.name }):
|
||||
for point in path.points:
|
||||
xml.singleton('point', { 'x': point.x, 'y': point.y })
|
||||
@@ -1,146 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from .writers.yaml import YAMLMaker, YAMLMakerObject, YAMLMakerArray
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, LTTextBlock, LTCharBlock, LTCurve, LTXObject
|
||||
from ..interpreter.commands import LTItem
|
||||
from ..interpreter.commands import LTRect, LTLine
|
||||
from ..interpreter.commands.state import CurvePath, PDFColor
|
||||
from ..parser.PSStackParser import PSLiteral
|
||||
from ..utils import enc
|
||||
|
||||
def normalize_color_values(values: list):
|
||||
ret = []
|
||||
for v in values:
|
||||
if isinstance(v, PSLiteral):
|
||||
ret.append( enc(str(v.name)).decode() )
|
||||
else:
|
||||
ret.append( enc(str(v)).decode() )
|
||||
return ret
|
||||
|
||||
def convert_to_yaml(
|
||||
input_file_path: str,
|
||||
output_file_path: str,
|
||||
image_folder_path: str = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = None,
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
ignore_bad_chars: bool = False,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
ignore_bad_chars=ignore_bad_chars,
|
||||
pagenos=pagenos,
|
||||
debug_level=debug_level
|
||||
)
|
||||
with YAMLMaker(output_file_path, codec=codec) as yaml:
|
||||
with yaml.array("pages") as arr:
|
||||
for page in intepreter:
|
||||
with arr.object() as page_obj:
|
||||
render_page(page_obj, page)
|
||||
|
||||
def render_page(yaml: YAMLMakerObject, ltpage: PageInterpreter):
|
||||
yaml.write("id", ltpage.page_num)
|
||||
yaml.write("width", ltpage.width)
|
||||
yaml.write("height", ltpage.height)
|
||||
with yaml.array("children") as chil_arr:
|
||||
for child in ltpage:
|
||||
with chil_arr.object() as chil_obj:
|
||||
render(chil_obj, child)
|
||||
|
||||
def render(yaml: YAMLMakerObject, item: LTItem):
|
||||
if isinstance(item, LTCurve):
|
||||
place_curve(yaml, item)
|
||||
elif isinstance(item, LTXObject):
|
||||
yaml.write("type", 'xobject')
|
||||
yaml.write("x0", item.x0)
|
||||
yaml.write("x1", item.x1)
|
||||
yaml.write("y0", item.y0)
|
||||
yaml.write("y1", item.y1)
|
||||
with yaml.array("children") as chil_arr:
|
||||
for child in item:
|
||||
with chil_arr.object() as chil_obj:
|
||||
render(chil_obj, child)
|
||||
elif isinstance(item, LTImage):
|
||||
# if yaml.imagewriter is not None:
|
||||
# name = yaml.imagewriter.export_image(item)
|
||||
yaml.write("type", 'img')
|
||||
yaml.write("src", enc(item.name, None))
|
||||
yaml.write("x0", item.x0)
|
||||
yaml.write("x1", item.x1)
|
||||
yaml.write("y0", item.y0)
|
||||
yaml.write("y1", item.y1)
|
||||
elif isinstance(item, LTTextBlock):
|
||||
place_text_block(yaml, item)
|
||||
|
||||
def place_text_block(yaml: YAMLMakerObject, text_block: LTTextBlock):
|
||||
yaml.write("type", 'text-block')
|
||||
yaml.write("x0", text_block.x0)
|
||||
yaml.write("x1", text_block.x1)
|
||||
yaml.write("y0", text_block.y0)
|
||||
yaml.write("y1", text_block.y1)
|
||||
with yaml.array("char_blocks") as cb_arr:
|
||||
for cb in text_block:
|
||||
with cb_arr.object() as cb_obj:
|
||||
place_char_block(cb_obj, cb)
|
||||
|
||||
def place_char_block(yaml: YAMLMakerObject, char_block: LTCharBlock):
|
||||
yaml.write("size", char_block.size)
|
||||
yaml.write("x0", char_block.x0)
|
||||
yaml.write("x1", char_block.x1)
|
||||
yaml.write("y0", char_block.y0)
|
||||
yaml.write("y1", char_block.y1)
|
||||
if char_block.color.color_space is not None:
|
||||
yaml.place_object("color", {
|
||||
"type": enc(char_block.color.color_space.name).decode(),
|
||||
"value": normalize_color_values(char_block.color.values)
|
||||
})
|
||||
for key, value in char_block.font.descriptor.items():
|
||||
if key != "Type" and "FontFile" not in key:
|
||||
yaml.write(key, value)
|
||||
yaml.write("text",
|
||||
"".join([
|
||||
char.get_text()
|
||||
for char in char_block
|
||||
])
|
||||
)
|
||||
|
||||
def place_curve(yaml: YAMLMakerObject, item: LTCurve):
|
||||
if isinstance(item, LTRect):
|
||||
yaml.write("type", 'rect')
|
||||
elif isinstance(item, LTLine):
|
||||
yaml.write("type", 'line')
|
||||
else:
|
||||
yaml.write("type", 'curve')
|
||||
with yaml.array('paths') as paths_arr:
|
||||
for path in item.paths:
|
||||
paths_arr.place_object({
|
||||
"type": path.method.name,
|
||||
"points": [
|
||||
{"x": point.x, "y": point.y}
|
||||
for point in path.points
|
||||
]
|
||||
})
|
||||
|
||||
yaml.write("x0", item.x0)
|
||||
yaml.write("x1", item.x1)
|
||||
yaml.write("y0", item.y0)
|
||||
yaml.write("y1", item.y1)
|
||||
if item.fill.color_space is not None:
|
||||
yaml.place_object("fill", {
|
||||
"type": enc(item.fill.color_space.name).decode(),
|
||||
"value": normalize_color_values(item.fill.values)
|
||||
})
|
||||
if item.stroke.color_space is not None:
|
||||
yaml.place_object("stroke", {
|
||||
"type": enc(item.stroke.color_space.name).decode(),
|
||||
"value": normalize_color_values(item.stroke.values)
|
||||
})
|
||||
@@ -0,0 +1 @@
|
||||
from .document import PDFDocument
|
||||
@@ -0,0 +1,18 @@
|
||||
from typing import Any, Dict, NamedTuple, Optional
|
||||
|
||||
from pdfmajor.document.metadata import PDFMetadata
|
||||
from pdfmajor.document.pages import PDFPageTreeNode
|
||||
from pdfmajor.pdf_parser.objects import PDFDictionary, PDFName
|
||||
|
||||
|
||||
class PDFDocumentCatalog(NamedTuple):
|
||||
"""A Parsed version of the PDF Catalog object (see PDF spec 1.7 section 7.7.2 for more detail)"""
|
||||
|
||||
version: Optional[PDFName]
|
||||
pages: PDFPageTreeNode
|
||||
page_labels: Optional[PDFDictionary]
|
||||
page_layout: Optional[PDFName]
|
||||
page_mode: Optional[PDFName]
|
||||
metadata: Optional[PDFMetadata]
|
||||
|
||||
raw: Dict[str, Any] # for other properties
|
||||
@@ -0,0 +1,69 @@
|
||||
import warnings
|
||||
from pathlib import Path
|
||||
from typing import BinaryIO, Iterator, List, Optional
|
||||
|
||||
from pdfmajor.document.pages import PDFPage
|
||||
from pdfmajor.document.parse_context import PDFParsingContext
|
||||
from pdfmajor.document.parsers.pages import iter_all_page_leafs
|
||||
from pdfmajor.document.parsers.root import get_catalog, get_info
|
||||
from pdfmajor.streambuffer import BufferStream
|
||||
|
||||
|
||||
class PDFDocument:
|
||||
"""A class encapsulating all of the access behavior to the document"""
|
||||
|
||||
@classmethod
|
||||
def from_io(cls, fp: BinaryIO, buffer_size=4096):
|
||||
return cls(BufferStream(fp, buffer_size))
|
||||
|
||||
@classmethod
|
||||
def from_path(cls, path: Path, buffer_size=4096):
|
||||
return cls(BufferStream(path.open("rb"), buffer_size))
|
||||
|
||||
def __init__(self, buffer: BufferStream) -> None:
|
||||
self.__parser = PDFParsingContext(buffer)
|
||||
self.__processed_pages: Optional[List[PDFPage]] = None
|
||||
self.__processed_pages_done = False
|
||||
self.catalog = get_catalog(self.__parser)
|
||||
self.info = get_info(self.__parser)
|
||||
|
||||
@property
|
||||
def health_report(self):
|
||||
"""A log of errors that occured in the document during the processing of the file"""
|
||||
return self.__parser.health_report
|
||||
|
||||
@property
|
||||
def num_pages(self) -> int:
|
||||
"""Returns the number of pages that the metadata of the document claims it has.
|
||||
This number should be trusted, unless you suspect the document may have encoutered some corruption. To get an excat count do `len(list(self.iter_pages()))`. Please note that this will load all of the metadata of each document into memory.
|
||||
|
||||
Returns:
|
||||
int
|
||||
"""
|
||||
return self.catalog.pages.leaft_count
|
||||
|
||||
def iter_pages(self) -> Iterator[PDFPage]:
|
||||
"""Iterate over all of the pages in the document, this will also keep a record of the pdf page in memory for quicker future retrieval! (use self.clear() to free it up)
|
||||
|
||||
Yields:
|
||||
Iterator[PDFPage]
|
||||
"""
|
||||
if self.__processed_pages is not None and self.__processed_pages_done:
|
||||
return iter(self.__processed_pages)
|
||||
else:
|
||||
self.__processed_pages = []
|
||||
for page in iter_all_page_leafs(self.__parser, self.catalog.pages):
|
||||
self.__processed_pages.append(page)
|
||||
yield page
|
||||
self.__processed_pages_done = True
|
||||
if len(self.__processed_pages) != self.num_pages:
|
||||
warnings.warn(
|
||||
"Number of pages proceseed with iter_pages did not match number of pages specified by the document's metadata!"
|
||||
f"\n --> expected pages = {self.num_pages}"
|
||||
f"\n --> found pages = {len(self.__processed_pages)}"
|
||||
)
|
||||
|
||||
def clear(self):
|
||||
"""Clears out memory used by the class as much as possible"""
|
||||
self.__processed_pages = None
|
||||
self.__processed_pages_done = False
|
||||
@@ -0,0 +1,37 @@
|
||||
from decimal import Decimal
|
||||
from typing import List, Set
|
||||
|
||||
from pdfmajor.exceptions import BrokenFile, PDFMajorException
|
||||
from pdfmajor.pdf_parser.objects import ObjectRef
|
||||
|
||||
|
||||
class PDFDocumentError(PDFMajorException):
|
||||
pass
|
||||
|
||||
|
||||
class BrokenFilePDF(BrokenFile):
|
||||
pass
|
||||
|
||||
|
||||
class MissingCatalogObj(BrokenFilePDF):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidCatalogObj(BrokenFilePDF):
|
||||
pass
|
||||
|
||||
|
||||
class TooManyInfoObj(BrokenFilePDF):
|
||||
def __init__(self, elms: Set[ObjectRef]) -> None:
|
||||
super().__init__(f"Too many info elements found | elms={elms}")
|
||||
self.elms = elms
|
||||
|
||||
|
||||
class TooManyRectField(BrokenFilePDF):
|
||||
def __init__(self, values: List[Decimal]) -> None:
|
||||
super().__init__(f"Too many elements found for rectangle | values={values}")
|
||||
self.values = values
|
||||
|
||||
|
||||
class InvalidPagesNodeKids(BrokenFilePDF):
|
||||
pass
|
||||
@@ -0,0 +1,8 @@
|
||||
from typing import NamedTuple
|
||||
|
||||
|
||||
class PDFMetadata(NamedTuple):
|
||||
"""A structure representing the data in a PDF Metadata object as is specified in PDF spec 1.7 section 14.3.2"""
|
||||
|
||||
sub_type: str
|
||||
stream_data: bytes
|
||||
@@ -0,0 +1,18 @@
|
||||
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"""
|
||||
|
||||
font: Dict[str, PDFFont]
|
||||
|
||||
# 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]
|
||||
@@ -0,0 +1,74 @@
|
||||
from typing import List, NamedTuple, Optional
|
||||
|
||||
from pdfmajor.document.exceptions import InvalidPagesNodeKids
|
||||
from pdfmajor.document.parse_context import PDFParsingContext
|
||||
from pdfmajor.document.structures import PDFRectangle
|
||||
from pdfmajor.exceptions import PDFMajorException
|
||||
from pdfmajor.pdf_parser.objects import (
|
||||
ObjectRef,
|
||||
PDFDictionary,
|
||||
PDFInteger,
|
||||
PDFReal,
|
||||
PDFStream,
|
||||
validate_object_or_none,
|
||||
)
|
||||
|
||||
from .utils import iter_single_ref_as_array_ref
|
||||
|
||||
|
||||
class PDFPageTreeNode(NamedTuple):
|
||||
"""A PDF Pages Node representation as it confirms with PDF spec 1.7 section 7.7.3.2"""
|
||||
|
||||
kids: List[ObjectRef]
|
||||
parent: Optional[ObjectRef]
|
||||
leaft_count: int
|
||||
|
||||
raw: PDFDictionary
|
||||
|
||||
@classmethod
|
||||
def from_pdfdict(cls, pdfdict: PDFDictionary):
|
||||
parent = validate_object_or_none(pdfdict.get("Parent"), ObjectRef)
|
||||
kids = pdfdict["Kids"]
|
||||
count = validate_object_or_none(pdfdict.get("Count"), PDFInteger)
|
||||
try:
|
||||
vetted_kids: List[ObjectRef] = list(
|
||||
iter_single_ref_as_array_ref(pdfdict["Kids"])
|
||||
)
|
||||
except PDFMajorException:
|
||||
raise InvalidPagesNodeKids(f"{kids}")
|
||||
return cls(
|
||||
kids=vetted_kids,
|
||||
parent=parent,
|
||||
raw=pdfdict,
|
||||
leaft_count=0 if count is None else count.to_python(),
|
||||
)
|
||||
|
||||
|
||||
class PDFDataPage(NamedTuple):
|
||||
"""The data of a PDF Page as it confirms with PDF Spec 1.7 section 7.7.3.3"""
|
||||
|
||||
parent: ObjectRef
|
||||
resources: PDFDictionary
|
||||
mediabox: PDFRectangle
|
||||
cropbox: PDFRectangle
|
||||
bleedbox: PDFRectangle
|
||||
trimbox: PDFRectangle
|
||||
artbox: PDFRectangle
|
||||
contents: List[PDFStream]
|
||||
boxcolor_info: Optional[PDFDictionary]
|
||||
rotate: PDFInteger
|
||||
metadata: Optional[PDFStream]
|
||||
user_unit: PDFReal
|
||||
|
||||
raw: PDFDictionary
|
||||
|
||||
|
||||
class PDFPage:
|
||||
"""A class encapsulating interactions with a PDF Page"""
|
||||
|
||||
def __init__(self, pctx: PDFParsingContext, data: PDFDataPage) -> None:
|
||||
self.__pctx = pctx
|
||||
self.data = data
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"PDFPage(data={repr(self.data)})"
|
||||
@@ -0,0 +1,237 @@
|
||||
from pathlib import Path
|
||||
from typing import Any, BinaryIO, Dict, Iterator, Optional, Tuple, Type, TypeVar, Union
|
||||
|
||||
from pdfmajor.document.exceptions import BrokenFilePDF
|
||||
from pdfmajor.document.parsers.stream import decode_stream, iter_filters_in_stream
|
||||
from pdfmajor.document.structures import PDFRectangle
|
||||
from pdfmajor.healthlog import PDFHealthReport
|
||||
from pdfmajor.pdf_parser.objects import (
|
||||
IndirectObject,
|
||||
ObjectRef,
|
||||
PDFArray,
|
||||
PDFDictionary,
|
||||
PDFInteger,
|
||||
PDFObject,
|
||||
PDFReal,
|
||||
validate_number_or_none,
|
||||
validate_object_or_none,
|
||||
)
|
||||
from pdfmajor.pdf_parser.objects.stream import PDFStream
|
||||
from pdfmajor.streambuffer import BufferStream
|
||||
from pdfmajor.xref.xrefdb import GenNum, ObjNum, XRefDB
|
||||
|
||||
|
||||
class PDFParsingContext:
|
||||
"""A utility class to encapsulate various interactions with the raw document stream"""
|
||||
|
||||
@classmethod
|
||||
def from_io(cls, fp: BinaryIO, buffer_size=4096):
|
||||
return cls(BufferStream(fp, buffer_size))
|
||||
|
||||
@classmethod
|
||||
def from_path(cls, path: Path, buffer_size=4096):
|
||||
return cls(BufferStream(path.open("rb"), buffer_size))
|
||||
|
||||
def __init__(self, buffer: BufferStream) -> None:
|
||||
self.buffer = buffer
|
||||
self.health_report = PDFHealthReport()
|
||||
with buffer.get_window():
|
||||
self.xrefdb = XRefDB(buffer)
|
||||
|
||||
def get_object_from_ref(self, objref: ObjectRef) -> IndirectObject:
|
||||
"""Get an indirect object from it's object reference
|
||||
|
||||
Args:
|
||||
objref (ObjectRef)
|
||||
|
||||
Returns:
|
||||
IndirectObject
|
||||
"""
|
||||
with self.buffer.get_window():
|
||||
return self.xrefdb.get_obj(
|
||||
objref.obj_num, objref.gen_num, buffer=self.buffer
|
||||
)
|
||||
|
||||
ExpectedType = TypeVar("ExpectedType", bound=PDFObject)
|
||||
|
||||
def get_validate_object(
|
||||
self, obj: Optional[PDFObject], exptype: Type[ExpectedType]
|
||||
) -> Optional[ExpectedType]:
|
||||
"""Validates the object's type if its not None
|
||||
|
||||
Args:
|
||||
obj (Optional[PDFObject])
|
||||
objtype (Type[ExpectedType]): expected type of the object
|
||||
|
||||
Raises:
|
||||
AssertionError: is raised if the object has an invalid type
|
||||
|
||||
Returns:
|
||||
Optional[ExpectedType]
|
||||
"""
|
||||
if isinstance(obj, ObjectRef):
|
||||
return validate_object_or_none(
|
||||
self.get_object_from_ref(obj).get_object(), exptype
|
||||
)
|
||||
return validate_object_or_none(obj, exptype)
|
||||
|
||||
def get_validate_numeric(
|
||||
self, obj: Optional[PDFObject]
|
||||
) -> Optional[Union[PDFInteger, PDFReal]]:
|
||||
"""Validates the object is numeric, if its not None
|
||||
|
||||
Args:
|
||||
obj (Optional[PDFObject])
|
||||
|
||||
Raises:
|
||||
AssertionError: is raised if the object has an invalid type
|
||||
|
||||
Returns:
|
||||
Optional[Union[PDFInteger, PDFReal]]
|
||||
"""
|
||||
if isinstance(obj, ObjectRef):
|
||||
return validate_number_or_none(self.get_object_from_ref(obj).get_object())
|
||||
return validate_number_or_none(obj)
|
||||
|
||||
def convert_pdfdict_to_validated_pythondict(
|
||||
self,
|
||||
pdfdict: PDFDictionary,
|
||||
field_mapping: Dict[str, Tuple[str, Type[PDFObject]]],
|
||||
) -> Dict[str, Optional[PDFObject]]:
|
||||
"""Takes a pdf-dictionary and converts it to a regular dictionary (but first validates the types of the objects)
|
||||
|
||||
Args:
|
||||
pdfdict (PDFDictionary)
|
||||
field_mapping (Dict[str, Tuple[Type[PDFObject]]]): mapping of the name as it in the pdf to a tuple with a (new name, expected objcet type)
|
||||
|
||||
Returns:
|
||||
dict
|
||||
"""
|
||||
out: Dict[str, Optional[PDFObject]] = {}
|
||||
for pdf_name, (new_name, exp_type) in field_mapping.items():
|
||||
try:
|
||||
out[new_name] = self.get_validate_object(
|
||||
pdfdict.get(pdf_name), exp_type
|
||||
)
|
||||
except AssertionError as err:
|
||||
self.health_report.write_error(err)
|
||||
return out
|
||||
|
||||
def extract_and_validate_pdf_rectangles(
|
||||
self, pdfdict: PDFDictionary, field_mapping: Dict[str, str]
|
||||
) -> Dict[str, Optional[PDFRectangle]]:
|
||||
"""Takes a pdf-dictionary and extracts the specified fields. Next it will validate and convert the fields into PDFRectangles
|
||||
|
||||
Args:
|
||||
pdfdict (PDFDictionary)
|
||||
field_mapping (Dict[str, str]): a mapping of names as they appear in the pdf to requested names
|
||||
|
||||
Returns:
|
||||
Dict[str, Optional[PDFRectangle]]
|
||||
"""
|
||||
vetted_values: Any = self.convert_pdfdict_to_validated_pythondict(
|
||||
pdfdict,
|
||||
{
|
||||
pdfname: (newname, PDFArray)
|
||||
for pdfname, newname in field_mapping.items()
|
||||
},
|
||||
)
|
||||
return {
|
||||
newname: PDFRectangle.from_pdfarray(value) if value is not None else value
|
||||
for newname, value in vetted_values.items()
|
||||
}
|
||||
|
||||
def get_obj_by_type(self, obj_type: str) -> Iterator[IndirectObject]:
|
||||
"""Iterates over the objects in memeory and filters out for the ones that match the requested type
|
||||
If the object is not loaded into memory this function will load it.
|
||||
|
||||
Args:
|
||||
obj_type (ObjType)
|
||||
|
||||
Raises:
|
||||
InvalidXref: if the object could not be found in memory or the buffer
|
||||
XRefError: if the object type if found but the object was never loaded into memory
|
||||
|
||||
Yields:
|
||||
Iterator[IndirectObject]
|
||||
"""
|
||||
with self.buffer.get_window() as buffer:
|
||||
return self.xrefdb.get_obj_by_type(buffer, obj_type)
|
||||
|
||||
def get_obj(
|
||||
self,
|
||||
obj_num: ObjNum,
|
||||
gen_num: GenNum,
|
||||
) -> IndirectObject:
|
||||
"""Get's an indirect object from either the pdf stream or a cached version in memeory
|
||||
|
||||
Args:
|
||||
obj_num (ObjNum)
|
||||
gen_num (GenNum)
|
||||
buffer (BufferStream)
|
||||
|
||||
Raises:
|
||||
InvalidXref: if the reference returned was not an indirect object
|
||||
|
||||
Returns:
|
||||
IndirectObject
|
||||
"""
|
||||
with self.buffer.get_window() as buffer:
|
||||
return self.xrefdb.get_obj(obj_num, gen_num, buffer)
|
||||
|
||||
def validated_and_iter_stream(
|
||||
self, obj_ref: PDFObject
|
||||
) -> Tuple[PDFDictionary, bytes]:
|
||||
"""Validates that an object is either an ObjectRef or IndirectObject and then checks that it has a stream.
|
||||
Once those checks are passed, this method will decode the stream and return it's contents witht the indirect objects dictionary
|
||||
|
||||
Args:
|
||||
obj_ref (PDFObject)
|
||||
|
||||
Raises:
|
||||
BrokenFilePDF: if a validation fails
|
||||
|
||||
Returns:
|
||||
Tuple[PDFDictionary, bytes]: (metadata, stream data)
|
||||
"""
|
||||
if isinstance(obj_ref, ObjectRef):
|
||||
obj = self.get_object_from_ref(obj_ref)
|
||||
elif isinstance(obj_ref, IndirectObject):
|
||||
obj = obj_ref
|
||||
else:
|
||||
raise BrokenFilePDF(f"Expected a pdf-stream, instead found {obj_ref}")
|
||||
|
||||
if obj.stream is None:
|
||||
raise BrokenFilePDF(f"Expected a pdf-stream, instead found {obj}")
|
||||
else:
|
||||
obj_def = obj.get_object()
|
||||
if not isinstance(obj_def, PDFDictionary):
|
||||
self.health_report.write_error(
|
||||
BrokenFilePDF(
|
||||
f"Stream object is missing a defining dictionary {obj_def} {obj_def}"
|
||||
)
|
||||
)
|
||||
obj_def = PDFDictionary()
|
||||
return obj_def, self.decode_stream(obj.stream)
|
||||
|
||||
def decode_stream(self, stream: PDFStream) -> bytes:
|
||||
"""Decode the bytes associated with the PDF-Stream
|
||||
|
||||
Args:
|
||||
stream (PDFStream)
|
||||
|
||||
Returns:
|
||||
bytes
|
||||
"""
|
||||
offset = stream.offset
|
||||
length_ref = stream.length
|
||||
if isinstance(length_ref, ObjectRef):
|
||||
length_obj = self.get_object_from_ref(length_ref).get_object()
|
||||
if not isinstance(length_obj, PDFInteger):
|
||||
raise BrokenFilePDF(f"Length should be an int not {length_obj}")
|
||||
else:
|
||||
length_obj = length_ref
|
||||
length = length_obj.value
|
||||
return decode_stream(
|
||||
offset, length, iter_filters_in_stream(stream), self.buffer
|
||||
)
|
||||
File renamed without changes.
@@ -0,0 +1,18 @@
|
||||
from pdfmajor.document.metadata import PDFMetadata
|
||||
from pdfmajor.pdf_parser.objects import PDFName, PDFObject
|
||||
|
||||
from ..exceptions import BrokenFilePDF
|
||||
from ..parse_context import PDFParsingContext
|
||||
|
||||
|
||||
def get_metadata(pctx: PDFParsingContext, ref: PDFObject):
|
||||
obj_def, data = pctx.validated_and_iter_stream(ref)
|
||||
subtype = obj_def["Subtype"]
|
||||
if not isinstance(subtype, PDFName):
|
||||
pctx.health_report.write_error(
|
||||
BrokenFilePDF(
|
||||
f"Metadata data object is missing a valid subtype {ref} {obj_def}"
|
||||
)
|
||||
)
|
||||
return PDFMetadata("", data)
|
||||
return PDFMetadata(subtype.value, data)
|
||||
@@ -0,0 +1,250 @@
|
||||
from decimal import Decimal
|
||||
from typing import Any, Dict, Iterator, List, Optional
|
||||
|
||||
from pdfmajor.document.exceptions import BrokenFilePDF
|
||||
from pdfmajor.pdf_parser.objects import (
|
||||
IndirectObject,
|
||||
ObjectRef,
|
||||
PDFArray,
|
||||
PDFDictionary,
|
||||
PDFInteger,
|
||||
PDFObject,
|
||||
PDFReal,
|
||||
PDFStream,
|
||||
validate_object_or_none,
|
||||
)
|
||||
|
||||
from ..pages import PDFDataPage, PDFPage, PDFPageTreeNode
|
||||
from ..parse_context import PDFParsingContext
|
||||
from ..utils import iter_single_ref_as_array_ref
|
||||
|
||||
PDFRawFields = Dict[str, Any]
|
||||
|
||||
|
||||
def iter_all_page_leafs(
|
||||
pctx: PDFParsingContext, root_node: PDFPageTreeNode
|
||||
) -> Iterator[PDFPage]:
|
||||
"""Iterate over every page in the pdf
|
||||
|
||||
Args:
|
||||
pctx (PDFParsingContext)
|
||||
root_node (PDFPageTreeNode)
|
||||
|
||||
Yields:
|
||||
Iterator[PDFPage]
|
||||
"""
|
||||
current_root: List[PDFPageTreeNode] = [root_node]
|
||||
current_root_aspage: List[Dict[str, Optional[PDFObject]]] = [
|
||||
parse_pdfpage_fields(pctx, root_node.raw, allow_missing=True)
|
||||
]
|
||||
current_child_idx: List[int] = [0]
|
||||
while len(current_root) > 0:
|
||||
croot = current_root[-1]
|
||||
croot_pagedata = current_root_aspage[-1]
|
||||
ckids = croot.kids
|
||||
cidx = current_child_idx[-1]
|
||||
if len(ckids) < cidx + 1:
|
||||
try:
|
||||
current_root.pop()
|
||||
current_root_aspage.pop()
|
||||
current_child_idx.pop()
|
||||
continue
|
||||
except IndexError:
|
||||
break
|
||||
page_ref = ckids[cidx]
|
||||
obj = pctx.get_object_from_ref(page_ref).get_object()
|
||||
if isinstance(obj, PDFDictionary):
|
||||
if obj["Type"].to_python() == "/Pages":
|
||||
current_root.append(PDFPageTreeNode.from_pdfdict(obj))
|
||||
current_root_aspage.append(
|
||||
{
|
||||
**croot_pagedata,
|
||||
**parse_pdfpage_fields(pctx, obj, allow_missing=True),
|
||||
}
|
||||
)
|
||||
current_child_idx[-1] += 1
|
||||
current_child_idx.append(0)
|
||||
continue
|
||||
elif obj["Type"].to_python() == "/Page":
|
||||
yield make_pdfpage(croot_pagedata, pctx, obj)
|
||||
current_child_idx[-1] += 1
|
||||
continue
|
||||
# catch all other cases (the above expression will issue a 'continue')
|
||||
pctx.health_report.write(
|
||||
"InvalidPageobject",
|
||||
f"Expecting page ref {page_ref} to be a dictionary with type 'Pages' or 'Page', but got a {obj}",
|
||||
)
|
||||
current_child_idx[-1] += 1
|
||||
|
||||
|
||||
def make_pdfpage(
|
||||
lastpage: Optional[Dict[str, Optional[PDFObject]]],
|
||||
pctx: PDFParsingContext,
|
||||
pdfdict: PDFDictionary,
|
||||
) -> PDFPage:
|
||||
"""Creates a PDFPage object, and handle the inheritance of properties
|
||||
|
||||
Args:
|
||||
lastpage (Optional[Dict[str, Optional[PDFObject]]]): the last inheritable properties for the pdf
|
||||
pctx (PDFParsingContext)
|
||||
pdfdict (PDFDictionary)
|
||||
|
||||
Returns:
|
||||
PDFPage
|
||||
"""
|
||||
vetted_fields: Any = parse_pdfpage_fields(
|
||||
pctx, pdfdict, lastpage=lastpage, allow_missing=False
|
||||
)
|
||||
parent = validate_object_or_none(pdfdict.get("Parent"), ObjectRef)
|
||||
content_streams: List[PDFStream] = []
|
||||
if pdfdict.get("Contents", None) is not None:
|
||||
content_streams = list(_parse_page_contents(pdfdict["Contents"], pctx))
|
||||
else:
|
||||
pctx.health_report.write(
|
||||
"MissingPDFPageContents",
|
||||
f"Page with data {pdfdict} is missing the 'Contents' property."
|
||||
"Will assume that the page has no content.",
|
||||
)
|
||||
vetted_fields["parent"] = parent
|
||||
vetted_fields["contents"] = content_streams
|
||||
vetted_fields["raw"] = pdfdict
|
||||
vetted_fields["metadata"] = _parse_metadata(pdfdict.get("Metadata", None), pctx)
|
||||
return PDFPage(pctx, PDFDataPage(**vetted_fields))
|
||||
|
||||
|
||||
def parse_pdfpage_fields(
|
||||
pctx: PDFParsingContext,
|
||||
pdfdict: PDFDictionary,
|
||||
allow_missing: bool = False,
|
||||
lastpage: Optional[PDFRawFields] = None,
|
||||
) -> PDFRawFields:
|
||||
parsed_values = pctx.convert_pdfdict_to_validated_pythondict(
|
||||
pdfdict,
|
||||
{
|
||||
"Resources": ("resources", PDFDictionary),
|
||||
"BoxColorInfo": ("boxcolor_info", PDFDictionary),
|
||||
"Rotate": ("rotate", PDFInteger),
|
||||
},
|
||||
)
|
||||
mediaboxes = pctx.extract_and_validate_pdf_rectangles(
|
||||
pdfdict,
|
||||
{
|
||||
"MediaBox": "mediabox",
|
||||
"CropBox": "cropbox",
|
||||
"BleedBox": "bleedbox",
|
||||
"TrimBox": "trimbox",
|
||||
"ArtBox": "artbox",
|
||||
},
|
||||
)
|
||||
return _deal_with_inheritance(
|
||||
{
|
||||
**parsed_values, # type: ignore
|
||||
**mediaboxes, # type: ignore
|
||||
"user_unit": pctx.get_validate_numeric(pdfdict.get("UserUnit")), # type: ignore
|
||||
},
|
||||
lastpage,
|
||||
allow_missing,
|
||||
)
|
||||
|
||||
|
||||
def _parse_metadata(
|
||||
metadata_raw: Optional[PDFObject], pctx: PDFParsingContext
|
||||
) -> Optional[PDFStream]:
|
||||
if metadata_raw is None:
|
||||
return None
|
||||
if isinstance(metadata_raw, ObjectRef):
|
||||
metadata_obj = pctx.get_object_from_ref(metadata_raw)
|
||||
elif isinstance(metadata_raw, IndirectObject):
|
||||
metadata_obj = metadata_raw
|
||||
else:
|
||||
raise BrokenFilePDF(f"Metadata object is not a valid type {metadata_raw}")
|
||||
if metadata_obj.stream is None:
|
||||
raise BrokenFilePDF(f"Metadata object is missing it's stream {metadata_obj}")
|
||||
else:
|
||||
return metadata_obj.stream
|
||||
|
||||
|
||||
def _parse_page_contents(contents_raw: PDFObject, pctx: PDFParsingContext):
|
||||
for content_ref in iter_single_ref_as_array_ref(contents_raw):
|
||||
content_obj = pctx.get_object_from_ref(content_ref)
|
||||
if isinstance(content_obj, PDFArray):
|
||||
for subref in iter_single_ref_as_array_ref(content_obj):
|
||||
sub_obj = pctx.get_object_from_ref(subref)
|
||||
if isinstance(sub_obj, IndirectObject):
|
||||
if sub_obj.stream is not None:
|
||||
yield sub_obj.stream
|
||||
continue
|
||||
raise BrokenFilePDF(f"Invalid PDFStream found for page {sub_obj}")
|
||||
continue
|
||||
elif isinstance(content_obj, IndirectObject):
|
||||
if content_obj.stream is not None:
|
||||
yield content_obj.stream
|
||||
continue
|
||||
raise BrokenFilePDF(f"Invalid PDFStream found for page {content_obj}")
|
||||
|
||||
|
||||
def _deal_with_inheritance(
|
||||
field_dict: Dict[str, Optional[PDFObject]],
|
||||
lastpage: Optional[PDFRawFields],
|
||||
allow_missing: bool = False,
|
||||
) -> Dict[str, Any]:
|
||||
_deal_with_inheritance_for_field("resources", field_dict, lastpage, PDFDictionary())
|
||||
_deal_with_inheritance_for_field(
|
||||
"rotate", field_dict, lastpage, PDFInteger(0, 0, 0)
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"user_unit", field_dict, lastpage, PDFReal(Decimal("1.0"), 0, 0)
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"mediabox", field_dict, lastpage, allow_missing=allow_missing
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"cropbox",
|
||||
field_dict,
|
||||
lastpage,
|
||||
default_value=field_dict["mediabox"],
|
||||
allow_missing=allow_missing,
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"bleedbox",
|
||||
field_dict,
|
||||
lastpage,
|
||||
default_value=field_dict["cropbox"],
|
||||
allow_missing=allow_missing,
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"trimbox",
|
||||
field_dict,
|
||||
lastpage,
|
||||
default_value=field_dict["cropbox"],
|
||||
allow_missing=allow_missing,
|
||||
)
|
||||
_deal_with_inheritance_for_field(
|
||||
"artbox",
|
||||
field_dict,
|
||||
lastpage,
|
||||
default_value=field_dict["cropbox"],
|
||||
allow_missing=allow_missing,
|
||||
)
|
||||
return field_dict
|
||||
|
||||
|
||||
def _deal_with_inheritance_for_field(
|
||||
field_name: str,
|
||||
field_dict: Dict[str, Optional[PDFObject]],
|
||||
lastpage: Optional[PDFRawFields],
|
||||
default_value: Optional[PDFObject] = None,
|
||||
allow_missing: bool = False,
|
||||
):
|
||||
if not field_dict[field_name]:
|
||||
if not lastpage:
|
||||
if default_value is not None:
|
||||
field_dict[field_name] = default_value
|
||||
elif not allow_missing:
|
||||
raise BrokenFilePDF(f"Page is missing {field_name}")
|
||||
elif lastpage.get(field_name, None):
|
||||
field_dict[field_name] = lastpage[field_name]
|
||||
elif default_value is not None:
|
||||
field_dict[field_name] = default_value
|
||||
elif not allow_missing:
|
||||
raise BrokenFilePDF(f"Page is missing {field_name}")
|
||||
@@ -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)
|
||||
@@ -0,0 +1,98 @@
|
||||
from typing import Any, Optional, Set
|
||||
|
||||
from pdfmajor.document.pages import PDFPageTreeNode
|
||||
from pdfmajor.document.parsers.metadata import get_metadata
|
||||
from pdfmajor.pdf_parser.objects import (
|
||||
IndirectObject,
|
||||
ObjectRef,
|
||||
PDFDictionary,
|
||||
PDFName,
|
||||
PDFObject,
|
||||
)
|
||||
from pdfmajor.xref.exceptions import InvalidNumberOfRoots, NotRootElement
|
||||
from pdfmajor.xref.trailer import get_root_obj
|
||||
|
||||
from ..catalog import PDFDocumentCatalog
|
||||
from ..exceptions import InvalidCatalogObj, MissingCatalogObj, TooManyInfoObj
|
||||
from ..parse_context import PDFParsingContext
|
||||
|
||||
|
||||
def get_info(pctx: PDFParsingContext) -> 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)"""
|
||||
info_obj = _find_indirect_obj_for_info(pctx)
|
||||
if info_obj is None:
|
||||
return None
|
||||
else:
|
||||
return info_obj.get_object()
|
||||
|
||||
|
||||
def get_catalog(pctx: PDFParsingContext) -> PDFDocumentCatalog:
|
||||
"""Gets the catalog for a document
|
||||
|
||||
Raises:
|
||||
InvalidCatalogObj: if something is not correctly set in the catalog
|
||||
|
||||
Returns:
|
||||
PDFDocumentCatalog
|
||||
"""
|
||||
cat_obj = _find_indirect_obj_for_root(pctx).get_object()
|
||||
if not isinstance(cat_obj, PDFDictionary):
|
||||
raise InvalidCatalogObj("not a dictionary")
|
||||
validated_fields: Any = pctx.convert_pdfdict_to_validated_pythondict(
|
||||
cat_obj,
|
||||
{
|
||||
"Version": ("version", PDFName),
|
||||
"PageLabels": ("page_labels", PDFDictionary),
|
||||
"PageLayout": ("page_layout", PDFName),
|
||||
"PageMode": ("page_mode", PDFName),
|
||||
},
|
||||
)
|
||||
try:
|
||||
pages_obj = cat_obj["Pages"]
|
||||
except KeyError:
|
||||
raise InvalidCatalogObj(f"Missing Pages entry {cat_obj}")
|
||||
if isinstance(pages_obj, ObjectRef):
|
||||
pages = pctx.get_object_from_ref(pages_obj).get_object()
|
||||
if not isinstance(pages, PDFDictionary):
|
||||
raise InvalidCatalogObj(f"Invalid pages ref entry {pages} from {pages_obj}")
|
||||
elif isinstance(pages_obj, PDFDictionary):
|
||||
pages = pages_obj
|
||||
else:
|
||||
raise InvalidCatalogObj(f"Invalid pages entry {pages_obj}")
|
||||
if cat_obj.get("Metadata"):
|
||||
validated_fields["metadata"] = get_metadata(pctx, cat_obj["Metadata"])
|
||||
else:
|
||||
validated_fields["metadata"] = None
|
||||
validated_fields["pages"] = PDFPageTreeNode.from_pdfdict(pages)
|
||||
validated_fields["raw"] = cat_obj
|
||||
return PDFDocumentCatalog(**validated_fields)
|
||||
|
||||
|
||||
def _find_indirect_obj_for_root(pctx: PDFParsingContext) -> IndirectObject:
|
||||
try:
|
||||
obj_ref = get_root_obj(pctx.xrefdb.trailers)
|
||||
root_element = pctx.get_obj(obj_num=obj_ref.obj_num, gen_num=obj_ref.gen_num)
|
||||
except InvalidNumberOfRoots as e:
|
||||
pctx.health_report.write_error(e)
|
||||
obj_ref = next(iter(e.roots))
|
||||
root_element = pctx.get_obj(obj_num=obj_ref.obj_num, gen_num=obj_ref.gen_num)
|
||||
except NotRootElement as e:
|
||||
pctx.health_report.write_error(e)
|
||||
try:
|
||||
root_element = next(pctx.get_obj_by_type("/Catalog"))
|
||||
except StopIteration:
|
||||
raise MissingCatalogObj()
|
||||
return root_element
|
||||
|
||||
|
||||
def _find_indirect_obj_for_info(pctx: PDFParsingContext) -> Optional[IndirectObject]:
|
||||
elements: Set[ObjectRef] = set()
|
||||
for trailer in pctx.xrefdb.trailers:
|
||||
if trailer.info is not None:
|
||||
elements.add(trailer.info)
|
||||
if len(elements) > 1:
|
||||
pctx.health_report.write_error(TooManyInfoObj(elements))
|
||||
elif len(elements) == 0:
|
||||
return None
|
||||
ref = next(iter(elements))
|
||||
return pctx.get_obj(ref.obj_num, ref.gen_num)
|
||||
@@ -0,0 +1,55 @@
|
||||
from itertools import chain
|
||||
from typing import Any, Dict, Iterator
|
||||
|
||||
from pdfmajor.filters import FilterPair, process_filters_on_data
|
||||
from pdfmajor.pdf_parser.exceptions import IncompleteStream
|
||||
from pdfmajor.pdf_parser.objects import PDFDictionary, PDFName, PDFStream
|
||||
from pdfmajor.streambuffer import BufferStream
|
||||
|
||||
|
||||
def iter_filters_in_stream(stream: PDFStream) -> Iterator[FilterPair]:
|
||||
"""loops over all filters and their params in the stream
|
||||
|
||||
Args:
|
||||
stream (PDFStream)
|
||||
|
||||
Raises:
|
||||
IncompleteStream: if a filter-name is invalid
|
||||
|
||||
Yields:
|
||||
Iterator[FilterPair]
|
||||
"""
|
||||
for f, dp in chain(
|
||||
zip(stream.filter, stream.decode_parms),
|
||||
zip(stream.ffilter, stream.fdecode_parms),
|
||||
):
|
||||
if not isinstance(f, PDFName):
|
||||
raise IncompleteStream(f"Invalid filter name {f}")
|
||||
else:
|
||||
filter_name = f.value
|
||||
params: Dict[str, Any] = {}
|
||||
if isinstance(dp, PDFDictionary):
|
||||
params = dp.to_python()
|
||||
yield filter_name, params
|
||||
|
||||
|
||||
def decode_stream(
|
||||
offset: int, length: int, it_filters: Iterator[FilterPair], buffer: BufferStream
|
||||
) -> bytes:
|
||||
"""Decode the bytes associated with the PDF-Stream
|
||||
|
||||
Args:
|
||||
offset (int)
|
||||
length (int)
|
||||
it_filters (Iterator[FilterPair])
|
||||
buffer (BufferStream)
|
||||
|
||||
Returns:
|
||||
bytes
|
||||
"""
|
||||
with buffer.get_window():
|
||||
buffer.seek(offset)
|
||||
data = buffer.read(length).data
|
||||
|
||||
data = process_filters_on_data(data, it_filters)
|
||||
return data
|
||||
@@ -0,0 +1,48 @@
|
||||
from decimal import Decimal
|
||||
from typing import List, NamedTuple
|
||||
|
||||
import numpy as np
|
||||
|
||||
from pdfmajor.document.exceptions import BrokenFilePDF, TooManyRectField
|
||||
from pdfmajor.pdf_parser.objects import PDFArray, PDFInteger, PDFReal
|
||||
|
||||
|
||||
class PDFRectangle(NamedTuple):
|
||||
"""A PDF Rectangle as specified by PDF spec 1.7 section 7.9.5"""
|
||||
|
||||
llx: Decimal
|
||||
lly: Decimal
|
||||
urx: Decimal
|
||||
ury: Decimal
|
||||
|
||||
@classmethod
|
||||
def from_pdfarray(cls, arr: PDFArray):
|
||||
vals: List[Decimal] = []
|
||||
for obj in arr:
|
||||
if isinstance(obj, PDFInteger):
|
||||
vals.append(Decimal(obj.to_python()))
|
||||
elif isinstance(obj, PDFReal):
|
||||
vals.append(obj.to_python())
|
||||
else:
|
||||
raise BrokenFilePDF(f"Invalid type for initilizing rectangle {obj}")
|
||||
if len(vals) > 4:
|
||||
raise TooManyRectField(vals)
|
||||
elif len(vals) < 4:
|
||||
raise BrokenFilePDF(
|
||||
f"Insufficient number of fields for rectangle {arr} {vals}"
|
||||
)
|
||||
return cls(*vals)
|
||||
|
||||
def to_numpy(self) -> np.ndarray:
|
||||
"""convert the rectangle to a numpy array
|
||||
|
||||
Returns:
|
||||
np.ndarray[np.float64]
|
||||
"""
|
||||
return np.array(
|
||||
[
|
||||
[np.float64(self.llx), np.float64(self.lly)],
|
||||
[np.float64(self.urx), np.float64(self.ury)],
|
||||
],
|
||||
dtype=np.float64,
|
||||
)
|
||||
@@ -0,0 +1,33 @@
|
||||
from typing import Iterator
|
||||
|
||||
from pdfmajor.pdf_parser.objects import (
|
||||
ObjectRef,
|
||||
PDFArray,
|
||||
PDFObject,
|
||||
validate_object_or_none,
|
||||
)
|
||||
|
||||
from .exceptions import BrokenFilePDF
|
||||
|
||||
|
||||
def iter_single_ref_as_array_ref(kids: PDFObject) -> Iterator[ObjectRef]:
|
||||
"""Validate that an object is either a list of refs or a single ref, then iterate over it
|
||||
|
||||
Args:
|
||||
kids (PDFObject)
|
||||
|
||||
Raises:
|
||||
BrokenFile: if the provided object is not a valid PDFObject
|
||||
|
||||
Yields:
|
||||
Iterator[ObjectRef]
|
||||
"""
|
||||
if isinstance(kids, ObjectRef):
|
||||
yield kids
|
||||
elif isinstance(kids, PDFArray):
|
||||
for kid in kids:
|
||||
vetted_kid = validate_object_or_none(kid, ObjectRef)
|
||||
if vetted_kid:
|
||||
yield vetted_kid
|
||||
else:
|
||||
raise BrokenFilePDF(f"expected a list of refs and got {kids}")
|
||||
@@ -0,0 +1,6 @@
|
||||
class PDFMajorException(Exception):
|
||||
pass
|
||||
|
||||
|
||||
class BrokenFile(PDFMajorException):
|
||||
pass
|
||||
@@ -1,2 +0,0 @@
|
||||
import pdfmajor.parser.exceptions as parser
|
||||
import pdfmajor.interpreter.exceptions as interpreter
|
||||
@@ -0,0 +1,71 @@
|
||||
from typing import Any, Dict, Iterator, List, Optional, Type
|
||||
|
||||
from .decoders import (
|
||||
ASCII85Decode,
|
||||
ASCIIHexDecode,
|
||||
CCITTFaxDecode,
|
||||
FlateDecode,
|
||||
LZWDecode,
|
||||
RunLengthDecode
|
||||
)
|
||||
from .types import FilterPair, PDFFilterDecoder
|
||||
|
||||
_filter_type_name_mapping: Dict[str, Optional[Type[PDFFilterDecoder]]] = {
|
||||
"FlateDecode": FlateDecode,
|
||||
"Fl": FlateDecode,
|
||||
"LZWDecode": LZWDecode,
|
||||
"LZW": LZWDecode,
|
||||
"ASCII85Decode": ASCII85Decode,
|
||||
"A85": ASCII85Decode,
|
||||
"ASCIIHexDecode": ASCIIHexDecode,
|
||||
"AHx": ASCIIHexDecode,
|
||||
"RunLengthDecode": RunLengthDecode,
|
||||
"RL": RunLengthDecode,
|
||||
"CCITTFaxDecode": CCITTFaxDecode,
|
||||
"CCF": CCITTFaxDecode,
|
||||
"DCTDecode": None, # FilterType.DCTDecode,
|
||||
"DCT": None, # FilterType.DCTDecode,
|
||||
"Crypt": None, # FilterType.Crypt,
|
||||
"JBIG2Decode": None, # FilterType.JBIG2Decode,
|
||||
"JPXDecode": None, # FilterType.JPXDecode,
|
||||
}
|
||||
|
||||
|
||||
def process_filters_on_data(
|
||||
data: bytes,
|
||||
it_filters: Iterator[FilterPair],
|
||||
) -> bytes:
|
||||
"""runs the filters provided by the list with the provided params against the data
|
||||
|
||||
Args:
|
||||
data (bytes)
|
||||
filters (Optional[List[str]])
|
||||
decode_params (Optional[List[Dict[str, Any]]])
|
||||
|
||||
Returns:
|
||||
bytes
|
||||
"""
|
||||
for f, params in it_filters:
|
||||
decoder = detect_decoder_type(f)
|
||||
data = decoder.decode(data, **params)
|
||||
return data
|
||||
|
||||
|
||||
def detect_decoder_type(name: str) -> Type[PDFFilterDecoder]:
|
||||
"""Check to see if the specified filter exists in our codebase
|
||||
|
||||
Args:
|
||||
name (str)
|
||||
|
||||
Raises:
|
||||
InvalidDecoderOrNotImplemented
|
||||
|
||||
Returns:
|
||||
Type[PDFFilterDecoder]
|
||||
"""
|
||||
decoder = _filter_type_name_mapping.get(name)
|
||||
if not decoder:
|
||||
raise NotImplementedError(
|
||||
f"Filter {name} is not implemented yet, feel free to submit a PR and help!"
|
||||
)
|
||||
return decoder
|
||||
@@ -0,0 +1,568 @@
|
||||
# CCITT Fax decoder
|
||||
#
|
||||
# Bugs: uncompressed mode untested.
|
||||
#
|
||||
# cf.
|
||||
# ITU-T Recommendation T.4
|
||||
# "Standardization of Group 3 facsimile terminals for document transmission"
|
||||
# ITU-T Recommendation T.6
|
||||
# "FACSIMILE CODING SCHEMES AND CODING CONTROL FUNCTIONS FOR GROUP 4 FACSIMILE APPARATUS"
|
||||
|
||||
|
||||
import array
|
||||
|
||||
from .exceptions import CCITEOFB, CCITByteSkip, CCITInvalidData
|
||||
|
||||
|
||||
def get_bytes(data):
|
||||
for byte in data:
|
||||
yield byte
|
||||
|
||||
|
||||
## BitParser
|
||||
##
|
||||
class BitParser(object):
|
||||
def __init__(self):
|
||||
self._pos = 0
|
||||
self._state = None
|
||||
return
|
||||
|
||||
@classmethod
|
||||
def add(cls, root, v, bits):
|
||||
p = root
|
||||
b = None
|
||||
for i in range(len(bits)):
|
||||
if 0 < i:
|
||||
if p[b] is None:
|
||||
p[b] = [None, None]
|
||||
p = p[b]
|
||||
if bits[i] == "1":
|
||||
b = 1
|
||||
else:
|
||||
b = 0
|
||||
p[b] = v
|
||||
return
|
||||
|
||||
def feedbytes(self, data):
|
||||
for byte in get_bytes(data):
|
||||
for m in (128, 64, 32, 16, 8, 4, 2, 1):
|
||||
self._parse_bit(byte & m)
|
||||
return
|
||||
|
||||
def _parse_bit(self, x):
|
||||
if x:
|
||||
v = self._state[1]
|
||||
else:
|
||||
v = self._state[0]
|
||||
self._pos += 1
|
||||
if isinstance(v, list):
|
||||
self._state = v
|
||||
else:
|
||||
self._state = self._accept(v)
|
||||
return
|
||||
|
||||
def _accept(self, v):
|
||||
raise NotImplementedError
|
||||
|
||||
|
||||
## CCITTG4Parser
|
||||
##
|
||||
class CCITTG4Parser(BitParser):
|
||||
|
||||
MODE = [None, None]
|
||||
BitParser.add(MODE, 0, "1")
|
||||
BitParser.add(MODE, +1, "011")
|
||||
BitParser.add(MODE, -1, "010")
|
||||
BitParser.add(MODE, "h", "001")
|
||||
BitParser.add(MODE, "p", "0001")
|
||||
BitParser.add(MODE, +2, "000011")
|
||||
BitParser.add(MODE, -2, "000010")
|
||||
BitParser.add(MODE, +3, "0000011")
|
||||
BitParser.add(MODE, -3, "0000010")
|
||||
BitParser.add(MODE, "u", "0000001111")
|
||||
BitParser.add(MODE, "x1", "0000001000")
|
||||
BitParser.add(MODE, "x2", "0000001001")
|
||||
BitParser.add(MODE, "x3", "0000001010")
|
||||
BitParser.add(MODE, "x4", "0000001011")
|
||||
BitParser.add(MODE, "x5", "0000001100")
|
||||
BitParser.add(MODE, "x6", "0000001101")
|
||||
BitParser.add(MODE, "x7", "0000001110")
|
||||
BitParser.add(MODE, "e", "000000000001000000000001")
|
||||
|
||||
WHITE = [None, None]
|
||||
BitParser.add(WHITE, 0, "00110101")
|
||||
BitParser.add(WHITE, 1, "000111")
|
||||
BitParser.add(WHITE, 2, "0111")
|
||||
BitParser.add(WHITE, 3, "1000")
|
||||
BitParser.add(WHITE, 4, "1011")
|
||||
BitParser.add(WHITE, 5, "1100")
|
||||
BitParser.add(WHITE, 6, "1110")
|
||||
BitParser.add(WHITE, 7, "1111")
|
||||
BitParser.add(WHITE, 8, "10011")
|
||||
BitParser.add(WHITE, 9, "10100")
|
||||
BitParser.add(WHITE, 10, "00111")
|
||||
BitParser.add(WHITE, 11, "01000")
|
||||
BitParser.add(WHITE, 12, "001000")
|
||||
BitParser.add(WHITE, 13, "000011")
|
||||
BitParser.add(WHITE, 14, "110100")
|
||||
BitParser.add(WHITE, 15, "110101")
|
||||
BitParser.add(WHITE, 16, "101010")
|
||||
BitParser.add(WHITE, 17, "101011")
|
||||
BitParser.add(WHITE, 18, "0100111")
|
||||
BitParser.add(WHITE, 19, "0001100")
|
||||
BitParser.add(WHITE, 20, "0001000")
|
||||
BitParser.add(WHITE, 21, "0010111")
|
||||
BitParser.add(WHITE, 22, "0000011")
|
||||
BitParser.add(WHITE, 23, "0000100")
|
||||
BitParser.add(WHITE, 24, "0101000")
|
||||
BitParser.add(WHITE, 25, "0101011")
|
||||
BitParser.add(WHITE, 26, "0010011")
|
||||
BitParser.add(WHITE, 27, "0100100")
|
||||
BitParser.add(WHITE, 28, "0011000")
|
||||
BitParser.add(WHITE, 29, "00000010")
|
||||
BitParser.add(WHITE, 30, "00000011")
|
||||
BitParser.add(WHITE, 31, "00011010")
|
||||
BitParser.add(WHITE, 32, "00011011")
|
||||
BitParser.add(WHITE, 33, "00010010")
|
||||
BitParser.add(WHITE, 34, "00010011")
|
||||
BitParser.add(WHITE, 35, "00010100")
|
||||
BitParser.add(WHITE, 36, "00010101")
|
||||
BitParser.add(WHITE, 37, "00010110")
|
||||
BitParser.add(WHITE, 38, "00010111")
|
||||
BitParser.add(WHITE, 39, "00101000")
|
||||
BitParser.add(WHITE, 40, "00101001")
|
||||
BitParser.add(WHITE, 41, "00101010")
|
||||
BitParser.add(WHITE, 42, "00101011")
|
||||
BitParser.add(WHITE, 43, "00101100")
|
||||
BitParser.add(WHITE, 44, "00101101")
|
||||
BitParser.add(WHITE, 45, "00000100")
|
||||
BitParser.add(WHITE, 46, "00000101")
|
||||
BitParser.add(WHITE, 47, "00001010")
|
||||
BitParser.add(WHITE, 48, "00001011")
|
||||
BitParser.add(WHITE, 49, "01010010")
|
||||
BitParser.add(WHITE, 50, "01010011")
|
||||
BitParser.add(WHITE, 51, "01010100")
|
||||
BitParser.add(WHITE, 52, "01010101")
|
||||
BitParser.add(WHITE, 53, "00100100")
|
||||
BitParser.add(WHITE, 54, "00100101")
|
||||
BitParser.add(WHITE, 55, "01011000")
|
||||
BitParser.add(WHITE, 56, "01011001")
|
||||
BitParser.add(WHITE, 57, "01011010")
|
||||
BitParser.add(WHITE, 58, "01011011")
|
||||
BitParser.add(WHITE, 59, "01001010")
|
||||
BitParser.add(WHITE, 60, "01001011")
|
||||
BitParser.add(WHITE, 61, "00110010")
|
||||
BitParser.add(WHITE, 62, "00110011")
|
||||
BitParser.add(WHITE, 63, "00110100")
|
||||
BitParser.add(WHITE, 64, "11011")
|
||||
BitParser.add(WHITE, 128, "10010")
|
||||
BitParser.add(WHITE, 192, "010111")
|
||||
BitParser.add(WHITE, 256, "0110111")
|
||||
BitParser.add(WHITE, 320, "00110110")
|
||||
BitParser.add(WHITE, 384, "00110111")
|
||||
BitParser.add(WHITE, 448, "01100100")
|
||||
BitParser.add(WHITE, 512, "01100101")
|
||||
BitParser.add(WHITE, 576, "01101000")
|
||||
BitParser.add(WHITE, 640, "01100111")
|
||||
BitParser.add(WHITE, 704, "011001100")
|
||||
BitParser.add(WHITE, 768, "011001101")
|
||||
BitParser.add(WHITE, 832, "011010010")
|
||||
BitParser.add(WHITE, 896, "011010011")
|
||||
BitParser.add(WHITE, 960, "011010100")
|
||||
BitParser.add(WHITE, 1024, "011010101")
|
||||
BitParser.add(WHITE, 1088, "011010110")
|
||||
BitParser.add(WHITE, 1152, "011010111")
|
||||
BitParser.add(WHITE, 1216, "011011000")
|
||||
BitParser.add(WHITE, 1280, "011011001")
|
||||
BitParser.add(WHITE, 1344, "011011010")
|
||||
BitParser.add(WHITE, 1408, "011011011")
|
||||
BitParser.add(WHITE, 1472, "010011000")
|
||||
BitParser.add(WHITE, 1536, "010011001")
|
||||
BitParser.add(WHITE, 1600, "010011010")
|
||||
BitParser.add(WHITE, 1664, "011000")
|
||||
BitParser.add(WHITE, 1728, "010011011")
|
||||
BitParser.add(WHITE, 1792, "00000001000")
|
||||
BitParser.add(WHITE, 1856, "00000001100")
|
||||
BitParser.add(WHITE, 1920, "00000001101")
|
||||
BitParser.add(WHITE, 1984, "000000010010")
|
||||
BitParser.add(WHITE, 2048, "000000010011")
|
||||
BitParser.add(WHITE, 2112, "000000010100")
|
||||
BitParser.add(WHITE, 2176, "000000010101")
|
||||
BitParser.add(WHITE, 2240, "000000010110")
|
||||
BitParser.add(WHITE, 2304, "000000010111")
|
||||
BitParser.add(WHITE, 2368, "000000011100")
|
||||
BitParser.add(WHITE, 2432, "000000011101")
|
||||
BitParser.add(WHITE, 2496, "000000011110")
|
||||
BitParser.add(WHITE, 2560, "000000011111")
|
||||
|
||||
BLACK = [None, None]
|
||||
BitParser.add(BLACK, 0, "0000110111")
|
||||
BitParser.add(BLACK, 1, "010")
|
||||
BitParser.add(BLACK, 2, "11")
|
||||
BitParser.add(BLACK, 3, "10")
|
||||
BitParser.add(BLACK, 4, "011")
|
||||
BitParser.add(BLACK, 5, "0011")
|
||||
BitParser.add(BLACK, 6, "0010")
|
||||
BitParser.add(BLACK, 7, "00011")
|
||||
BitParser.add(BLACK, 8, "000101")
|
||||
BitParser.add(BLACK, 9, "000100")
|
||||
BitParser.add(BLACK, 10, "0000100")
|
||||
BitParser.add(BLACK, 11, "0000101")
|
||||
BitParser.add(BLACK, 12, "0000111")
|
||||
BitParser.add(BLACK, 13, "00000100")
|
||||
BitParser.add(BLACK, 14, "00000111")
|
||||
BitParser.add(BLACK, 15, "000011000")
|
||||
BitParser.add(BLACK, 16, "0000010111")
|
||||
BitParser.add(BLACK, 17, "0000011000")
|
||||
BitParser.add(BLACK, 18, "0000001000")
|
||||
BitParser.add(BLACK, 19, "00001100111")
|
||||
BitParser.add(BLACK, 20, "00001101000")
|
||||
BitParser.add(BLACK, 21, "00001101100")
|
||||
BitParser.add(BLACK, 22, "00000110111")
|
||||
BitParser.add(BLACK, 23, "00000101000")
|
||||
BitParser.add(BLACK, 24, "00000010111")
|
||||
BitParser.add(BLACK, 25, "00000011000")
|
||||
BitParser.add(BLACK, 26, "000011001010")
|
||||
BitParser.add(BLACK, 27, "000011001011")
|
||||
BitParser.add(BLACK, 28, "000011001100")
|
||||
BitParser.add(BLACK, 29, "000011001101")
|
||||
BitParser.add(BLACK, 30, "000001101000")
|
||||
BitParser.add(BLACK, 31, "000001101001")
|
||||
BitParser.add(BLACK, 32, "000001101010")
|
||||
BitParser.add(BLACK, 33, "000001101011")
|
||||
BitParser.add(BLACK, 34, "000011010010")
|
||||
BitParser.add(BLACK, 35, "000011010011")
|
||||
BitParser.add(BLACK, 36, "000011010100")
|
||||
BitParser.add(BLACK, 37, "000011010101")
|
||||
BitParser.add(BLACK, 38, "000011010110")
|
||||
BitParser.add(BLACK, 39, "000011010111")
|
||||
BitParser.add(BLACK, 40, "000001101100")
|
||||
BitParser.add(BLACK, 41, "000001101101")
|
||||
BitParser.add(BLACK, 42, "000011011010")
|
||||
BitParser.add(BLACK, 43, "000011011011")
|
||||
BitParser.add(BLACK, 44, "000001010100")
|
||||
BitParser.add(BLACK, 45, "000001010101")
|
||||
BitParser.add(BLACK, 46, "000001010110")
|
||||
BitParser.add(BLACK, 47, "000001010111")
|
||||
BitParser.add(BLACK, 48, "000001100100")
|
||||
BitParser.add(BLACK, 49, "000001100101")
|
||||
BitParser.add(BLACK, 50, "000001010010")
|
||||
BitParser.add(BLACK, 51, "000001010011")
|
||||
BitParser.add(BLACK, 52, "000000100100")
|
||||
BitParser.add(BLACK, 53, "000000110111")
|
||||
BitParser.add(BLACK, 54, "000000111000")
|
||||
BitParser.add(BLACK, 55, "000000100111")
|
||||
BitParser.add(BLACK, 56, "000000101000")
|
||||
BitParser.add(BLACK, 57, "000001011000")
|
||||
BitParser.add(BLACK, 58, "000001011001")
|
||||
BitParser.add(BLACK, 59, "000000101011")
|
||||
BitParser.add(BLACK, 60, "000000101100")
|
||||
BitParser.add(BLACK, 61, "000001011010")
|
||||
BitParser.add(BLACK, 62, "000001100110")
|
||||
BitParser.add(BLACK, 63, "000001100111")
|
||||
BitParser.add(BLACK, 64, "0000001111")
|
||||
BitParser.add(BLACK, 128, "000011001000")
|
||||
BitParser.add(BLACK, 192, "000011001001")
|
||||
BitParser.add(BLACK, 256, "000001011011")
|
||||
BitParser.add(BLACK, 320, "000000110011")
|
||||
BitParser.add(BLACK, 384, "000000110100")
|
||||
BitParser.add(BLACK, 448, "000000110101")
|
||||
BitParser.add(BLACK, 512, "0000001101100")
|
||||
BitParser.add(BLACK, 576, "0000001101101")
|
||||
BitParser.add(BLACK, 640, "0000001001010")
|
||||
BitParser.add(BLACK, 704, "0000001001011")
|
||||
BitParser.add(BLACK, 768, "0000001001100")
|
||||
BitParser.add(BLACK, 832, "0000001001101")
|
||||
BitParser.add(BLACK, 896, "0000001110010")
|
||||
BitParser.add(BLACK, 960, "0000001110011")
|
||||
BitParser.add(BLACK, 1024, "0000001110100")
|
||||
BitParser.add(BLACK, 1088, "0000001110101")
|
||||
BitParser.add(BLACK, 1152, "0000001110110")
|
||||
BitParser.add(BLACK, 1216, "0000001110111")
|
||||
BitParser.add(BLACK, 1280, "0000001010010")
|
||||
BitParser.add(BLACK, 1344, "0000001010011")
|
||||
BitParser.add(BLACK, 1408, "0000001010100")
|
||||
BitParser.add(BLACK, 1472, "0000001010101")
|
||||
BitParser.add(BLACK, 1536, "0000001011010")
|
||||
BitParser.add(BLACK, 1600, "0000001011011")
|
||||
BitParser.add(BLACK, 1664, "0000001100100")
|
||||
BitParser.add(BLACK, 1728, "0000001100101")
|
||||
BitParser.add(BLACK, 1792, "00000001000")
|
||||
BitParser.add(BLACK, 1856, "00000001100")
|
||||
BitParser.add(BLACK, 1920, "00000001101")
|
||||
BitParser.add(BLACK, 1984, "000000010010")
|
||||
BitParser.add(BLACK, 2048, "000000010011")
|
||||
BitParser.add(BLACK, 2112, "000000010100")
|
||||
BitParser.add(BLACK, 2176, "000000010101")
|
||||
BitParser.add(BLACK, 2240, "000000010110")
|
||||
BitParser.add(BLACK, 2304, "000000010111")
|
||||
BitParser.add(BLACK, 2368, "000000011100")
|
||||
BitParser.add(BLACK, 2432, "000000011101")
|
||||
BitParser.add(BLACK, 2496, "000000011110")
|
||||
BitParser.add(BLACK, 2560, "000000011111")
|
||||
|
||||
UNCOMPRESSED = [None, None]
|
||||
BitParser.add(UNCOMPRESSED, "1", "1")
|
||||
BitParser.add(UNCOMPRESSED, "01", "01")
|
||||
BitParser.add(UNCOMPRESSED, "001", "001")
|
||||
BitParser.add(UNCOMPRESSED, "0001", "0001")
|
||||
BitParser.add(UNCOMPRESSED, "00001", "00001")
|
||||
BitParser.add(UNCOMPRESSED, "00000", "000001")
|
||||
BitParser.add(UNCOMPRESSED, "T00", "00000011")
|
||||
BitParser.add(UNCOMPRESSED, "T10", "00000010")
|
||||
BitParser.add(UNCOMPRESSED, "T000", "000000011")
|
||||
BitParser.add(UNCOMPRESSED, "T100", "000000010")
|
||||
BitParser.add(UNCOMPRESSED, "T0000", "0000000011")
|
||||
BitParser.add(UNCOMPRESSED, "T1000", "0000000010")
|
||||
BitParser.add(UNCOMPRESSED, "T00000", "00000000011")
|
||||
BitParser.add(UNCOMPRESSED, "T10000", "00000000010")
|
||||
|
||||
def __init__(self, width, bytealign=False):
|
||||
BitParser.__init__(self)
|
||||
self.width = width
|
||||
self.bytealign = bytealign
|
||||
self.reset()
|
||||
return
|
||||
|
||||
def feedbytes(self, data):
|
||||
for byte in get_bytes(data):
|
||||
try:
|
||||
for m in (128, 64, 32, 16, 8, 4, 2, 1):
|
||||
self._parse_bit(byte & m)
|
||||
except CCITByteSkip:
|
||||
self._accept = self._parse_mode
|
||||
self._state = self.MODE
|
||||
except CCITEOFB:
|
||||
break
|
||||
return
|
||||
|
||||
def _parse_mode(self, mode: str):
|
||||
if mode == "p":
|
||||
self._do_pass()
|
||||
self._flush_line()
|
||||
return self.MODE
|
||||
elif mode == "h":
|
||||
self._n1 = 0
|
||||
self._accept = self._parse_horiz1 # type: ignore
|
||||
if self._color:
|
||||
return self.WHITE
|
||||
else:
|
||||
return self.BLACK
|
||||
elif mode == "u":
|
||||
self._accept = self._parse_uncompressed # type: ignore
|
||||
return self.UNCOMPRESSED
|
||||
elif mode == "e":
|
||||
raise CCITEOFB
|
||||
elif isinstance(mode, int):
|
||||
self._do_vertical(mode)
|
||||
self._flush_line()
|
||||
return self.MODE
|
||||
else:
|
||||
raise CCITInvalidData(mode)
|
||||
|
||||
def _parse_horiz1(self, n):
|
||||
if n is None:
|
||||
raise CCITInvalidData
|
||||
self._n1 += n
|
||||
if n < 64:
|
||||
self._n2 = 0
|
||||
self._color = 1 - self._color
|
||||
self._accept = self._parse_horiz2
|
||||
if self._color:
|
||||
return self.WHITE
|
||||
else:
|
||||
return self.BLACK
|
||||
|
||||
def _parse_horiz2(self, n):
|
||||
if n is None:
|
||||
raise CCITInvalidData
|
||||
self._n2 += n
|
||||
if n < 64:
|
||||
self._color = 1 - self._color
|
||||
self._accept = self._parse_mode
|
||||
self._do_horizontal(self._n1, self._n2)
|
||||
self._flush_line()
|
||||
return self.MODE
|
||||
elif self._color:
|
||||
return self.WHITE
|
||||
else:
|
||||
return self.BLACK
|
||||
|
||||
def _parse_uncompressed(self, bits):
|
||||
if not bits:
|
||||
raise CCITInvalidData
|
||||
if bits.startswith("T"):
|
||||
self._accept = self._parse_mode
|
||||
self._color = int(bits[1])
|
||||
self._do_uncompressed(bits[2:])
|
||||
return self.MODE
|
||||
else:
|
||||
self._do_uncompressed(bits)
|
||||
return self.UNCOMPRESSED
|
||||
|
||||
def _get_bits(self):
|
||||
return "".join(str(b) for b in self._curline[: self._curpos])
|
||||
|
||||
def _get_refline(self, i):
|
||||
if i < 0:
|
||||
return "[]" + "".join(str(b) for b in self._refline)
|
||||
elif len(self._refline) <= i:
|
||||
return "".join(str(b) for b in self._refline) + "[]"
|
||||
else:
|
||||
return (
|
||||
"".join(str(b) for b in self._refline[:i])
|
||||
+ "["
|
||||
+ str(self._refline[i])
|
||||
+ "]"
|
||||
+ "".join(str(b) for b in self._refline[i + 1 :])
|
||||
)
|
||||
|
||||
def reset(self):
|
||||
self._y = 0
|
||||
self._curline = array.array("b", [1] * self.width)
|
||||
self._reset_line()
|
||||
self._accept = self._parse_mode
|
||||
self._state = self.MODE
|
||||
return
|
||||
|
||||
def output_line(self, y, bits):
|
||||
print(y, "".join(str(b) for b in bits))
|
||||
return
|
||||
|
||||
def _reset_line(self):
|
||||
self._refline = self._curline
|
||||
self._curline = array.array("b", [1] * self.width)
|
||||
self._curpos = -1
|
||||
self._color = 1
|
||||
return
|
||||
|
||||
def _flush_line(self):
|
||||
if self.width <= self._curpos:
|
||||
self.output_line(self._y, self._curline)
|
||||
self._y += 1
|
||||
self._reset_line()
|
||||
if self.bytealign:
|
||||
raise CCITByteSkip
|
||||
return
|
||||
|
||||
def _do_vertical(self, dx):
|
||||
x1 = self._curpos + 1
|
||||
while 1:
|
||||
if x1 == 0:
|
||||
if self._color == 1 and self._refline[x1] != self._color:
|
||||
break
|
||||
elif x1 == len(self._refline):
|
||||
break
|
||||
elif (
|
||||
self._refline[x1 - 1] == self._color
|
||||
and self._refline[x1] != self._color
|
||||
):
|
||||
break
|
||||
x1 += 1
|
||||
x1 += dx
|
||||
x0 = max(0, self._curpos)
|
||||
x1 = max(0, min(self.width, x1))
|
||||
if x1 < x0:
|
||||
for x in range(x1, x0):
|
||||
self._curline[x] = self._color
|
||||
elif x0 < x1:
|
||||
for x in range(x0, x1):
|
||||
self._curline[x] = self._color
|
||||
self._curpos = x1
|
||||
self._color = 1 - self._color
|
||||
return
|
||||
|
||||
def _do_pass(self):
|
||||
x1 = self._curpos + 1
|
||||
while 1:
|
||||
if x1 == 0:
|
||||
if self._color == 1 and self._refline[x1] != self._color:
|
||||
break
|
||||
elif x1 == len(self._refline):
|
||||
break
|
||||
elif (
|
||||
self._refline[x1 - 1] == self._color
|
||||
and self._refline[x1] != self._color
|
||||
):
|
||||
break
|
||||
x1 += 1
|
||||
while 1:
|
||||
if x1 == 0:
|
||||
if self._color == 0 and self._refline[x1] == self._color:
|
||||
break
|
||||
elif x1 == len(self._refline):
|
||||
break
|
||||
elif (
|
||||
self._refline[x1 - 1] != self._color
|
||||
and self._refline[x1] == self._color
|
||||
):
|
||||
break
|
||||
x1 += 1
|
||||
for x in range(self._curpos, x1):
|
||||
self._curline[x] = self._color
|
||||
self._curpos = x1
|
||||
return
|
||||
|
||||
def _do_horizontal(self, n1, n2):
|
||||
if self._curpos < 0:
|
||||
self._curpos = 0
|
||||
x = self._curpos
|
||||
for _ in range(n1):
|
||||
if len(self._curline) <= x:
|
||||
break
|
||||
self._curline[x] = self._color
|
||||
x += 1
|
||||
for _ in range(n2):
|
||||
if len(self._curline) <= x:
|
||||
break
|
||||
self._curline[x] = 1 - self._color
|
||||
x += 1
|
||||
self._curpos = x
|
||||
return
|
||||
|
||||
def _do_uncompressed(self, bits):
|
||||
for c in bits:
|
||||
self._curline[self._curpos] = int(c)
|
||||
self._curpos += 1
|
||||
self._flush_line()
|
||||
return
|
||||
|
||||
|
||||
class CCITTFaxDecoder(CCITTG4Parser):
|
||||
def __init__(self, width, bytealign=False, reversed=False):
|
||||
CCITTG4Parser.__init__(self, width, bytealign=bytealign)
|
||||
self.reversed = reversed
|
||||
self._buf: bytes = b""
|
||||
return
|
||||
|
||||
def close(self) -> bytes:
|
||||
return self._buf
|
||||
|
||||
def output_line(self, y, bits):
|
||||
bytes = array.array("B", [0] * ((len(bits) + 7) // 8))
|
||||
if self.reversed:
|
||||
bits = [1 - b for b in bits]
|
||||
for (i, b) in enumerate(bits):
|
||||
if b:
|
||||
bytes[i // 8] += (128, 64, 32, 16, 8, 4, 2, 1)[i % 8]
|
||||
self._buf += bytes.tostring()
|
||||
return
|
||||
|
||||
|
||||
def ccittfaxdecode(
|
||||
data: bytes,
|
||||
# arguments for algo, with defaults based on PDF spec 1.7 section 7.4.6
|
||||
Columns: int = 1728,
|
||||
EncodedByteAlign: bool = False,
|
||||
BlackIs1: bool = False,
|
||||
K: int = 0,
|
||||
EndOfLine: bool = False,
|
||||
Rows: int = 0,
|
||||
DamagedRowsBeforeError: int = 0,
|
||||
) -> bytes:
|
||||
if K == -1:
|
||||
parser = CCITTFaxDecoder(Columns, bytealign=EncodedByteAlign, reversed=BlackIs1)
|
||||
else:
|
||||
raise ValueError(K)
|
||||
parser.feedbytes(data)
|
||||
return parser.close()
|
||||
@@ -0,0 +1,48 @@
|
||||
import zlib
|
||||
from base64 import a85decode
|
||||
from binascii import a2b_hex
|
||||
from typing import Any
|
||||
|
||||
from .ccit import ccittfaxdecode
|
||||
from .lzw import lzwdecode
|
||||
from .rld import rldecode
|
||||
from .types import PDFFilterDecoder
|
||||
|
||||
|
||||
class ASCIIHexDecode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
clean_data = b"".join(data.split(b" "))
|
||||
if len(clean_data) & 2 != 0:
|
||||
clean_data += b"0"
|
||||
return a2b_hex(clean_data)
|
||||
|
||||
|
||||
class ASCII85Decode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
return a85decode(data, adobe=True)
|
||||
|
||||
|
||||
class LZWDecode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
return lzwdecode(data)
|
||||
|
||||
|
||||
class FlateDecode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
return zlib.decompress(data.strip(b"\r\n"))
|
||||
|
||||
|
||||
class RunLengthDecode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
return rldecode(data)
|
||||
|
||||
|
||||
class CCITTFaxDecode(PDFFilterDecoder):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
return ccittfaxdecode(data, **decode_params)
|
||||
@@ -0,0 +1,25 @@
|
||||
from pdfmajor.exceptions import BrokenFile
|
||||
|
||||
|
||||
class FilterError(BrokenFile):
|
||||
pass
|
||||
|
||||
|
||||
class DecodeFailed(FilterError):
|
||||
pass
|
||||
|
||||
|
||||
class InvalidDecoderOrNotImplemented(DecodeFailed, NotImplementedError):
|
||||
pass
|
||||
|
||||
|
||||
class CCITEOFB(DecodeFailed, EOFError):
|
||||
pass
|
||||
|
||||
|
||||
class CCITInvalidData(DecodeFailed):
|
||||
pass
|
||||
|
||||
|
||||
class CCITByteSkip(DecodeFailed):
|
||||
pass
|
||||
@@ -1,43 +1,38 @@
|
||||
|
||||
from io import BytesIO
|
||||
from ..utils import int2byte
|
||||
from typing import List, Optional
|
||||
|
||||
import logging
|
||||
|
||||
class CorruptDataError(Exception):
|
||||
pass
|
||||
from .exceptions import DecodeFailed
|
||||
|
||||
|
||||
## LZWDecoder
|
||||
##
|
||||
class LZWDecoder(object):
|
||||
|
||||
def __init__(self, fp):
|
||||
def __init__(self, fp: BytesIO):
|
||||
self.fp = fp
|
||||
self.buff = 0
|
||||
self.bpos = 8
|
||||
self.nbits = 9
|
||||
self.table = None
|
||||
self.prevbuf = None
|
||||
self.buff: int = 0
|
||||
self.bpos: int = 8
|
||||
self.nbits: int = 9
|
||||
self.table: Optional[List[Optional[bytes]]] = None
|
||||
self.prevbuf: Optional[bytes] = None
|
||||
return
|
||||
|
||||
def readbits(self, bits):
|
||||
v = 0
|
||||
while 1:
|
||||
# the number of remaining bits we can get from the current buffer.
|
||||
r = 8-self.bpos
|
||||
r = 8 - self.bpos
|
||||
if bits <= r:
|
||||
# |-----8-bits-----|
|
||||
# |-bpos-|-bits-| |
|
||||
# | |----r----|
|
||||
v = (v << bits) | ((self.buff >> (r-bits)) & ((1 << bits)-1))
|
||||
v = (v << bits) | ((self.buff >> (r - bits)) & ((1 << bits) - 1))
|
||||
self.bpos += bits
|
||||
break
|
||||
else:
|
||||
# |-----8-bits-----|
|
||||
# |-bpos-|---bits----...
|
||||
# | |----r----|
|
||||
v = (v << r) | (self.buff & ((1 << r)-1))
|
||||
v = (v << r) | (self.buff & ((1 << r) - 1))
|
||||
bits -= r
|
||||
x = self.fp.read(1)
|
||||
if not x:
|
||||
@@ -47,27 +42,27 @@ class LZWDecoder(object):
|
||||
return v
|
||||
|
||||
def feed(self, code):
|
||||
x = b''
|
||||
x = b""
|
||||
if code == 256:
|
||||
self.table = [int2byte(c) for c in range(256)] # 0-255
|
||||
self.table = [bytes([c]) for c in range(256)] # 0-255
|
||||
self.table.append(None) # 256
|
||||
self.table.append(None) # 257
|
||||
self.prevbuf = b''
|
||||
self.prevbuf = b""
|
||||
self.nbits = 9
|
||||
elif code == 257:
|
||||
pass
|
||||
elif not self.prevbuf:
|
||||
x = self.prevbuf = self.table[code]
|
||||
else:
|
||||
if code < len(self.table):
|
||||
if code < len(self.table): # type: ignore
|
||||
x = self.table[code]
|
||||
self.table.append(self.prevbuf+x[:1])
|
||||
elif code == len(self.table):
|
||||
self.table.append(self.prevbuf+self.prevbuf[:1])
|
||||
self.table.append(self.prevbuf + x[:1])
|
||||
elif code == len(self.table): # type: ignore
|
||||
self.table.append(self.prevbuf + self.prevbuf[:1])
|
||||
x = self.table[code]
|
||||
else:
|
||||
raise CorruptDataError
|
||||
l = len(self.table)
|
||||
raise DecodeFailed("LZW")
|
||||
l = len(self.table) # type: ignore
|
||||
if l == 511:
|
||||
self.nbits = 10
|
||||
elif l == 1023:
|
||||
@@ -81,21 +76,15 @@ class LZWDecoder(object):
|
||||
while 1:
|
||||
try:
|
||||
code = self.readbits(self.nbits)
|
||||
x = self.feed(code)
|
||||
except EOFError:
|
||||
break
|
||||
try:
|
||||
x = self.feed(code)
|
||||
except CorruptDataError:
|
||||
# just ignore corrupt data and stop yielding there
|
||||
break
|
||||
yield x
|
||||
logging.debug('nbits=%d, code=%d, output=%r, table=%r' %
|
||||
(self.nbits, code, x, self.table[258:]))
|
||||
return
|
||||
|
||||
|
||||
# lzwdecode
|
||||
def lzwdecode(data):
|
||||
def lzwdecode(data: bytes) -> bytes:
|
||||
fp = BytesIO(data)
|
||||
s=LZWDecoder(fp).run()
|
||||
return b''.join(s)
|
||||
s = LZWDecoder(fp).run()
|
||||
return b"".join(s) # type: ignore
|
||||
@@ -0,0 +1,36 @@
|
||||
#
|
||||
# RunLength decoder (Adobe version) implementation based on PDF Reference
|
||||
# version 1.4 section 3.3.4.
|
||||
#
|
||||
# * public domain *
|
||||
#
|
||||
def rldecode(data: bytes) -> bytes:
|
||||
"""
|
||||
RunLength decoder (Adobe version) implementation based on PDF Reference
|
||||
version 1.4 section 3.3.4:
|
||||
The RunLengthDecode filter decodes data that has been encoded in a
|
||||
simple byte-oriented format based on run length. The encoded data
|
||||
is a sequence of runs, where each run consists of a length byte
|
||||
followed by 1 to 128 bytes of data. If the length byte is in the
|
||||
range 0 to 127, the following length + 1 (1 to 128) bytes are
|
||||
copied literally during decompression. If length is in the range
|
||||
129 to 255, the following single byte is to be copied 257 - length
|
||||
(2 to 128) times during decompression. A length value of 128
|
||||
denotes EOD.
|
||||
"""
|
||||
decoded = b""
|
||||
i: int = 0
|
||||
while i < len(data):
|
||||
length = data[i]
|
||||
if length == 128:
|
||||
break
|
||||
if length >= 0 and length < 128:
|
||||
for j in range(i + 1, (i + 1) + (length + 1)):
|
||||
decoded += bytes([data[j]])
|
||||
|
||||
i = (i + 1) + (length + 1)
|
||||
if length > 128:
|
||||
run: bytes = bytes([data[i + 1]]) * (257 - length)
|
||||
decoded += run
|
||||
i = (i + 1) + 1
|
||||
return decoded
|
||||
@@ -0,0 +1,13 @@
|
||||
from abc import ABCMeta
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from .exceptions import InvalidDecoderOrNotImplemented
|
||||
|
||||
|
||||
class PDFFilterDecoder(metaclass=ABCMeta):
|
||||
@staticmethod
|
||||
def decode(data: bytes, **decode_params: Any) -> bytes:
|
||||
raise InvalidDecoderOrNotImplemented
|
||||
|
||||
|
||||
FilterPair = Tuple[str, Dict[str, Any]]
|
||||
@@ -0,0 +1,30 @@
|
||||
from pdfmajor.fonts.exceptions import InvalidFont
|
||||
from typing import Any, Dict
|
||||
from .base import PDFFont
|
||||
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)
|
||||
@@ -0,0 +1,17 @@
|
||||
from abc import ABCMeta, abstractclassmethod
|
||||
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: str, **kwrg: Any) -> None:
|
||||
self.subtype = subtype
|
||||
self.raw = kwrg
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"PDFFont:{self.subtype}({self.raw})"
|
||||
|
||||
@abstractclassmethod
|
||||
def from_dict(cls, d: Dict[str, Any]) -> "PDFFont":
|
||||
raise NotImplementedError
|
||||
@@ -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)
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 41139 52164", "FontName": "Courier-Bold", "FullName": "Courier Bold", "FamilyName": "Courier", "Weight": "Bold", "ItalicAngle": 0, "IsFixedPitch": true, "CharacterSet": "ExtendedRoman", "FontBBox": [-113, -250, 749, 801], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 3.0, "Notice": "Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 562, "XHeight": 439, "Ascender": 629, "Descender": -157, "StdHW": 84, "StdVW": 106}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 17529 79244", "FontName": "Courier-BoldOblique", "FullName": "Courier Bold Oblique", "FamilyName": "Courier", "Weight": "Bold", "ItalicAngle": -12, "IsFixedPitch": true, "CharacterSet": "ExtendedRoman", "FontBBox": [-57, -250, 869, 801], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 3.0, "Notice": "Copyright (c) 1989, 1990, 1991, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 562, "XHeight": 439, "Ascender": 629, "Descender": -157, "StdHW": 84, "StdVW": 106}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 16248 75829", "FontName": "Courier-Oblique", "FullName": "Courier Oblique", "FamilyName": "Courier", "Weight": "Medium", "ItalicAngle": -12, "IsFixedPitch": true, "CharacterSet": "ExtendedRoman", "FontBBox": [-27, -250, 849, 805], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 3.0, "Notice": "Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 562, "XHeight": 426, "Ascender": 629, "Descender": -157, "StdHW": 51, "StdVW": 51}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 39754 50779", "FontName": "Courier", "FullName": "Courier", "FamilyName": "Courier", "Weight": "Medium", "ItalicAngle": 0, "IsFixedPitch": true, "CharacterSet": "ExtendedRoman", "FontBBox": [-23, -250, 715, 805], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 3.0, "Notice": "Copyright (c) 1989, 1990, 1991, 1992, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 562, "XHeight": 426, "Ascender": 629, "Descender": -157, "StdHW": 51, "StdVW": 51}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600, 600]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 37169 48194", "FontName": "Helvetica-Bold", "FullName": "Helvetica Bold", "FamilyName": "Helvetica", "Weight": "Bold", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-170, -228, 1003, 962], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 718, "XHeight": 532, "Ascender": 718, "Descender": -207, "StdHW": 118, "StdVW": 140}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [278, 333, 474, 556, 556, 889, 722, 278, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 278, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 333, 556, 556, 167, 556, 556, 556, 556, 238, 500, 556, 333, 333, 611, 611, 556, 556, 556, 278, 556, 350, 278, 500, 500, 556, 1000, 1000, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 1000, 370, 611, 778, 1000, 365, 889, 278, 278, 611, 944, 611, 278, 556, 556, 611, 556, 667, 584, 667, 722, 556, 722, 556, 556, 556, 722, 722, 556, 722, 611, 667, 722, 250, 737, 667, 556, 556, 722, 278, 556, 611, 722, 556, 667, 556, 556, 278, 494, 722, 778, 611, 556, 722, 389, 556, 611, 667, 778, 722, 667, 743, 722, 611, 333, 778, 722, 722, 584, 611, 611, 494, 556, 722, 278, 667, 556, 556, 556, 611, 611, 722, 278, 584, 280, 737, 778, 278, 600, 667, 389, 611, 611, 611, 549, 722, 722, 278, 389, 556, 722, 722, 722, 556, 500, 278, 778, 611, 556, 556, 278, 778, 722, 612, 611, 333, 778, 611, 278, 611, 667, 611, 834, 667, 400, 722, 611, 1000, 556, 278, 278, 611, 834, 549, 611, 611, 722, 667, 556, 611, 834, 667, 667, 778, 400, 611, 722, 611, 549, 722, 389, 722, 611, 722, 611, 722, 722, 722, 778, 500, 667, 278, 556, 584, 278, 611, 333, 584, 611, 611, 549, 611, 611, 500, 611, 333, 278, 556]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 14482 68586", "FontName": "Helvetica-BoldOblique", "FullName": "Helvetica Bold Oblique", "FamilyName": "Helvetica", "Weight": "Bold", "ItalicAngle": -12, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-174, -228, 1114, 962], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 718, "XHeight": 532, "Ascender": 718, "Descender": -207, "StdHW": 118, "StdVW": 140}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [278, 333, 474, 556, 556, 889, 722, 278, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 333, 333, 584, 584, 584, 611, 975, 722, 722, 722, 722, 667, 611, 778, 722, 278, 556, 722, 611, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 333, 278, 333, 584, 556, 278, 556, 611, 556, 611, 556, 333, 611, 611, 278, 278, 556, 278, 889, 611, 611, 611, 611, 389, 556, 333, 611, 556, 778, 556, 556, 500, 389, 280, 389, 584, 333, 556, 556, 167, 556, 556, 556, 556, 238, 500, 556, 333, 333, 611, 611, 556, 556, 556, 278, 556, 350, 278, 500, 500, 556, 1000, 1000, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 1000, 370, 611, 778, 1000, 365, 889, 278, 278, 611, 944, 611, 278, 556, 556, 611, 556, 667, 584, 667, 722, 556, 722, 556, 556, 556, 722, 722, 556, 722, 611, 667, 722, 250, 737, 667, 556, 556, 722, 278, 556, 611, 722, 556, 667, 556, 556, 278, 494, 722, 778, 611, 556, 722, 389, 556, 611, 667, 778, 722, 667, 743, 722, 611, 333, 778, 722, 722, 584, 611, 611, 494, 556, 722, 278, 667, 556, 556, 556, 611, 611, 722, 278, 584, 280, 737, 778, 278, 600, 667, 389, 611, 611, 611, 549, 722, 722, 278, 389, 556, 722, 722, 722, 556, 500, 278, 778, 611, 556, 556, 278, 778, 722, 612, 611, 333, 778, 611, 278, 611, 667, 611, 834, 667, 400, 722, 611, 1000, 556, 278, 278, 611, 834, 549, 611, 611, 722, 667, 556, 611, 834, 667, 667, 778, 400, 611, 722, 611, 549, 722, 389, 722, 611, 722, 611, 722, 722, 722, 778, 500, 667, 278, 556, 584, 278, 611, 333, 584, 611, 611, 549, 611, 611, 500, 611, 333, 278, 556]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 14960 69346", "FontName": "Helvetica-Oblique", "FullName": "Helvetica Oblique", "FamilyName": "Helvetica", "Weight": "Medium", "ItalicAngle": -12, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-170, -225, 1116, 931], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 718, "XHeight": 523, "Ascender": 718, "Descender": -207, "StdHW": 76, "StdVW": 88}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [278, 278, 355, 556, 556, 889, 667, 222, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 222, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 333, 556, 556, 167, 556, 556, 556, 556, 191, 333, 556, 333, 333, 500, 500, 556, 556, 556, 278, 537, 350, 222, 333, 333, 556, 1000, 1000, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 1000, 370, 556, 778, 1000, 365, 889, 278, 222, 611, 944, 611, 278, 556, 556, 556, 556, 667, 584, 667, 667, 556, 722, 500, 500, 556, 722, 722, 556, 722, 556, 667, 722, 250, 737, 667, 500, 556, 722, 222, 556, 611, 722, 556, 667, 500, 500, 278, 471, 722, 778, 556, 556, 667, 333, 500, 611, 667, 778, 722, 667, 643, 722, 556, 333, 778, 667, 667, 584, 556, 611, 476, 500, 722, 278, 667, 556, 556, 500, 556, 556, 722, 278, 584, 260, 737, 778, 278, 600, 667, 333, 556, 611, 611, 549, 722, 722, 222, 317, 556, 722, 667, 667, 556, 500, 222, 778, 556, 556, 500, 278, 778, 722, 612, 556, 333, 778, 556, 278, 556, 667, 556, 834, 667, 299, 667, 556, 1000, 556, 278, 278, 556, 834, 549, 556, 556, 722, 667, 556, 556, 834, 667, 667, 778, 400, 556, 722, 556, 453, 722, 333, 722, 556, 722, 556, 667, 667, 667, 778, 500, 667, 278, 500, 584, 278, 556, 278, 584, 556, 556, 549, 556, 556, 500, 556, 333, 278, 556]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 37069 48094", "FontName": "Helvetica", "FullName": "Helvetica", "FamilyName": "Helvetica", "Weight": "Medium", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-166, -225, 1000, 931], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All Rights Reserved.Helvetica is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 718, "XHeight": 523, "Ascender": 718, "Descender": -207, "StdHW": 76, "StdVW": 88}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [278, 278, 355, 556, 556, 889, 667, 222, 333, 333, 389, 584, 278, 333, 278, 278, 556, 556, 556, 556, 556, 556, 556, 556, 556, 556, 278, 278, 584, 584, 584, 556, 1015, 667, 667, 722, 722, 667, 611, 778, 722, 278, 500, 667, 556, 833, 722, 778, 667, 778, 722, 667, 611, 722, 667, 944, 667, 667, 611, 278, 278, 278, 469, 556, 222, 556, 556, 500, 556, 556, 278, 556, 556, 222, 222, 500, 222, 833, 556, 556, 556, 556, 333, 500, 278, 556, 500, 722, 500, 500, 500, 334, 260, 334, 584, 333, 556, 556, 167, 556, 556, 556, 556, 191, 333, 556, 333, 333, 500, 500, 556, 556, 556, 278, 537, 350, 222, 333, 333, 556, 1000, 1000, 611, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 1000, 370, 556, 778, 1000, 365, 889, 278, 222, 611, 944, 611, 278, 556, 556, 556, 556, 667, 584, 667, 667, 556, 722, 500, 500, 556, 722, 722, 556, 722, 556, 667, 722, 250, 737, 667, 500, 556, 722, 222, 556, 611, 722, 556, 667, 500, 500, 278, 471, 722, 778, 556, 556, 667, 333, 500, 611, 667, 778, 722, 667, 643, 722, 556, 333, 778, 667, 667, 584, 556, 611, 476, 500, 722, 278, 667, 556, 556, 500, 556, 556, 722, 278, 584, 260, 737, 778, 278, 600, 667, 333, 556, 611, 611, 549, 722, 722, 222, 317, 556, 722, 667, 667, 556, 500, 222, 778, 556, 556, 500, 278, 778, 722, 612, 556, 333, 778, 556, 278, 556, 667, 556, 834, 667, 299, 667, 556, 1000, 556, 278, 278, 556, 834, 549, 556, 556, 722, 667, 556, 556, 834, 667, 667, 778, 400, 556, 722, 556, 453, 722, 333, 722, 556, 722, 556, 667, 667, 667, 778, 500, 667, 278, 500, 584, 278, 556, 278, 584, 556, 556, 549, 556, 556, 500, 556, 333, 278, 556]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 30820 39997", "FontName": "Symbol", "FullName": "Symbol", "FamilyName": "Symbol", "Weight": "Medium", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "Special", "FontBBox": [-180, -293, 1090, 1010], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 1.008, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1997 Adobe Systems Incorporated. All rights reserved.", "EncodingScheme": "FontSpecific", "StdHW": 92, "StdVW": 85}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 160, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254, -1], "widths": [250, 333, 713, 500, 549, 833, 778, 439, 333, 333, 500, 549, 250, 549, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 549, 549, 549, 444, 549, 722, 667, 722, 612, 611, 763, 603, 722, 333, 631, 722, 686, 889, 722, 722, 768, 741, 556, 592, 611, 690, 439, 768, 645, 795, 611, 333, 863, 333, 658, 500, 500, 631, 549, 549, 494, 439, 521, 411, 603, 329, 603, 549, 549, 576, 521, 549, 549, 521, 549, 603, 439, 576, 713, 686, 493, 686, 494, 480, 200, 480, 549, 750, 620, 247, 549, 167, 713, 500, 753, 753, 753, 753, 1042, 987, 603, 987, 603, 400, 549, 411, 549, 549, 713, 494, 460, 549, 549, 549, 549, 1000, 603, 1000, 658, 823, 686, 795, 987, 768, 768, 823, 768, 768, 713, 713, 713, 713, 713, 713, 713, 768, 713, 790, 790, 890, 823, 549, 250, 713, 603, 603, 1042, 987, 603, 987, 603, 494, 329, 790, 790, 786, 713, 384, 384, 384, 384, 384, 384, 494, 494, 494, 494, 329, 274, 686, 686, 686, 384, 384, 384, 384, 384, 384, 494, 494, 494, 790]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 41636 52661", "FontName": "Times-Bold", "FullName": "Times Bold", "FamilyName": "Times", "Weight": "Bold", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-168, -218, 1000, 935], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 676, "XHeight": 461, "Ascender": 683, "Descender": -217, "StdHW": 44, "StdVW": 139}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [250, 333, 555, 500, 500, 1000, 833, 333, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 930, 722, 667, 722, 722, 667, 611, 778, 778, 389, 500, 778, 667, 944, 722, 778, 611, 778, 722, 556, 667, 722, 722, 1000, 722, 722, 667, 333, 278, 333, 581, 500, 333, 500, 556, 444, 556, 444, 333, 500, 556, 278, 333, 556, 278, 833, 556, 500, 556, 556, 444, 389, 333, 556, 500, 722, 500, 500, 444, 394, 220, 394, 520, 333, 500, 500, 167, 500, 500, 500, 500, 278, 500, 500, 333, 333, 556, 556, 500, 500, 500, 250, 540, 350, 333, 500, 500, 500, 1000, 1000, 500, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 1000, 300, 667, 778, 1000, 330, 722, 278, 278, 500, 722, 556, 389, 444, 500, 556, 444, 722, 570, 722, 722, 500, 722, 500, 389, 444, 722, 722, 500, 722, 556, 667, 722, 250, 747, 667, 444, 500, 722, 278, 500, 667, 722, 500, 667, 389, 389, 278, 494, 722, 778, 556, 500, 722, 444, 444, 667, 611, 778, 722, 556, 672, 722, 556, 300, 778, 722, 722, 570, 556, 667, 494, 500, 722, 278, 667, 500, 444, 444, 556, 556, 722, 389, 570, 220, 747, 778, 389, 600, 667, 444, 500, 667, 667, 549, 722, 722, 278, 416, 444, 722, 722, 722, 444, 444, 278, 778, 500, 500, 389, 278, 778, 722, 612, 556, 300, 778, 556, 278, 500, 667, 556, 750, 556, 394, 778, 667, 1000, 444, 389, 389, 667, 750, 549, 500, 556, 722, 667, 444, 500, 750, 556, 556, 778, 400, 500, 722, 556, 549, 722, 444, 722, 500, 722, 667, 722, 722, 722, 778, 444, 667, 389, 556, 570, 389, 556, 333, 570, 500, 556, 549, 500, 500, 444, 556, 300, 278, 500]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 45874 56899", "FontName": "Times-BoldItalic", "FullName": "Times Bold Italic", "FamilyName": "Times", "Weight": "Bold", "ItalicAngle": -15, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-200, -218, 996, 921], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 669, "XHeight": 462, "Ascender": 683, "Descender": -217, "StdHW": 42, "StdVW": 121}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [250, 389, 555, 500, 500, 833, 778, 333, 333, 333, 500, 570, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 570, 570, 570, 500, 832, 667, 667, 667, 722, 667, 667, 722, 778, 389, 500, 667, 611, 889, 722, 722, 611, 722, 667, 556, 611, 722, 667, 889, 667, 611, 611, 333, 278, 333, 570, 500, 333, 500, 500, 444, 500, 444, 333, 500, 556, 278, 278, 500, 278, 778, 556, 500, 500, 500, 389, 389, 278, 556, 444, 667, 500, 444, 389, 348, 220, 348, 570, 389, 500, 500, 167, 500, 500, 500, 500, 278, 500, 500, 333, 333, 556, 556, 500, 500, 500, 250, 500, 350, 333, 500, 500, 500, 1000, 1000, 500, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 944, 266, 611, 722, 944, 300, 722, 278, 278, 500, 722, 500, 389, 444, 500, 556, 444, 611, 570, 611, 667, 500, 722, 444, 389, 444, 722, 722, 500, 722, 556, 667, 722, 250, 747, 667, 444, 500, 722, 278, 500, 611, 667, 500, 667, 389, 389, 278, 494, 667, 722, 556, 500, 667, 389, 444, 611, 611, 722, 667, 556, 608, 722, 556, 300, 722, 667, 667, 570, 556, 611, 494, 444, 722, 278, 667, 500, 444, 444, 556, 556, 722, 389, 570, 220, 747, 722, 389, 600, 667, 389, 500, 611, 611, 549, 722, 667, 278, 366, 444, 722, 667, 667, 444, 389, 278, 722, 500, 500, 389, 278, 722, 722, 612, 500, 300, 722, 576, 278, 500, 667, 500, 750, 556, 382, 667, 611, 1000, 444, 389, 389, 611, 750, 549, 500, 556, 722, 667, 444, 500, 750, 556, 556, 722, 400, 500, 667, 556, 549, 722, 389, 722, 500, 667, 611, 667, 667, 667, 722, 389, 667, 389, 500, 606, 389, 556, 278, 606, 500, 556, 549, 500, 500, 389, 556, 300, 278, 500]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 47727 58752", "FontName": "Times-Italic", "FullName": "Times Italic", "FamilyName": "Times", "Weight": "Medium", "ItalicAngle": -15.5, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-169, -217, 1010, 883], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 653, "XHeight": 441, "Ascender": 683, "Descender": -217, "StdHW": 32, "StdVW": 76}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [250, 333, 420, 500, 500, 833, 778, 333, 333, 333, 500, 675, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 333, 333, 675, 675, 675, 500, 920, 611, 611, 667, 722, 611, 611, 722, 722, 333, 444, 667, 556, 833, 667, 722, 611, 722, 611, 500, 556, 722, 611, 833, 611, 556, 556, 389, 278, 389, 422, 500, 333, 500, 500, 444, 500, 444, 278, 500, 500, 278, 278, 444, 278, 722, 500, 500, 500, 500, 389, 389, 278, 500, 444, 667, 444, 444, 389, 400, 275, 400, 541, 389, 500, 500, 167, 500, 500, 500, 500, 214, 556, 500, 333, 333, 500, 500, 500, 500, 500, 250, 523, 350, 333, 556, 556, 500, 889, 1000, 500, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 889, 889, 276, 556, 722, 944, 310, 667, 278, 278, 500, 667, 500, 333, 444, 500, 500, 444, 556, 675, 556, 611, 500, 722, 444, 389, 444, 722, 722, 500, 722, 500, 611, 722, 250, 760, 611, 444, 500, 667, 278, 500, 556, 667, 500, 611, 389, 389, 278, 471, 611, 722, 500, 500, 611, 389, 444, 556, 611, 722, 611, 500, 544, 722, 500, 300, 722, 611, 611, 675, 500, 556, 476, 444, 667, 278, 611, 500, 444, 444, 500, 500, 667, 333, 675, 275, 760, 722, 333, 600, 611, 389, 500, 556, 556, 549, 722, 667, 278, 300, 444, 722, 611, 611, 444, 389, 278, 722, 500, 500, 389, 278, 722, 722, 612, 500, 300, 722, 500, 278, 500, 611, 500, 750, 500, 300, 667, 556, 980, 444, 333, 333, 611, 750, 549, 500, 500, 722, 611, 444, 500, 750, 500, 500, 722, 400, 500, 667, 500, 453, 722, 389, 667, 500, 611, 556, 611, 611, 611, 722, 389, 611, 333, 444, 675, 333, 500, 278, 675, 500, 500, 549, 500, 500, 389, 500, 300, 278, 500]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 43909 54934", "FontName": "Times-Roman", "FullName": "Times Roman", "FamilyName": "Times", "Weight": "Roman", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "ExtendedRoman", "FontBBox": [-168, -218, 1000, 898], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1989, 1990, 1993, 1997 Adobe Systems Incorporated. All Rights Reserved.Times is a trademark of Linotype-Hell AG and/or its subsidiaries.", "EncodingScheme": "AdobeStandardEncoding", "CapHeight": 662, "XHeight": 450, "Ascender": 683, "Descender": -217, "StdHW": 28, "StdVW": 84}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 177, 178, 179, 180, 182, 183, 184, 185, 186, 187, 188, 189, 191, 193, 194, 195, 196, 197, 198, 199, 200, 202, 203, 205, 206, 207, 208, 225, 227, 232, 233, 234, 235, 241, 245, 248, 249, 250, 251, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1], "widths": [250, 333, 408, 500, 500, 833, 778, 333, 333, 333, 500, 564, 250, 333, 250, 278, 500, 500, 500, 500, 500, 500, 500, 500, 500, 500, 278, 278, 564, 564, 564, 444, 921, 722, 667, 667, 722, 611, 556, 722, 722, 333, 389, 722, 611, 889, 722, 722, 556, 722, 667, 556, 611, 722, 722, 944, 722, 722, 611, 333, 278, 333, 469, 500, 333, 444, 500, 444, 500, 444, 333, 500, 500, 278, 278, 500, 278, 778, 500, 500, 500, 500, 333, 389, 278, 500, 500, 722, 500, 500, 444, 480, 200, 480, 541, 333, 500, 500, 167, 500, 500, 500, 500, 180, 444, 500, 333, 333, 556, 556, 500, 500, 500, 250, 453, 350, 333, 444, 444, 500, 1000, 1000, 444, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 333, 1000, 889, 276, 611, 722, 889, 310, 667, 278, 278, 500, 722, 500, 333, 444, 444, 500, 444, 722, 564, 722, 722, 444, 722, 500, 389, 444, 722, 722, 444, 722, 500, 611, 722, 250, 760, 611, 444, 444, 722, 278, 444, 611, 667, 444, 611, 389, 389, 278, 471, 667, 722, 500, 444, 722, 333, 444, 611, 556, 722, 667, 556, 588, 722, 500, 300, 722, 722, 722, 564, 500, 611, 476, 500, 722, 278, 611, 444, 444, 444, 500, 500, 722, 333, 564, 200, 760, 722, 333, 600, 611, 333, 500, 611, 611, 549, 722, 667, 278, 326, 444, 722, 722, 722, 444, 444, 278, 722, 500, 444, 389, 278, 722, 722, 612, 500, 300, 722, 500, 278, 500, 611, 500, 750, 556, 344, 722, 611, 980, 444, 333, 333, 611, 750, 549, 500, 500, 722, 611, 444, 500, 750, 556, 556, 722, 400, 500, 667, 500, 453, 722, 333, 722, 500, 667, 611, 722, 722, 722, 722, 444, 611, 333, 500, 564, 333, 500, 278, 564, 500, 500, 549, 500, 500, 444, 500, 300, 278, 500]}}
|
||||
@@ -0,0 +1 @@
|
||||
{"descriptor": {"StartFontMetrics": 4.1, "Comment": "VMusage 45775 55535", "FontName": "ZapfDingbats", "FullName": "ITC Zapf Dingbats", "FamilyName": "ZapfDingbats", "Weight": "Medium", "ItalicAngle": 0, "IsFixedPitch": false, "CharacterSet": "Special", "FontBBox": [-1, -143, 981, 820], "UnderlinePosition": -100, "UnderlineThickness": 50, "Version": 2.0, "Notice": "Copyright (c) 1985, 1987, 1988, 1989, 1997 Adobe Systems Incorporated. All Rights Reserved.ITC Zapf Dingbats is a registered trademark of International Typeface Corporation.", "EncodingScheme": "FontSpecific", "StdHW": 28, "StdVW": 90}, "metrics": {"codes": [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, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, 92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, 104, 105, 106, 107, 108, 109, 110, 111, 112, 113, 114, 115, 116, 117, 118, 119, 120, 121, 122, 123, 124, 125, 126, 128, 129, 130, 131, 132, 133, 134, 135, 136, 137, 138, 139, 140, 141, 161, 162, 163, 164, 165, 166, 167, 168, 169, 170, 171, 172, 173, 174, 175, 176, 177, 178, 179, 180, 181, 182, 183, 184, 185, 186, 187, 188, 189, 190, 191, 192, 193, 194, 195, 196, 197, 198, 199, 200, 201, 202, 203, 204, 205, 206, 207, 208, 209, 210, 211, 212, 213, 214, 215, 216, 217, 218, 219, 220, 221, 222, 223, 224, 225, 226, 227, 228, 229, 230, 231, 232, 233, 234, 235, 236, 237, 238, 239, 241, 242, 243, 244, 245, 246, 247, 248, 249, 250, 251, 252, 253, 254], "widths": [278, 974, 961, 974, 980, 719, 789, 790, 791, 690, 960, 939, 549, 855, 911, 933, 911, 945, 974, 755, 846, 762, 761, 571, 677, 763, 760, 759, 754, 494, 552, 537, 577, 692, 786, 788, 788, 790, 793, 794, 816, 823, 789, 841, 823, 833, 816, 831, 923, 744, 723, 749, 790, 792, 695, 776, 768, 792, 759, 707, 708, 682, 701, 826, 815, 789, 789, 707, 687, 696, 689, 786, 787, 713, 791, 785, 791, 873, 761, 762, 762, 759, 759, 892, 892, 788, 784, 438, 138, 277, 415, 392, 392, 668, 668, 390, 390, 317, 317, 276, 276, 509, 509, 410, 410, 234, 234, 334, 334, 732, 544, 544, 910, 667, 760, 760, 776, 595, 694, 626, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 788, 894, 838, 1016, 458, 748, 924, 748, 918, 927, 928, 928, 834, 873, 828, 924, 924, 917, 930, 931, 463, 883, 836, 836, 867, 867, 696, 696, 874, 874, 760, 946, 771, 865, 771, 888, 967, 888, 831, 873, 927, 970, 918]}}
|
||||
@@ -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")
|
||||
@@ -0,0 +1,65 @@
|
||||
from typing import Any, Dict, Union
|
||||
|
||||
from .base import PDFFont
|
||||
from . import standard14
|
||||
|
||||
|
||||
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],
|
||||
encoding: Union[str, Dict[str, Any], None],
|
||||
to_unicode: Any,
|
||||
) -> None:
|
||||
PDFFont.__init__(
|
||||
self,
|
||||
subtype,
|
||||
base_font=base_font,
|
||||
widths=widths,
|
||||
font_descriptor=font_descriptor,
|
||||
encoding=encoding,
|
||||
to_unicode=to_unicode,
|
||||
)
|
||||
self.base_font = base_font
|
||||
self.widths = widths
|
||||
self.font_descriptor = font_descriptor
|
||||
self.encoding = encoding
|
||||
self.to_unicode = to_unicode
|
||||
|
||||
@classmethod
|
||||
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,
|
||||
encoding=encoding,
|
||||
to_unicode=to_unicode,
|
||||
)
|
||||
else:
|
||||
first_char = int(d.get("FirstChar", 0))
|
||||
last_char = int(d.get("FirstChar", 255))
|
||||
if d.get("Widths"):
|
||||
widths_array = map(int, d["Widths"])
|
||||
else:
|
||||
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,
|
||||
encoding=encoding,
|
||||
to_unicode=to_unicode,
|
||||
)
|
||||
@@ -0,0 +1,31 @@
|
||||
import json
|
||||
from pathlib import Path
|
||||
from typing import Any, Dict, List, NamedTuple, Optional
|
||||
|
||||
CORE_14_FOLDER = Path(__file__).parent / "core14"
|
||||
ALL_FILES = {fpath.stem: fpath for fpath in CORE_14_FOLDER.iterdir()}
|
||||
|
||||
|
||||
class StandardFontMetric(NamedTuple):
|
||||
descriptor: Dict[str, Any]
|
||||
char_codes: List[int]
|
||||
widths: List[int]
|
||||
|
||||
|
||||
def get_ifexists(font_name: str) -> Optional[StandardFontMetric]:
|
||||
"""checks if have the font's parsed afm file, and return it's metadata if we do
|
||||
|
||||
Args:
|
||||
font_name (str)
|
||||
|
||||
Returns:
|
||||
Optional[StandardFontMetric]
|
||||
"""
|
||||
if font_name in ALL_FILES:
|
||||
data = json.loads(ALL_FILES[font_name].read_text())
|
||||
return StandardFontMetric(
|
||||
descriptor=data["descriptor"],
|
||||
char_codes=data["metrics"]["codes"],
|
||||
widths=data["metrics"]["widths"],
|
||||
)
|
||||
return None
|
||||
@@ -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)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,32 @@
|
||||
import traceback
|
||||
import warnings
|
||||
from typing import List
|
||||
|
||||
|
||||
class PDFMajorWarning(Warning):
|
||||
def __init__(self, issue_name: str, additional_info: str) -> None:
|
||||
self.issue_name = issue_name
|
||||
self.additional_info = additional_info
|
||||
super().__init__(f"health issue detected: {issue_name}: {additional_info}")
|
||||
|
||||
|
||||
class PDFHealthReport(List[PDFMajorWarning]):
|
||||
"""a list of all issues that occured during the parsing of the document"""
|
||||
|
||||
def write(self, issue_name: str, additional_info: str):
|
||||
log = PDFMajorWarning(issue_name, additional_info)
|
||||
warnings.warn(log)
|
||||
self.append(log)
|
||||
|
||||
def write_error(self, err: Exception):
|
||||
tb = traceback.TracebackException.from_exception(err)
|
||||
self.write(err.__class__.__name__, "\n".join(tb.format()))
|
||||
|
||||
def __repr__(self) -> str:
|
||||
out = "<---HEALTH REPORT--->"
|
||||
for log in self:
|
||||
out += "\n"
|
||||
out += f" > {log.issue_name}"
|
||||
out += f" |-> {log.additional_info}"
|
||||
out += "</---HEALTH REPORT--->"
|
||||
return out
|
||||
@@ -1,46 +0,0 @@
|
||||
from pdfmajor.parser.PDFPage import PDFPage
|
||||
from pdfmajor.parser.PDFStream import list_value
|
||||
|
||||
from .commands import PDFStateStack
|
||||
from .commands import process_command_stream, prep_state
|
||||
|
||||
class PageInterpreter:
|
||||
|
||||
def __init__(self, page: PDFPage, page_num: int, font_cache: dict = None, ignore_bad_chars = False):
|
||||
(x0, y0, x1, y1) = page.mediabox
|
||||
if page.rotate == 90:
|
||||
ctm = [0, -1, 1, 0, -y0, x1]
|
||||
elif page.rotate == 180:
|
||||
ctm = [-1, 0, 0, -1, x1, y1]
|
||||
elif page.rotate == 270:
|
||||
ctm = [0, 1, -1, 0, y1, -x0]
|
||||
else:
|
||||
ctm = [1, 0, 0, 1, -x0, -y0]
|
||||
|
||||
# Locals
|
||||
self.font_cache = font_cache if font_cache is not None else {}
|
||||
self.page = page
|
||||
self.page_num = page_num
|
||||
self.height = y1-y0
|
||||
self.width = x1-x0
|
||||
|
||||
# Init State
|
||||
self.state: PDFStateStack = prep_state(
|
||||
PDFStateStack(),
|
||||
ctm=ctm,
|
||||
resources=page.resources,
|
||||
font_cache=self.font_cache,
|
||||
ignore_bad_chars=ignore_bad_chars
|
||||
)
|
||||
|
||||
|
||||
def __iter__(self):
|
||||
for item in process_command_stream(
|
||||
streams=list_value(self.page.contents),
|
||||
font_cache=self.font_cache,
|
||||
state=self.state
|
||||
):
|
||||
yield item
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Page:{self.page_num} width={self.width} height={self.height}/>"
|
||||
@@ -1,72 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from ..parser.PDFPage import PDFPage
|
||||
from ..utils import set_log_level, get_logger, logging
|
||||
from .commands.state import PDFStateStack, PDFColorSpace, PREDEFINED_COLORSPACE
|
||||
from .commands import PDFCommands
|
||||
from .commands import LTTextBlock, LTCharBlock, LTChar
|
||||
from .commands import LTCurve, LTLine, LTHorizontalLine, LTVerticalLine, LTRect
|
||||
from .commands import LTImage
|
||||
from .commands import LTXObject
|
||||
from .PageInterpreter import PageInterpreter
|
||||
|
||||
log = get_logger(__name__)
|
||||
|
||||
class PDFInterpreter:
|
||||
class AccessError(Exception): pass
|
||||
|
||||
def __init__(self,
|
||||
input_file_path: str,
|
||||
maxpages: int = 0,
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
password: str = None,
|
||||
pagenos: List[int] = None,
|
||||
preload: bool = False,
|
||||
ignore_bad_chars: bool = False,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
self.input_file_path = input_file_path
|
||||
self.maxpages = maxpages
|
||||
self.caching = caching
|
||||
self.check_extractable = check_extractable
|
||||
self.password = password
|
||||
self.pagenos = pagenos
|
||||
self.ignore_bad_chars = ignore_bad_chars
|
||||
self.debug_level = debug_level
|
||||
self.__pages = []
|
||||
if preload:
|
||||
for _ in self.__load_pages():
|
||||
pass
|
||||
|
||||
def __load_pages(self):
|
||||
set_log_level(self.debug_level)
|
||||
log.info("Opening file...")
|
||||
with open(self.input_file_path, 'rb') as input_file:
|
||||
font_cache = {}
|
||||
log.info("Parsing file...")
|
||||
pages = PDFPage.get_pages(
|
||||
input_file,
|
||||
pagenos=self.pagenos,
|
||||
maxpages=self.maxpages,
|
||||
password=self.password,
|
||||
caching=self.caching,
|
||||
check_extractable=self.check_extractable
|
||||
)
|
||||
for page_num, page in enumerate(pages):
|
||||
self.__pages.append(PageInterpreter(page, page_num, font_cache, ignore_bad_chars=self.ignore_bad_chars))
|
||||
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")
|
||||
|
||||
def __iter__(self):
|
||||
if len(self.__pages) > 0:
|
||||
set_log_level(self.debug_level)
|
||||
for page in self.__pages:
|
||||
yield page
|
||||
set_log_level(logging.WARNING)
|
||||
else:
|
||||
for page in self.__load_pages():
|
||||
yield page
|
||||
@@ -1,31 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
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
|
||||
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 = {}
|
||||
|
||||
@classmethod
|
||||
def __add(cls, cmd_name: str, cmd: callable):
|
||||
if not (cmd_name in cls.commands.keys()):
|
||||
cls.commands[cmd_name] = cmd
|
||||
return cmd
|
||||
raise PDFCommandsRepeatedCommand(cmd_name)
|
||||
|
||||
@classmethod
|
||||
def add(cls, *cmd_names: List[str]):
|
||||
def wrap(cmd: callable):
|
||||
for cmd_name in cmd_names:
|
||||
cls.__add(cmd_name, cmd)
|
||||
return cmd
|
||||
return wrap
|
||||
|
||||
|
||||
@@ -1,85 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from pdfmajor.parser.PDFContentParser import PDFContentParser, PDFStream
|
||||
from pdfmajor.parser.PSStackParser import PSKeyword, keyword_name
|
||||
from pdfmajor.utils import get_logger
|
||||
|
||||
from .commands import PDFCommands
|
||||
from .state import PDFStateStack, PDFGraphicState, PDFTextState
|
||||
from .state.PDFGraphicState import PDFColor, PDFColorSpace, PREDEFINED_COLORSPACE
|
||||
from .state import PDFFont, get_font
|
||||
from .state import LTTextBlock, LTCharBlock, LTChar
|
||||
from .state import LTCurve, LTLine, LTHorizontalLine, LTVerticalLine, LTRect
|
||||
from .state import LTImage
|
||||
from .state import LTXObject
|
||||
from .state import LTItem, LTComponent, LTContainer
|
||||
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 = {}
|
||||
parser = PDFContentParser(streams)
|
||||
# from .cmd_record import CmdRecord
|
||||
# history = CmdRecord()
|
||||
for obj in parser:
|
||||
if isinstance(obj, PSKeyword):
|
||||
name = keyword_name(obj)
|
||||
method = name.replace('*', '_a').replace('"', '_w').replace("'", '_q')
|
||||
func = None
|
||||
args = []
|
||||
if method == "Do":
|
||||
pass
|
||||
if method in PDFCommands.commands.keys():
|
||||
func = PDFCommands.commands.get(method)
|
||||
nargs = func.__code__.co_argcount-1
|
||||
if nargs:
|
||||
args = state.pop(nargs)
|
||||
if len(args) == nargs:
|
||||
func(state, *args)
|
||||
else:
|
||||
raise CommandProcessorError(f"Invalid Number of Args provided {method}")
|
||||
else:
|
||||
func(state)
|
||||
else:
|
||||
log.debug('Unknown operator: %r (i.e. %r)' % (name, method))
|
||||
# history.write(name,
|
||||
# None if func is None else func.__name__
|
||||
# , args)
|
||||
else:
|
||||
state.argstack.append(obj)
|
||||
# history.write('arg', None, obj)
|
||||
|
||||
for complete_item in state.complete_layout_items:
|
||||
if isinstance(complete_item, LTXObject):
|
||||
xobj_state = prep_state(
|
||||
state=PDFStateStack(),
|
||||
ctm=complete_item.t_matrix,
|
||||
resources=complete_item.resources,
|
||||
font_cache=font_cache
|
||||
)
|
||||
xobj_state.graphics = state.graphics.copy()
|
||||
for item in process_command_stream(
|
||||
[complete_item.stream],
|
||||
font_cache=font_cache,
|
||||
state=xobj_state
|
||||
):
|
||||
complete_item.add(item)
|
||||
yield complete_item
|
||||
state.complete_layout_items = []
|
||||
|
||||
def prep_state(state: PDFStateStack, ctm: tuple, resources: dict, font_cache: dict, ignore_bad_chars: bool = False) -> PDFStateStack:
|
||||
state.t_matrix = ctm
|
||||
state.resources = resources
|
||||
state.text.ignore_bad_chars = ignore_bad_chars
|
||||
|
||||
# set some global states.
|
||||
state.graphics.ncolspace = state.graphics.scolspace = None
|
||||
if state.colorspace_map:
|
||||
col_space = next(iter(state.colorspace_map.values()))
|
||||
state.graphics.ncolspace = state.graphics.scolspace = col_space
|
||||
init_resources(state, font_cache)
|
||||
return state
|
||||
@@ -1,9 +0,0 @@
|
||||
|
||||
class CmdRecord:
|
||||
def __init__(self, file_name: str = "./cmd_record"):
|
||||
self.file = open(file_name, 'w')
|
||||
self.file.write("c_name,func_name,args\n")
|
||||
def write(self, c_name, func_name, args):
|
||||
self.file.write(f"{c_name},{func_name},{args}\n")
|
||||
def close(self):
|
||||
self.file.close()
|
||||
@@ -1,516 +0,0 @@
|
||||
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 .state import PDFStateStack, PDFGraphicState, LTTextBlock
|
||||
from .state.Curves import CurveMethod, CurvePath, CurvePoint
|
||||
# from .state.PDFItem import PDFImage, PDFShape, PDFText, PDFXObject
|
||||
from .state import make_char_block, make_curve, make_image, make_xobject
|
||||
|
||||
log = get_logger('commands')
|
||||
|
||||
# No Support
|
||||
# @PDFCommands.add('W','W_a', 'sh', 'ET', 'BX', 'EX' ,'BI', 'ID', 'gs')
|
||||
# def do_no_support(stack: PDFStateStack) -> PDFStateStack:
|
||||
# # log.debug("Unsupported command")
|
||||
# return stack
|
||||
|
||||
# marked content operators
|
||||
# @PDFCommands.add('MP')
|
||||
# def do_MP(stack: PDFStateStack, tag) -> PDFStateStack:
|
||||
# log.debug(f"Unsupported command - do_tag {[tag]}")
|
||||
# # self.device.do_tag(tag)
|
||||
# return stack
|
||||
|
||||
# @PDFCommands.add('DP')
|
||||
# def do_DP(stack: PDFStateStack, tag, props=None) -> PDFStateStack:
|
||||
# log.debug(f"Unsupported command - do_tag {[tag.name, type(tag), props]}")
|
||||
# # self.device.do_tag(tag)
|
||||
# return stack
|
||||
|
||||
# @PDFCommands.add('BMC')
|
||||
# def do_BMC(stack: PDFStateStack, tag) -> PDFStateStack:
|
||||
# log.debug(f"Unsupported command - begin_tag {[tag.name, type(tag)]}")
|
||||
# # self.device.begin_tag(tag)
|
||||
# return stack
|
||||
|
||||
# @PDFCommands.add('BDC')
|
||||
# def do_BDC(stack: PDFStateStack, tag, props=None) -> PDFStateStack:
|
||||
# log.debug(f"Unsupported command - begin_tag {[tag.name, type(tag), props]}")
|
||||
# # self.device.begin_tag(tag)
|
||||
# return stack
|
||||
|
||||
# @PDFCommands.add('EMC')
|
||||
# def do_EMC(stack: PDFStateStack) -> PDFStateStack:
|
||||
# # self.device.end_tag(tag)
|
||||
# log.debug("Unsupported command - end_tag")
|
||||
# return stack
|
||||
|
||||
@PDFCommands.add('q')
|
||||
def save_state(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.gstack.append([
|
||||
stack.t_matrix,
|
||||
stack.text.copy(),
|
||||
stack.graphics.copy()
|
||||
])
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('Q')
|
||||
def restore_state(stack: PDFStateStack) -> PDFStateStack:
|
||||
if len(stack.gstack) > 0:
|
||||
stack.t_matrix, stack.text, stack.graphicstate = stack.gstack.pop()
|
||||
return stack
|
||||
|
||||
# concat-matrix
|
||||
@PDFCommands.add('cm')
|
||||
def concat_transition_matrix(stack: PDFStateStack, a1, b1, c1, d1, e1, f1) -> PDFStateStack:
|
||||
stack.t_matrix = mult_matrix((a1, b1, c1, d1, e1, f1), stack.t_matrix)
|
||||
return stack
|
||||
|
||||
# setlinewidth
|
||||
@PDFCommands.add('w')
|
||||
def set_line_width(stack: PDFStateStack, linewidth) -> PDFStateStack:
|
||||
stack.graphics.linewidth = linewidth
|
||||
return stack
|
||||
|
||||
# setlinecap
|
||||
@PDFCommands.add('J')
|
||||
def set_linecap(stack: PDFStateStack, linecap) -> PDFStateStack:
|
||||
stack.graphics.linecap = linecap
|
||||
return stack
|
||||
|
||||
# setlinejoin
|
||||
@PDFCommands.add('j')
|
||||
def set_linejoin(stack: PDFStateStack, linejoin) -> PDFStateStack:
|
||||
stack.graphics.linejoin = linejoin
|
||||
return stack
|
||||
|
||||
# setmiterlimit
|
||||
@PDFCommands.add('M')
|
||||
def set_miterlimit(stack: PDFStateStack, miterlimit) -> PDFStateStack:
|
||||
stack.graphics.miterlimit = miterlimit
|
||||
return stack
|
||||
|
||||
# setdash
|
||||
@PDFCommands.add('d')
|
||||
def set_dash(stack: PDFStateStack, dash, phase) -> PDFStateStack:
|
||||
stack.graphics.dash = (dash, phase)
|
||||
return stack
|
||||
|
||||
# setintent
|
||||
@PDFCommands.add('ri')
|
||||
def set_intent(stack: PDFStateStack, intent) -> PDFStateStack:
|
||||
stack.graphics.intent = intent
|
||||
return stack
|
||||
|
||||
# setflatness
|
||||
@PDFCommands.add('i')
|
||||
def set_flatness(stack: PDFStateStack, flatness) -> PDFStateStack:
|
||||
stack.graphics.flatness = flatness
|
||||
return stack
|
||||
|
||||
# moveto
|
||||
@PDFCommands.add('m')
|
||||
def curve_moveto(stack: PDFStateStack, x: float, y: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.MOVE_TO,
|
||||
CurvePoint(stack.t_matrix, x, y)
|
||||
))
|
||||
return stack
|
||||
|
||||
# lineto
|
||||
@PDFCommands.add('l')
|
||||
def curve_lineto(stack: PDFStateStack, x: float, y: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.LINE_TO,
|
||||
CurvePoint(stack.t_matrix, x, y)
|
||||
))
|
||||
return stack
|
||||
|
||||
# curveto
|
||||
@PDFCommands.add('c')
|
||||
def curve_curveto(stack: PDFStateStack,
|
||||
x1: float, y1: float,
|
||||
x2: float, y2: float,
|
||||
x3: float, y3: float ) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CURVE_BOTH_TO,
|
||||
CurvePoint(stack.t_matrix, x1, y1),
|
||||
CurvePoint(stack.t_matrix, x2, y2),
|
||||
CurvePoint(stack.t_matrix, x3, y3),
|
||||
))
|
||||
return stack
|
||||
|
||||
# urveto
|
||||
@PDFCommands.add('v')
|
||||
def curve_urveto(stack: PDFStateStack,
|
||||
x2: float, y2: float,
|
||||
x3: float, y3: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CURVE_NEXT_TO,
|
||||
CurvePoint(stack.t_matrix, x2, y2),
|
||||
CurvePoint(stack.t_matrix, x3, y3),
|
||||
))
|
||||
return stack
|
||||
|
||||
# rveto
|
||||
@PDFCommands.add('y')
|
||||
def curve_rveto(stack: PDFStateStack,
|
||||
x1: float, y1: float,
|
||||
x3: float, y3: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CURVE_FIRST_TO,
|
||||
CurvePoint(stack.t_matrix, x1, y1),
|
||||
CurvePoint(stack.t_matrix, x3, y3)
|
||||
))
|
||||
return stack
|
||||
|
||||
# closepath
|
||||
@PDFCommands.add('h')
|
||||
def curve_close(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(CurvePath.METHOD.CLOSE_PATH))
|
||||
return stack
|
||||
|
||||
# rectangle
|
||||
@PDFCommands.add('re')
|
||||
def curve_rect(stack: PDFStateStack, x, y, w, h) -> PDFStateStack:
|
||||
stack.curvestacks.extend([
|
||||
CurvePath(CurvePath.METHOD.MOVE_TO, CurvePoint(stack.t_matrix, x, y) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(stack.t_matrix, x+w, y) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(stack.t_matrix, x+w, y+h) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(stack.t_matrix, x, y+h) ),
|
||||
CurvePath(CurvePath.METHOD.CLOSE_PATH)
|
||||
])
|
||||
return stack
|
||||
|
||||
# stroke, fill
|
||||
@PDFCommands.add('S', 'f', 'F', 'B')
|
||||
def curve_complete_path(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.complete_layout_items.append(make_curve(
|
||||
stack.t_matrix,
|
||||
stack.graphics.copy(),
|
||||
False,
|
||||
stack.curvestacks
|
||||
))
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
# sroke, fill-even-odd
|
||||
@PDFCommands.add('f_a', 'B_a')
|
||||
def curve_complete_path_evenodd(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.complete_layout_items.append(make_curve(
|
||||
stack.t_matrix,
|
||||
stack.graphics.copy(),
|
||||
True,
|
||||
stack.curvestacks
|
||||
))
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
# close-and-stroke (do_h, do_S)
|
||||
@PDFCommands.add('s', 'b')
|
||||
def curve_close_complete(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CLOSE_PATH
|
||||
))
|
||||
stack.complete_layout_items.append(make_curve(
|
||||
stack.t_matrix,
|
||||
stack.graphics.copy(),
|
||||
False,
|
||||
stack.curvestacks
|
||||
))
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
# close-fill-and-stroke-even-odd
|
||||
@PDFCommands.add('b_a')
|
||||
def curve_close_complete_evenodd(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CLOSE_PATH
|
||||
))
|
||||
stack.complete_layout_items.append(make_curve(
|
||||
stack.t_matrix,
|
||||
stack.graphics.copy(),
|
||||
True,
|
||||
stack.curvestacks
|
||||
))
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
# close-only (empty path)
|
||||
@PDFCommands.add('n')
|
||||
def curve_close_only(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
|
||||
# setcolorspace-stroking
|
||||
@PDFCommands.add('CS')
|
||||
def set_stroke_colorspace(stack: PDFStateStack, name: str) -> PDFStateStack:
|
||||
try:
|
||||
stack.graphics.scolspace = stack.colorspace_map[literal_name(name)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommandsInvalidOperation('Undefined ColorSpace: %r' % name)
|
||||
|
||||
# setcolorspace-non-strokine
|
||||
@PDFCommands.add('cs')
|
||||
def set_nonstroke_colorspace(stack: PDFStateStack, name: str) -> PDFStateStack:
|
||||
try:
|
||||
stack.graphics.ncolspace = stack.colorspace_map[literal_name(name)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommandsInvalidOperation('Undefined ColorSpace: %r' % name)
|
||||
|
||||
# setgray-stroking
|
||||
@PDFCommands.add('G')
|
||||
def set_stroke_gray(stack: PDFStateStack, gray: float) -> PDFStateStack:
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.colorspace_map['DeviceGray'],
|
||||
gray
|
||||
)
|
||||
return stack
|
||||
|
||||
# setgray-non-stroking
|
||||
@PDFCommands.add('g')
|
||||
def set_nonstroke_gray(stack: PDFStateStack, gray: float) -> PDFStateStack:
|
||||
stack.graphics.set_nostroke_color(
|
||||
stack.colorspace_map['DeviceGray'],
|
||||
gray
|
||||
)
|
||||
return stack
|
||||
|
||||
|
||||
# setrgb-stroking
|
||||
@PDFCommands.add('RG')
|
||||
def set_stroke_rgb(stack: PDFStateStack, r, g, b) -> PDFStateStack:
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.colorspace_map['DeviceRGB'],
|
||||
round(r*255),
|
||||
round(g*255),
|
||||
round(b*255)
|
||||
)
|
||||
return stack
|
||||
|
||||
# setrgb-non-stroking
|
||||
@PDFCommands.add('rg')
|
||||
def set_nonstroke_rgb(stack: PDFStateStack, r, g, b) -> PDFStateStack:
|
||||
stack.graphics.set_nostroke_color(
|
||||
stack.colorspace_map['DeviceRGB'],
|
||||
round(r*255),
|
||||
round(g*255),
|
||||
round(b*255)
|
||||
)
|
||||
return stack
|
||||
|
||||
# setcmyk-stroking
|
||||
@PDFCommands.add('K')
|
||||
def set_stroke_cmyk(stack: PDFStateStack, c, m, y, k) -> PDFStateStack:
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.colorspace_map['DeviceCMYK'],
|
||||
c, m, y, k
|
||||
)
|
||||
return stack
|
||||
|
||||
# setcmyk-non-stroking
|
||||
@PDFCommands.add('k')
|
||||
def set_nonstroke_cmyk(stack: PDFStateStack, c, m, y, k) -> PDFStateStack:
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.colorspace_map['DeviceCMYK'],
|
||||
c, m, y, k
|
||||
)
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('SCN','SC')
|
||||
def set_stroke_colorspace_custom(stack: PDFStateStack) -> PDFStateStack:
|
||||
if stack.graphics.scolspace is None:
|
||||
raise PDFCommandsInvalidOperation('No colorspace specified!')
|
||||
components = stack.pop(stack.graphics.scolspace.ncomponents)
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.graphics.scolspace,
|
||||
*components
|
||||
)
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('scn','sc')
|
||||
def set_nonstroke_colorspace_custom(stack: PDFStateStack) -> PDFStateStack:
|
||||
if stack.graphics.ncolspace is None:
|
||||
raise PDFCommandsInvalidOperation('No colorspace specified!')
|
||||
components = stack.pop(stack.graphics.ncolspace.ncomponents)
|
||||
stack.graphics.set_nostroke_color(
|
||||
stack.graphics.ncolspace,
|
||||
*components
|
||||
)
|
||||
return stack
|
||||
|
||||
# begin-text
|
||||
@PDFCommands.add('BT')
|
||||
def begin_text(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.text.matrix = MATRIX_IDENTITY
|
||||
stack.text.linematrix = [0, 0]
|
||||
if stack.current_textblock is None:
|
||||
stack.current_textblock = LTTextBlock()
|
||||
else:
|
||||
raise PDFCommandsInvalidOperation("Last TextBlock did not clear")
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('ET')
|
||||
def end_text(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.complete_layout_items.append(stack.current_textblock)
|
||||
stack.current_textblock = None
|
||||
return stack
|
||||
|
||||
# setcharspace
|
||||
@PDFCommands.add('Tc')
|
||||
def set_charspace(stack: PDFStateStack, charspace) -> PDFStateStack:
|
||||
stack.text.charspace = charspace
|
||||
return stack
|
||||
|
||||
# setwordspace
|
||||
@PDFCommands.add('Tw')
|
||||
def set_wordspace(stack: PDFStateStack, wordspace) -> PDFStateStack:
|
||||
stack.text.wordspace = wordspace
|
||||
return stack
|
||||
|
||||
# textscale
|
||||
@PDFCommands.add('Tz')
|
||||
def set_textscale(stack: PDFStateStack, scaling) -> PDFStateStack:
|
||||
stack.text.scaling = scaling
|
||||
return stack
|
||||
|
||||
# setleading
|
||||
@PDFCommands.add('TL')
|
||||
def set_text_leading(stack: PDFStateStack, leading) -> PDFStateStack:
|
||||
stack.text.leading = -leading
|
||||
return stack
|
||||
|
||||
# selectfont
|
||||
@PDFCommands.add('Tf')
|
||||
def set_font(stack: PDFStateStack, fontid, fontsize) -> PDFStateStack:
|
||||
stack.text.fontsize = fontsize
|
||||
try:
|
||||
stack.text.font = stack.fontmap[literal_name(fontid)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommandsInvalidOperation('Undefined Font id: %r' % fontid)
|
||||
|
||||
# setrendering
|
||||
@PDFCommands.add('Tr')
|
||||
def set_text_rendering(stack: PDFStateStack, render) -> PDFStateStack:
|
||||
stack.text.render = render
|
||||
return stack
|
||||
|
||||
# settextrise
|
||||
@PDFCommands.add('Ts')
|
||||
def set_textrise(stack: PDFStateStack, rise) -> PDFStateStack:
|
||||
stack.text.rise = rise
|
||||
return stack
|
||||
|
||||
# text-move
|
||||
@PDFCommands.add('Td')
|
||||
def move_text_x(stack: PDFStateStack, tx, ty) -> PDFStateStack:
|
||||
(a, b, c, d, e, f) = stack.text.matrix
|
||||
stack.text.matrix = (a, b, c, d, tx*a+ty*c+e, tx*b+ty*d+f)
|
||||
stack.text.linematrix = [0, 0]
|
||||
return stack
|
||||
|
||||
# text-move
|
||||
@PDFCommands.add('TD')
|
||||
def move_text_y(stack: PDFStateStack, tx, ty) -> PDFStateStack:
|
||||
(a, b, c, d, e, f) = stack.text.matrix
|
||||
stack.text.matrix = (a, b, c, d, tx*a+ty*c+e, tx*b+ty*d+f)
|
||||
stack.text.leading = ty
|
||||
stack.text.linematrix = [0, 0]
|
||||
return stack
|
||||
|
||||
# textmatrix
|
||||
@PDFCommands.add('Tm')
|
||||
def set_text_matrix(stack: PDFStateStack, a, b, c, d, e, f) -> PDFStateStack:
|
||||
stack.text.matrix = (a, b, c, d, e, f)
|
||||
stack.text.linematrix = [0, 0]
|
||||
return stack
|
||||
|
||||
# nextline
|
||||
@PDFCommands.add('T_a')
|
||||
def nextline(stack: PDFStateStack) -> PDFStateStack:
|
||||
(a, b, c, d, e, f) = stack.text.matrix
|
||||
stack.text.matrix = (a, b, c, d, stack.text.leading*c+e, stack.text.leading*d+f)
|
||||
stack.text.linematrix = [0, 0]
|
||||
return stack
|
||||
|
||||
# show-pos
|
||||
@PDFCommands.add('TJ')
|
||||
def add_char_blocks(stack: PDFStateStack, seq: bytearray) -> PDFStateStack:
|
||||
if stack.text.font is None:
|
||||
raise PDFCommandsInvalidOperation("No Font Specified")
|
||||
if stack.current_textblock is None:
|
||||
raise PDFCommandsInvalidOperation("No TextBlock initilized")
|
||||
stack.current_textblock.add_char_block(
|
||||
seq,
|
||||
stack.t_matrix,
|
||||
stack.text.copy(),
|
||||
stack.graphics.ncolor.copy()
|
||||
)
|
||||
return stack
|
||||
|
||||
# show
|
||||
@PDFCommands.add('Tj')
|
||||
def add_char_block(stack: PDFStateStack, b: bytes) -> PDFStateStack:
|
||||
return add_char_blocks(stack, [b])
|
||||
|
||||
# quote
|
||||
@PDFCommands.add('_q')
|
||||
def add_quoted_char_blocks(stack: PDFStateStack, b: bytes) -> PDFStateStack:
|
||||
return add_char_blocks(nextline(stack), [b])
|
||||
|
||||
# doublequote
|
||||
@PDFCommands.add('_w')
|
||||
def add_dbquoted_char_blocks(stack: PDFStateStack, wordspace, charspace, b) -> PDFStateStack:
|
||||
stack.text.wordspace = wordspace
|
||||
stack.text.charspace = charspace
|
||||
return add_char_blocks(stack, [b])
|
||||
|
||||
@PDFCommands.add('EI')
|
||||
def insert_image(stack: PDFStateStack, obj) -> PDFStateStack:
|
||||
if 'W' in obj and 'H' in obj:
|
||||
stack.complete_layout_items.append(make_image(
|
||||
obj, stack.t_matrix
|
||||
))
|
||||
return stack
|
||||
|
||||
# invoke an XObject
|
||||
@PDFCommands.add('Do')
|
||||
def insert_xobject(stack: PDFStateStack, xobjid) -> PDFStateStack:
|
||||
xobjid = literal_name(xobjid)
|
||||
try:
|
||||
xobj = PDFStream.validated_stream(stack.xobjmap[xobjid])
|
||||
except KeyError:
|
||||
raise PDFCommandsInvalidOperation('Undefined xobject id: %r' % xobjid)
|
||||
# log.info('Processing xobj: %r', xobj)
|
||||
subtype = xobj.get('Subtype')
|
||||
if subtype is LITERAL_FORM and 'BBox' in xobj:
|
||||
bbox = list_value(xobj['BBox'])
|
||||
matrix = list_value(xobj.get('Matrix', MATRIX_IDENTITY))
|
||||
# According to PDF reference 1.7 section 4.9.1, XObjects in
|
||||
# earlier PDFs (prior to v1.2) use the page's Resources entry
|
||||
# instead of having their own Resources entry.
|
||||
xobjres = xobj.get('Resources')
|
||||
resources = dict_value(xobjres) if xobjres else stack.resources.copy()
|
||||
stack.complete_layout_items.append(make_xobject(
|
||||
obj=xobj,
|
||||
bbox=bbox,
|
||||
ctm=stack.t_matrix,
|
||||
matrix=matrix,
|
||||
resources=resources
|
||||
))
|
||||
elif subtype is LITERAL_IMAGE and 'Width' in xobj and 'Height' in xobj:
|
||||
stack.complete_layout_items.append(make_image(
|
||||
xobj, stack.t_matrix
|
||||
))
|
||||
else:
|
||||
# unsupported xobject type.
|
||||
pass
|
||||
return stack
|
||||
|
||||
@@ -1,33 +0,0 @@
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
from pdfmajor.utils import apply_matrix_pt
|
||||
|
||||
class CurvePoint:
|
||||
def __init__(self, ctm: tuple, x: float, y: float):
|
||||
# old = (x,y)
|
||||
# (x, y) = apply_matrix_pt(ctm, (x, y))
|
||||
# if old != (x,y):
|
||||
# print("CurvePoint", ctm, old)
|
||||
# print(" >", x, y)
|
||||
self.x = x
|
||||
self.y = y
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<CurvePoint ({self.x}, {self.y})/>'
|
||||
|
||||
class CurveMethod(Enum):
|
||||
MOVE_TO='m'
|
||||
LINE_TO='l'
|
||||
CURVE_BOTH_TO='c'
|
||||
CURVE_NEXT_TO='v'
|
||||
CURVE_FIRST_TO='y'
|
||||
CLOSE_PATH='h'
|
||||
|
||||
class CurvePath:
|
||||
METHOD = CurveMethod
|
||||
def __init__(self, method: CurveMethod, *points: List[CurvePoint]):
|
||||
self.method = method
|
||||
self.points = points
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f'<CurvePath {self.method} path=[{",".join(map(repr, self.points))}]/>'
|
||||
@@ -1,18 +0,0 @@
|
||||
from typing import Tuple, Optional
|
||||
from .PDFColorSpace import PDFColorSpace
|
||||
|
||||
class PDFColor:
|
||||
def __init__(self, color_space: Optional[PDFColorSpace], *values: float):
|
||||
self.color_space: Optional[PDFColorSpace] = color_space
|
||||
self.values: Tuple[float, ...] = values
|
||||
|
||||
def copy(self):
|
||||
return self.__class__(
|
||||
self.color_space,
|
||||
*self.values
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"""<PDFColor space="{
|
||||
None if self.color_space is None else self.color_space.name
|
||||
}" values={self.values}/>"""
|
||||
@@ -1,27 +0,0 @@
|
||||
from typing import Dict
|
||||
from collections import OrderedDict
|
||||
|
||||
class PDFColorSpace(object):
|
||||
|
||||
def __init__(self, name: str, ncomponents: int):
|
||||
self.name: str = name
|
||||
self.ncomponents: int = ncomponents
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents)
|
||||
|
||||
|
||||
PREDEFINED_COLORSPACE: Dict[str, PDFColorSpace] = OrderedDict()
|
||||
|
||||
for (name, n) in [
|
||||
('DeviceGray', 1), # default value first
|
||||
('CalRGB', 3),
|
||||
('CalGray', 1),
|
||||
('Lab', 3),
|
||||
('DeviceRGB', 3),
|
||||
('DeviceCMYK', 4),
|
||||
('Separation', 1),
|
||||
('Indexed', 1),
|
||||
('Pattern', 1),
|
||||
]:
|
||||
PREDEFINED_COLORSPACE[name]=PDFColorSpace(name, n)
|
||||
@@ -1,54 +0,0 @@
|
||||
from .PDFColor import PDFColor, PDFColorSpace
|
||||
from .PDFColorSpace import PREDEFINED_COLORSPACE
|
||||
|
||||
class PDFGraphicState(object):
|
||||
|
||||
def __init__(self):
|
||||
self.linewidth = 0
|
||||
self.linecap = None
|
||||
self.linejoin = None
|
||||
self.miterlimit = None
|
||||
self.dash = None
|
||||
self.intent = None
|
||||
self.flatness = None
|
||||
self.scolor:PDFColor = PDFColor(None)
|
||||
self.ncolor:PDFColor = PDFColor(None)
|
||||
self.scolspace:PDFColorSpace = None
|
||||
self.ncolspace:PDFColorSpace = None
|
||||
|
||||
def set_stroke_color(self, colspace: PDFColorSpace, *values):
|
||||
if colspace is None:
|
||||
colspace = self.scolspace
|
||||
self.scolor = PDFColor(colspace, *values)
|
||||
|
||||
def set_nostroke_color(self, colspace: PDFColorSpace, *values):
|
||||
if colspace is None:
|
||||
colspace = self.ncolspace
|
||||
self.ncolor = PDFColor(colspace, *values)
|
||||
|
||||
def copy(self):
|
||||
obj = PDFGraphicState()
|
||||
obj.linewidth = self.linewidth
|
||||
obj.linecap = self.linecap
|
||||
obj.linejoin = self.linejoin
|
||||
obj.miterlimit = self.miterlimit
|
||||
obj.dash = self.dash
|
||||
obj.intent = self.intent
|
||||
obj.flatness = self.flatness
|
||||
obj.scolor = self.scolor.copy()
|
||||
obj.ncolor = self.ncolor.copy()
|
||||
obj.scolspace = self.scolspace
|
||||
obj.ncolspace = self.ncolspace
|
||||
return obj
|
||||
|
||||
def __repr__(self):
|
||||
return ('<PDFGraphicState linewidth=%r, linecap=%r, linejoin=%r, '
|
||||
' miterlimit=%r, dash=%r, intent=%r, flatness=%r, '
|
||||
' stroking color=%r, non stroking color=%r'
|
||||
'>' %
|
||||
(
|
||||
self.linewidth, self.linecap, self.linejoin,
|
||||
self.miterlimit, self.dash, self.intent, self.flatness,
|
||||
str(self.scolor), str(self.ncolor)
|
||||
)
|
||||
)
|
||||
@@ -1,6 +0,0 @@
|
||||
from pdfmajor.parser.PDFStream import PDFStream
|
||||
from ._base import PDFItem
|
||||
|
||||
class PDFImage(PDFItem):
|
||||
def __init__(self, stream: PDFStream):
|
||||
self.stream = stream
|
||||
@@ -1,12 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from ..PDFGraphicState import PDFGraphicState, PDFColorSpace
|
||||
from ..Curves import CurvePath
|
||||
|
||||
from ._base import PDFItem
|
||||
|
||||
class PDFShape(PDFItem):
|
||||
def __init__(self, gstate: PDFGraphicState, evenodd: bool, paths: List[CurvePath]):
|
||||
self.gstate = gstate
|
||||
self.evenodd = evenodd
|
||||
self.paths = paths
|
||||
@@ -1,116 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from pdfmajor.utils import mult_matrix, isnumber, apply_matrix_pt, translate_matrix
|
||||
from pdfmajor.utils import Bbox
|
||||
|
||||
from ..PDFTextState import PDFTextState
|
||||
from ..PDFGraphicState import PDFGraphicState, PDFColorSpace
|
||||
from ._base import PDFItem
|
||||
|
||||
|
||||
class Char:
|
||||
def __init__(self, char: str, bbox: Bbox):
|
||||
self.char = char
|
||||
self.bbox = bbox
|
||||
def __str__(self):
|
||||
return '"%s" %s' % (self.char, self.bbox)
|
||||
def __repr__(self):
|
||||
return f"<Char:{str(self)}/>"
|
||||
|
||||
class PDFText(PDFItem):
|
||||
def __init__(self, chars: List[Char], textstate: PDFTextState, graphicstate: PDFGraphicState):
|
||||
self.chars = chars
|
||||
self.tstate = textstate
|
||||
self.gstate = graphicstate
|
||||
|
||||
@classmethod
|
||||
def make(cls, seq: bytearray, ctm, textstate: PDFTextState, graphicstate: PDFGraphicState):
|
||||
textstate.matrix = mult_matrix(textstate.matrix, ctm)
|
||||
textstate.scaling = textstate.scaling * .01
|
||||
textstate.charspace = textstate.charspace * textstate.scaling
|
||||
textstate.wordspace = textstate.wordspace * textstate.scaling
|
||||
ncs = graphicstate.ncolor.color_space
|
||||
|
||||
if textstate.font.is_multibyte():
|
||||
textstate.wordspace = 0
|
||||
dxscale = .001 * textstate.fontsize * textstate.scaling
|
||||
|
||||
if textstate.font.is_vertical():
|
||||
return cls.__render_string_along(1,
|
||||
seq, textstate, dxscale, ncs, graphicstate
|
||||
)
|
||||
else:
|
||||
return cls.__render_string_along(0,
|
||||
seq, textstate, dxscale, ncs, graphicstate
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def __render_string_along(cls, idx: int, seq: bytearray,
|
||||
textstate: PDFTextState, dxscale: float, ncs: PDFColorSpace, graphicstate: PDFGraphicState):
|
||||
needcharspace = False
|
||||
char_meta_datas = []
|
||||
for obj in seq:
|
||||
if isnumber(obj):
|
||||
textstate.linematrix[idx] -= obj*dxscale
|
||||
needcharspace = True
|
||||
else:
|
||||
for cid in textstate.font.decode(obj):
|
||||
if needcharspace:
|
||||
textstate.linematrix[idx] += textstate.charspace
|
||||
|
||||
text = textstate.to_unichr(cid)
|
||||
assert isinstance(text, str), str(type(text))
|
||||
|
||||
matrix = translate_matrix(textstate.matrix, textstate.linematrix)
|
||||
adv, bbox = cls.__compute_char_bbox(matrix, cid, textstate)
|
||||
textstate.linematrix[idx] += adv
|
||||
|
||||
char_meta_datas.append(
|
||||
Char( text, Bbox.from_points(bbox), )
|
||||
)
|
||||
if cid == 32 and textstate.wordspace:
|
||||
textstate.linematrix[idx] += textstate.wordspace
|
||||
needcharspace = True
|
||||
|
||||
return PDFText(char_meta_datas, textstate, graphicstate)
|
||||
|
||||
@classmethod
|
||||
def __compute_char_bbox(cls, matrix, char_id: int, textstate: PDFTextState):
|
||||
font = textstate.font
|
||||
fontsize = textstate.fontsize
|
||||
rise = textstate.rise
|
||||
scaling = textstate.scaling
|
||||
|
||||
textwidth = font.char_width(char_id)
|
||||
textdisp = font.char_disp(char_id)
|
||||
adv = textwidth * fontsize * scaling
|
||||
|
||||
# compute the boundary rectangle.
|
||||
if font.is_vertical():
|
||||
# vertical
|
||||
width = font.get_width() * fontsize
|
||||
(vx, vy) = textdisp
|
||||
if vx is None:
|
||||
vx = width * 0.5
|
||||
else:
|
||||
vx = vx * fontsize * .001
|
||||
vy = (1000 - vy) * fontsize * .001
|
||||
tx = -vx
|
||||
ty = vy + rise
|
||||
bll = (tx, ty+adv)
|
||||
bur = (tx+width, ty)
|
||||
else:
|
||||
# horizontal
|
||||
height = font.get_height() * fontsize
|
||||
descent = font.get_descent() * fontsize
|
||||
ty = descent + rise
|
||||
bll = (0, ty)
|
||||
bur = (adv, ty+height)
|
||||
(x0, y0) = apply_matrix_pt(matrix, bll)
|
||||
(x1, y1) = apply_matrix_pt(matrix, bur)
|
||||
if x1 < x0:
|
||||
(x0, x1) = (x1, x0)
|
||||
if y1 < y0:
|
||||
(y0, y1) = (y1, y0)
|
||||
|
||||
return (adv, ((x0, y0), (x1, y1)))
|
||||
@@ -1,9 +0,0 @@
|
||||
from ._base import PDFItem
|
||||
|
||||
class PDFXObject(PDFItem):
|
||||
def __init__(self, xobj_strem, bbox, resources, ctm):
|
||||
self.stream = xobj_strem
|
||||
self.bbox = bbox
|
||||
self.resources = resources
|
||||
self.ctm = ctm
|
||||
self.children = []
|
||||
@@ -1,100 +0,0 @@
|
||||
from pdfmajor.utils import mult_matrix, isnumber, apply_matrix_pt, translate_matrix
|
||||
|
||||
from ..PDFTextState import PDFTextState
|
||||
from ..PDFGraphicState import PDFGraphicState, PDFColorSpace
|
||||
from .PDFItem import PDFText
|
||||
from .Char import Char, Bbox
|
||||
|
||||
class TextDecoder:
|
||||
|
||||
@classmethod
|
||||
def make_pdftext(cls, seq: bytearray, ctm, textstate: PDFTextState, graphicstate: PDFGraphicState) -> PDFText:
|
||||
textstate.matrix = mult_matrix(textstate.matrix, ctm)
|
||||
textstate.scaling = textstate.scaling * .01
|
||||
textstate.charspace = textstate.charspace * textstate.scaling
|
||||
textstate.wordspace = textstate.wordspace * textstate.scaling
|
||||
ncs = graphicstate.ncolor.color_space
|
||||
|
||||
if textstate.font.is_multibyte():
|
||||
textstate.wordspace = 0
|
||||
dxscale = .001 * textstate.fontsize * textstate.scaling
|
||||
|
||||
if textstate.font.is_vertical():
|
||||
return cls.__render_string_along(1,
|
||||
seq, textstate, dxscale, ncs, graphicstate
|
||||
)
|
||||
else:
|
||||
return cls.__render_string_along(0,
|
||||
seq, textstate, dxscale, ncs, graphicstate
|
||||
)
|
||||
|
||||
@classmethod
|
||||
def __render_string_along(cls, idx: int, seq: bytearray,
|
||||
textstate: PDFTextState, dxscale: float, ncs: PDFColorSpace, graphicstate: PDFGraphicState) -> PDFText:
|
||||
needcharspace = False
|
||||
char_meta_datas = []
|
||||
for obj in seq:
|
||||
if isnumber(obj):
|
||||
textstate.linematrix[idx] -= obj*dxscale
|
||||
needcharspace = True
|
||||
else:
|
||||
for cid in textstate.font.decode(obj):
|
||||
if needcharspace:
|
||||
textstate.linematrix[idx] += textstate.charspace
|
||||
|
||||
text = textstate.to_unichr(cid)
|
||||
assert isinstance(text, str), str(type(text))
|
||||
|
||||
matrix = translate_matrix(textstate.matrix, textstate.linematrix)
|
||||
adv, bbox = cls.__compute_char_bbox(matrix, cid, textstate)
|
||||
textstate.linematrix[idx] += adv
|
||||
|
||||
char_meta_datas.append(
|
||||
Char( text, Bbox.from_points(bbox), )
|
||||
)
|
||||
if cid == 32 and textstate.wordspace:
|
||||
textstate.linematrix[idx] += textstate.wordspace
|
||||
needcharspace = True
|
||||
|
||||
return PDFText(char_meta_datas, textstate, graphicstate)
|
||||
|
||||
@classmethod
|
||||
def __compute_char_bbox(cls, matrix, char_id: int, textstate: PDFTextState):
|
||||
font = textstate.font
|
||||
fontsize = textstate.fontsize
|
||||
rise = textstate.rise
|
||||
scaling = textstate.scaling
|
||||
|
||||
textwidth = font.char_width(char_id)
|
||||
textdisp = font.char_disp(char_id)
|
||||
adv = textwidth * fontsize * scaling
|
||||
|
||||
# compute the boundary rectangle.
|
||||
if font.is_vertical():
|
||||
# vertical
|
||||
width = font.get_width() * fontsize
|
||||
(vx, vy) = textdisp
|
||||
if vx is None:
|
||||
vx = width * 0.5
|
||||
else:
|
||||
vx = vx * fontsize * .001
|
||||
vy = (1000 - vy) * fontsize * .001
|
||||
tx = -vx
|
||||
ty = vy + rise
|
||||
bll = (tx, ty+adv)
|
||||
bur = (tx+width, ty)
|
||||
else:
|
||||
# horizontal
|
||||
height = font.get_height() * fontsize
|
||||
descent = font.get_descent() * fontsize
|
||||
ty = descent + rise
|
||||
bll = (0, ty)
|
||||
bur = (adv, ty+height)
|
||||
(x0, y0) = apply_matrix_pt(matrix, bll)
|
||||
(x1, y1) = apply_matrix_pt(matrix, bur)
|
||||
if x1 < x0:
|
||||
(x0, x1) = (x1, x0)
|
||||
if y1 < y0:
|
||||
(y0, y1) = (y1, y0)
|
||||
|
||||
return (adv, ((x0, y0), (x1, y1)))
|
||||
@@ -1,5 +0,0 @@
|
||||
from ._base import PDFItem
|
||||
from .PDFShape import PDFShape
|
||||
from .PDFImage import PDFImage
|
||||
from .PDFText import PDFText
|
||||
from .PDFXObject import PDFXObject
|
||||
@@ -1,6 +0,0 @@
|
||||
class PDFItem:
|
||||
def __repr__(self) -> str:
|
||||
return f"""<{self.__class__.__name__} {' '.join([
|
||||
f'{name}="{val}"'
|
||||
for name, val in vars(self).items()
|
||||
])}/>"""
|
||||
@@ -1,246 +0,0 @@
|
||||
## CFFFont
|
||||
## (Format specified in Adobe Technical Note: #5176
|
||||
## "The Compact Font Format Specification")
|
||||
##
|
||||
import struct
|
||||
from io import BytesIO
|
||||
from pdfmajor.utils import nunpack
|
||||
|
||||
NIBBLES = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.', 'e', 'e-', None, '-')
|
||||
|
||||
def getdict(data):
|
||||
d = {}
|
||||
fp = BytesIO(data)
|
||||
stack = []
|
||||
while 1:
|
||||
c = fp.read(1)
|
||||
if not c:
|
||||
break
|
||||
b0 = ord(c)
|
||||
if b0 <= 21:
|
||||
d[b0] = stack
|
||||
stack = []
|
||||
continue
|
||||
if b0 == 30:
|
||||
s = ''
|
||||
loop = True
|
||||
while loop:
|
||||
b = ord(fp.read(1))
|
||||
for n in (b >> 4, b & 15):
|
||||
if n == 15:
|
||||
loop = False
|
||||
else:
|
||||
s += NIBBLES[n]
|
||||
value = float(s)
|
||||
elif 32 <= b0 and b0 <= 246:
|
||||
value = b0-139
|
||||
else:
|
||||
b1 = ord(fp.read(1))
|
||||
if 247 <= b0 and b0 <= 250:
|
||||
value = ((b0-247) << 8)+b1+108
|
||||
elif 251 <= b0 and b0 <= 254:
|
||||
value = -((b0-251) << 8)-b1-108
|
||||
else:
|
||||
b2 = ord(fp.read(1))
|
||||
if 128 <= b1:
|
||||
b1 -= 256
|
||||
if b0 == 28:
|
||||
value = b1 << 8 | b2
|
||||
else:
|
||||
value = b1 << 24 | b2 << 16 | struct.unpack('>H', fp.read(2))[0]
|
||||
stack.append(value)
|
||||
return d
|
||||
|
||||
|
||||
class CFFFont(object):
|
||||
|
||||
STANDARD_STRINGS = (
|
||||
'.notdef', 'space', 'exclam', 'quotedbl', 'numbersign',
|
||||
'dollar', 'percent', 'ampersand', 'quoteright', 'parenleft',
|
||||
'parenright', 'asterisk', 'plus', 'comma', 'hyphen', 'period',
|
||||
'slash', 'zero', 'one', 'two', 'three', 'four', 'five', 'six',
|
||||
'seven', 'eight', 'nine', 'colon', 'semicolon', 'less', 'equal',
|
||||
'greater', 'question', 'at', 'A', 'B', 'C', 'D', 'E', 'F', 'G',
|
||||
'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T',
|
||||
'U', 'V', 'W', 'X', 'Y', 'Z', 'bracketleft', 'backslash',
|
||||
'bracketright', 'asciicircum', 'underscore', 'quoteleft', 'a',
|
||||
'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n',
|
||||
'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z',
|
||||
'braceleft', 'bar', 'braceright', 'asciitilde', 'exclamdown',
|
||||
'cent', 'sterling', 'fraction', 'yen', 'florin', 'section',
|
||||
'currency', 'quotesingle', 'quotedblleft', 'guillemotleft',
|
||||
'guilsinglleft', 'guilsinglright', 'fi', 'fl', 'endash',
|
||||
'dagger', 'daggerdbl', 'periodcentered', 'paragraph', 'bullet',
|
||||
'quotesinglbase', 'quotedblbase', 'quotedblright',
|
||||
'guillemotright', 'ellipsis', 'perthousand', 'questiondown',
|
||||
'grave', 'acute', 'circumflex', 'tilde', 'macron', 'breve',
|
||||
'dotaccent', 'dieresis', 'ring', 'cedilla', 'hungarumlaut',
|
||||
'ogonek', 'caron', 'emdash', 'AE', 'ordfeminine', 'Lslash',
|
||||
'Oslash', 'OE', 'ordmasculine', 'ae', 'dotlessi', 'lslash',
|
||||
'oslash', 'oe', 'germandbls', 'onesuperior', 'logicalnot', 'mu',
|
||||
'trademark', 'Eth', 'onehalf', 'plusminus', 'Thorn',
|
||||
'onequarter', 'divide', 'brokenbar', 'degree', 'thorn',
|
||||
'threequarters', 'twosuperior', 'registered', 'minus', 'eth',
|
||||
'multiply', 'threesuperior', 'copyright', 'Aacute',
|
||||
'Acircumflex', 'Adieresis', 'Agrave', 'Aring', 'Atilde',
|
||||
'Ccedilla', 'Eacute', 'Ecircumflex', 'Edieresis', 'Egrave',
|
||||
'Iacute', 'Icircumflex', 'Idieresis', 'Igrave', 'Ntilde',
|
||||
'Oacute', 'Ocircumflex', 'Odieresis', 'Ograve', 'Otilde',
|
||||
'Scaron', 'Uacute', 'Ucircumflex', 'Udieresis', 'Ugrave',
|
||||
'Yacute', 'Ydieresis', 'Zcaron', 'aacute', 'acircumflex',
|
||||
'adieresis', 'agrave', 'aring', 'atilde', 'ccedilla', 'eacute',
|
||||
'ecircumflex', 'edieresis', 'egrave', 'iacute', 'icircumflex',
|
||||
'idieresis', 'igrave', 'ntilde', 'oacute', 'ocircumflex',
|
||||
'odieresis', 'ograve', 'otilde', 'scaron', 'uacute',
|
||||
'ucircumflex', 'udieresis', 'ugrave', 'yacute', 'ydieresis',
|
||||
'zcaron', 'exclamsmall', 'Hungarumlautsmall', 'dollaroldstyle',
|
||||
'dollarsuperior', 'ampersandsmall', 'Acutesmall',
|
||||
'parenleftsuperior', 'parenrightsuperior', 'twodotenleader',
|
||||
'onedotenleader', 'zerooldstyle', 'oneoldstyle', 'twooldstyle',
|
||||
'threeoldstyle', 'fouroldstyle', 'fiveoldstyle', 'sixoldstyle',
|
||||
'sevenoldstyle', 'eightoldstyle', 'nineoldstyle',
|
||||
'commasuperior', 'threequartersemdash', 'periodsuperior',
|
||||
'questionsmall', 'asuperior', 'bsuperior', 'centsuperior',
|
||||
'dsuperior', 'esuperior', 'isuperior', 'lsuperior', 'msuperior',
|
||||
'nsuperior', 'osuperior', 'rsuperior', 'ssuperior', 'tsuperior',
|
||||
'ff', 'ffi', 'ffl', 'parenleftinferior', 'parenrightinferior',
|
||||
'Circumflexsmall', 'hyphensuperior', 'Gravesmall', 'Asmall',
|
||||
'Bsmall', 'Csmall', 'Dsmall', 'Esmall', 'Fsmall', 'Gsmall',
|
||||
'Hsmall', 'Ismall', 'Jsmall', 'Ksmall', 'Lsmall', 'Msmall',
|
||||
'Nsmall', 'Osmall', 'Psmall', 'Qsmall', 'Rsmall', 'Ssmall',
|
||||
'Tsmall', 'Usmall', 'Vsmall', 'Wsmall', 'Xsmall', 'Ysmall',
|
||||
'Zsmall', 'colonmonetary', 'onefitted', 'rupiah', 'Tildesmall',
|
||||
'exclamdownsmall', 'centoldstyle', 'Lslashsmall', 'Scaronsmall',
|
||||
'Zcaronsmall', 'Dieresissmall', 'Brevesmall', 'Caronsmall',
|
||||
'Dotaccentsmall', 'Macronsmall', 'figuredash', 'hypheninferior',
|
||||
'Ogoneksmall', 'Ringsmall', 'Cedillasmall', 'questiondownsmall',
|
||||
'oneeighth', 'threeeighths', 'fiveeighths', 'seveneighths',
|
||||
'onethird', 'twothirds', 'zerosuperior', 'foursuperior',
|
||||
'fivesuperior', 'sixsuperior', 'sevensuperior', 'eightsuperior',
|
||||
'ninesuperior', 'zeroinferior', 'oneinferior', 'twoinferior',
|
||||
'threeinferior', 'fourinferior', 'fiveinferior', 'sixinferior',
|
||||
'seveninferior', 'eightinferior', 'nineinferior',
|
||||
'centinferior', 'dollarinferior', 'periodinferior',
|
||||
'commainferior', 'Agravesmall', 'Aacutesmall',
|
||||
'Acircumflexsmall', 'Atildesmall', 'Adieresissmall',
|
||||
'Aringsmall', 'AEsmall', 'Ccedillasmall', 'Egravesmall',
|
||||
'Eacutesmall', 'Ecircumflexsmall', 'Edieresissmall',
|
||||
'Igravesmall', 'Iacutesmall', 'Icircumflexsmall',
|
||||
'Idieresissmall', 'Ethsmall', 'Ntildesmall', 'Ogravesmall',
|
||||
'Oacutesmall', 'Ocircumflexsmall', 'Otildesmall',
|
||||
'Odieresissmall', 'OEsmall', 'Oslashsmall', 'Ugravesmall',
|
||||
'Uacutesmall', 'Ucircumflexsmall', 'Udieresissmall',
|
||||
'Yacutesmall', 'Thornsmall', 'Ydieresissmall', '001.000',
|
||||
'001.001', '001.002', '001.003', 'Black', 'Bold', 'Book',
|
||||
'Light', 'Medium', 'Regular', 'Roman', 'Semibold',
|
||||
)
|
||||
|
||||
class INDEX(object):
|
||||
|
||||
def __init__(self, fp):
|
||||
self.fp = fp
|
||||
self.offsets = []
|
||||
(count, offsize) = struct.unpack('>HB', self.fp.read(3))
|
||||
for _ in range(count+1):
|
||||
self.offsets.append(nunpack(self.fp.read(offsize)))
|
||||
self.base = self.fp.tell()-1
|
||||
self.fp.seek(self.base+self.offsets[-1])
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<INDEX: size=%d>' % len(self)
|
||||
|
||||
def __len__(self): # pylint: disable=E0303
|
||||
return len(self.offsets)-1
|
||||
|
||||
def __getitem__(self, i):
|
||||
self.fp.seek(self.base+self.offsets[i])
|
||||
return self.fp.read(self.offsets[i+1]-self.offsets[i])
|
||||
|
||||
def __iter__(self):
|
||||
return iter(self[i] for i in range(len(self)))
|
||||
|
||||
def __init__(self, name, fp):
|
||||
self.name = name
|
||||
self.fp = fp
|
||||
# Header
|
||||
(_major, _minor, hdrsize, _) = struct.unpack('BBBB', self.fp.read(4))
|
||||
self.fp.read(hdrsize-4)
|
||||
# Name INDEX
|
||||
self.name_index = self.INDEX(self.fp)
|
||||
# Top DICT INDEX
|
||||
self.dict_index = self.INDEX(self.fp)
|
||||
# String INDEX
|
||||
self.string_index = self.INDEX(self.fp)
|
||||
# Global Subr INDEX
|
||||
self.subr_index = self.INDEX(self.fp)
|
||||
# Top DICT DATA
|
||||
self.top_dict = getdict(self.dict_index[0])
|
||||
(charset_pos,) = self.top_dict.get(15, [0])
|
||||
(encoding_pos,) = self.top_dict.get(16, [0])
|
||||
(charstring_pos,) = self.top_dict.get(17, [0])
|
||||
# CharStrings
|
||||
self.fp.seek(charstring_pos)
|
||||
self.charstring = self.INDEX(self.fp)
|
||||
self.nglyphs = len(self.charstring)
|
||||
# Encodings
|
||||
self.code2gid = {}
|
||||
self.gid2code = {}
|
||||
self.fp.seek(encoding_pos)
|
||||
format = self.fp.read(1)
|
||||
if format == b'\x00':
|
||||
# Format 0
|
||||
(n,) = struct.unpack('B', self.fp.read(1))
|
||||
for (code, gid) in enumerate(struct.unpack('B'*n, self.fp.read(n))):
|
||||
self.code2gid[code] = gid
|
||||
self.gid2code[gid] = code
|
||||
elif format == b'\x01':
|
||||
# Format 1
|
||||
(n,) = struct.unpack('B', self.fp.read(1))
|
||||
code = 0
|
||||
for _ in range(n):
|
||||
(first, nleft) = struct.unpack('BB', self.fp.read(2))
|
||||
for gid in range(first, first+nleft+1):
|
||||
self.code2gid[code] = gid
|
||||
self.gid2code[gid] = code
|
||||
code += 1
|
||||
else:
|
||||
raise ValueError('unsupported encoding format: %r' % format)
|
||||
# Charsets
|
||||
self.name2gid = {}
|
||||
self.gid2name = {}
|
||||
self.fp.seek(charset_pos)
|
||||
format = self.fp.read(1)
|
||||
if format == b'\x00':
|
||||
# Format 0
|
||||
n = self.nglyphs-1
|
||||
for (gid, sid) in enumerate(struct.unpack('>'+'H'*n, self.fp.read(2*n))):
|
||||
gid += 1
|
||||
name = self.getstr(sid)
|
||||
self.name2gid[name] = gid
|
||||
self.gid2name[gid] = name
|
||||
elif format == b'\x01':
|
||||
# Format 1
|
||||
(n,) = struct.unpack('B', self.fp.read(1))
|
||||
sid = 0
|
||||
for _ in range(n):
|
||||
(first, nleft) = struct.unpack('BB', self.fp.read(2))
|
||||
for gid in range(first, first+nleft+1):
|
||||
name = self.getstr(sid)
|
||||
self.name2gid[name] = gid
|
||||
self.gid2name[gid] = name
|
||||
sid += 1
|
||||
elif format == b'\x02':
|
||||
# Format 2
|
||||
assert False, str(('Unhandled', format))
|
||||
else:
|
||||
raise ValueError('unsupported charset format: %r' % format)
|
||||
#print self.code2gid
|
||||
#print self.name2gid
|
||||
#assert 0
|
||||
return
|
||||
|
||||
def getstr(self, sid):
|
||||
if sid < len(self.STANDARD_STRINGS):
|
||||
return self.STANDARD_STRINGS[sid]
|
||||
return self.string_index[sid-len(self.STANDARD_STRINGS)]
|
||||
@@ -1,138 +0,0 @@
|
||||
# PDFFont
|
||||
from abc import abstractmethod
|
||||
from io import BytesIO
|
||||
|
||||
from pdfmajor.parser.EncodingDB import EncodingDB
|
||||
from pdfmajor.parser.PSStackParser import LIT
|
||||
from pdfmajor.parser.PSStackParser import PSLiteral
|
||||
from pdfmajor.parser.PSStackParser import literal_name
|
||||
from pdfmajor.parser.PDFStream import resolve1
|
||||
from pdfmajor.parser.PDFStream import int_value
|
||||
from pdfmajor.parser.PDFStream import num_value
|
||||
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
|
||||
##
|
||||
LITERAL_STANDARD_ENCODING = LIT('StandardEncoding')
|
||||
LITERAL_TYPE1C = LIT('Type1C')
|
||||
|
||||
|
||||
class PDFFont(object):
|
||||
|
||||
def __init__(self, descriptor, widths, default_width=None):
|
||||
self.descriptor = descriptor
|
||||
self.widths = widths
|
||||
self.fontname = resolve1(descriptor.get('FontName', 'unknown'))
|
||||
if isinstance(self.fontname, PSLiteral):
|
||||
self.fontname = literal_name(self.fontname)
|
||||
self.flags = int_value(descriptor.get('Flags', 0))
|
||||
self.ascent = num_value(descriptor.get('Ascent', 0))
|
||||
self.descent = num_value(descriptor.get('Descent', 0))
|
||||
self.italic_angle = num_value(descriptor.get('ItalicAngle', 0))
|
||||
self.default_width = default_width or num_value(descriptor.get('MissingWidth', 0))
|
||||
self.leading = num_value(descriptor.get('Leading', 0))
|
||||
self.bbox = list_value(descriptor.get('FontBBox', (0, 0, 0, 0)))
|
||||
self.hscale = self.vscale = .001
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFFont>'
|
||||
|
||||
def is_vertical(self):
|
||||
return False
|
||||
|
||||
def is_multibyte(self):
|
||||
return False
|
||||
|
||||
def decode(self, bytes):
|
||||
return bytearray(bytes) # map(ord, bytes)
|
||||
|
||||
def get_ascent(self):
|
||||
return self.ascent * self.vscale
|
||||
|
||||
def get_descent(self):
|
||||
return self.descent * self.vscale
|
||||
|
||||
def get_width(self):
|
||||
w = self.bbox[2]-self.bbox[0]
|
||||
if w == 0:
|
||||
w = -self.default_width
|
||||
return w * self.hscale
|
||||
|
||||
def get_height(self):
|
||||
h = self.bbox[3]-self.bbox[1]
|
||||
if h == 0:
|
||||
h = self.ascent - self.descent
|
||||
return h * self.vscale
|
||||
|
||||
def char_width(self, cid):
|
||||
try:
|
||||
return self.widths[cid] * self.hscale
|
||||
except KeyError:
|
||||
try:
|
||||
return self.widths[self.to_unichr(cid)] * self.hscale
|
||||
except (KeyError, PDFUnicodeNotDefined):
|
||||
return self.default_width * self.hscale
|
||||
|
||||
def char_disp(self, cid):
|
||||
return 0
|
||||
|
||||
def string_width(self, s):
|
||||
return sum(self.char_width(cid) for cid in self.decode(s))
|
||||
|
||||
@abstractmethod
|
||||
def to_unichr(self, cid):
|
||||
raise NotImplementedError
|
||||
|
||||
@property
|
||||
def font_weight(self):
|
||||
if 'FontWeight' in self.descriptor.keys():
|
||||
return self.descriptor['FontWeight']
|
||||
elif 'bold' in self.fontname.lower():
|
||||
return 'bold'
|
||||
else:
|
||||
return None
|
||||
|
||||
@property
|
||||
def is_bold(self):
|
||||
return self.font_weight == 'bold' or self.font_weight > 549
|
||||
|
||||
# PDFSimpleFont
|
||||
class PDFSimpleFont(PDFFont):
|
||||
|
||||
def __init__(self, descriptor, widths, spec):
|
||||
# Font encoding is specified either by a name of
|
||||
# built-in encoding or a dictionary that describes
|
||||
# the differences.
|
||||
if 'Encoding' in spec:
|
||||
encoding = resolve1(spec['Encoding'])
|
||||
else:
|
||||
encoding = LITERAL_STANDARD_ENCODING
|
||||
if isinstance(encoding, dict):
|
||||
name = literal_name(encoding.get('BaseEncoding', LITERAL_STANDARD_ENCODING))
|
||||
diff = list_value(encoding.get('Differences', []))
|
||||
self.cid2unicode = EncodingDB.get_encoding(name, diff)
|
||||
else:
|
||||
self.cid2unicode = EncodingDB.get_encoding(literal_name(encoding))
|
||||
self.unicode_map = None
|
||||
if 'ToUnicode' in spec:
|
||||
strm = PDFStream.validated_stream(spec['ToUnicode'])
|
||||
self.unicode_map = FileUnicodeMap()
|
||||
CMapParser(self.unicode_map, BytesIO(strm.get_data())).run()
|
||||
PDFFont.__init__(self, descriptor, widths)
|
||||
return
|
||||
|
||||
def to_unichr(self, cid):
|
||||
if self.unicode_map:
|
||||
try:
|
||||
return self.unicode_map.get_unichr(cid)
|
||||
except KeyError:
|
||||
pass
|
||||
try:
|
||||
return self.cid2unicode[cid]
|
||||
except KeyError:
|
||||
raise PDFUnicodeNotDefined(None, cid)
|
||||
@@ -1,89 +0,0 @@
|
||||
## TrueTypeFont
|
||||
##
|
||||
import struct
|
||||
from pdfmajor.parser.cmapdb import FileUnicodeMap
|
||||
|
||||
class TrueTypeFont(object):
|
||||
|
||||
class CMapNotFound(Exception):
|
||||
pass
|
||||
|
||||
def __init__(self, name, fp):
|
||||
self.name = name
|
||||
self.fp = fp
|
||||
self.tables = {}
|
||||
self.fonttype = fp.read(4)
|
||||
try:
|
||||
(ntables, _1, _2, _3) = struct.unpack('>HHHH', fp.read(8))
|
||||
for _ in range(ntables):
|
||||
(name, _, offset, length) = struct.unpack('>4sLLL', fp.read(16))
|
||||
self.tables[name] = (offset, length)
|
||||
except struct.error:
|
||||
# Do not fail if there are not enough bytes to read. Even for
|
||||
# corrupted PDFs we would like to get as much information as
|
||||
# possible, so continue.
|
||||
pass
|
||||
return
|
||||
|
||||
def create_unicode_map(self):
|
||||
if 'cmap' not in self.tables:
|
||||
raise TrueTypeFont.CMapNotFound
|
||||
(base_offset, _) = self.tables['cmap']
|
||||
fp = self.fp
|
||||
fp.seek(base_offset)
|
||||
(_, nsubtables) = struct.unpack('>HH', fp.read(4))
|
||||
subtables = []
|
||||
for i in range(nsubtables):
|
||||
subtables.append(struct.unpack('>HHL', fp.read(8)))
|
||||
char2gid = {}
|
||||
# Only supports subtable type 0, 2 and 4.
|
||||
for (_1, _2, st_offset) in subtables:
|
||||
fp.seek(base_offset+st_offset)
|
||||
(fmttype, _, _) = struct.unpack('>HHH', fp.read(6))
|
||||
if fmttype == 0:
|
||||
char2gid.update(enumerate(struct.unpack('>256B', fp.read(256))))
|
||||
elif fmttype == 2:
|
||||
subheaderkeys = struct.unpack('>256H', fp.read(512))
|
||||
firstbytes = [0]*8192
|
||||
for (i, k) in enumerate(subheaderkeys):
|
||||
firstbytes[k//8] = i
|
||||
nhdrs = max(subheaderkeys)//8 + 1
|
||||
hdrs = []
|
||||
for i in range(nhdrs):
|
||||
(firstcode, entcount, delta, offset) = struct.unpack('>HHhH', fp.read(8))
|
||||
hdrs.append((i, firstcode, entcount, delta, fp.tell()-2+offset))
|
||||
for (i, firstcode, entcount, delta, pos) in hdrs:
|
||||
if not entcount:
|
||||
continue
|
||||
first = firstcode + (firstbytes[i] << 8)
|
||||
fp.seek(pos)
|
||||
for c in range(entcount):
|
||||
gid = struct.unpack('>H', fp.read(2))
|
||||
if gid:
|
||||
gid += delta
|
||||
char2gid[first+c] = gid
|
||||
elif fmttype == 4:
|
||||
(segcount, _1, _2, _3) = struct.unpack('>HHHH', fp.read(8))
|
||||
segcount //= 2
|
||||
ecs = struct.unpack('>%dH' % segcount, fp.read(2*segcount))
|
||||
fp.read(2)
|
||||
scs = struct.unpack('>%dH' % segcount, fp.read(2*segcount))
|
||||
idds = struct.unpack('>%dh' % segcount, fp.read(2*segcount))
|
||||
pos = fp.tell()
|
||||
idrs = struct.unpack('>%dH' % segcount, fp.read(2*segcount))
|
||||
for (ec, sc, idd, idr) in zip(ecs, scs, idds, idrs):
|
||||
if idr:
|
||||
fp.seek(pos+idr)
|
||||
for c in range(sc, ec+1):
|
||||
char2gid[c] = (struct.unpack('>H', fp.read(2))[0] + idd) & 0xffff
|
||||
else:
|
||||
for c in range(sc, ec+1):
|
||||
char2gid[c] = (c + idd) & 0xffff
|
||||
else:
|
||||
assert False, str(('Unhandled', fmttype))
|
||||
# create unicode map
|
||||
unicode_map = FileUnicodeMap()
|
||||
for (char, gid) in char2gid.items():
|
||||
unicode_map.add_cid2unichr(gid, char)
|
||||
return unicode_map
|
||||
|
||||
@@ -1,45 +0,0 @@
|
||||
from pdfmajor.parser.PSStackParser import PSStackParser
|
||||
from pdfmajor.parser.PSStackParser import PSEOF, KWD
|
||||
from pdfmajor.parser.PSStackParser import PSLiteral
|
||||
from pdfmajor.parser.PSStackParser import literal_name
|
||||
from pdfmajor.parser.EncodingDB import name2unicode
|
||||
|
||||
## Type1FontHeaderParser
|
||||
##
|
||||
class Type1FontHeaderParser(PSStackParser):
|
||||
|
||||
KEYWORD_BEGIN = KWD(b'begin')
|
||||
KEYWORD_END = KWD(b'end')
|
||||
KEYWORD_DEF = KWD(b'def')
|
||||
KEYWORD_PUT = KWD(b'put')
|
||||
KEYWORD_DICT = KWD(b'dict')
|
||||
KEYWORD_ARRAY = KWD(b'array')
|
||||
KEYWORD_READONLY = KWD(b'readonly')
|
||||
KEYWORD_FOR = KWD(b'for')
|
||||
KEYWORD_FOR = KWD(b'for')
|
||||
|
||||
def __init__(self, data):
|
||||
PSStackParser.__init__(self, data)
|
||||
self._cid2unicode = {}
|
||||
return
|
||||
|
||||
def get_encoding(self):
|
||||
while 1:
|
||||
try:
|
||||
(cid, name) = self.nextobject()
|
||||
except PSEOF:
|
||||
break
|
||||
try:
|
||||
self._cid2unicode[cid] = name2unicode(name)
|
||||
except KeyError:
|
||||
pass
|
||||
return self._cid2unicode
|
||||
|
||||
def do_keyword(self, pos, token):
|
||||
if token is self.KEYWORD_PUT:
|
||||
((_, key), (_, value)) = self.pop(2) # pylint: disable=E0632
|
||||
if (isinstance(key, int) and
|
||||
isinstance(value, PSLiteral)):
|
||||
self.add_results((key, literal_name(value)))
|
||||
return
|
||||
|
||||
@@ -1,58 +0,0 @@
|
||||
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
|
||||
|
||||
log = get_logger(__file__)
|
||||
|
||||
def get_font(objid: int, spec: dict, cached_fonts: dict = {}):
|
||||
if objid and objid in cached_fonts:
|
||||
font = cached_fonts[objid]
|
||||
else:
|
||||
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')
|
||||
# Create a Font object.
|
||||
if 'Subtype' in spec:
|
||||
subtype = literal_name(spec['Subtype'])
|
||||
else:
|
||||
if settings.STRICT:
|
||||
raise PDFFontError('Font Subtype is not specified.')
|
||||
subtype = 'Type1'
|
||||
if subtype in ('Type1', 'MMType1'):
|
||||
# Type1 Font
|
||||
font = PDFType1Font(spec)
|
||||
elif subtype == 'TrueType':
|
||||
# TrueType Font
|
||||
font = PDFTrueTypeFont(spec)
|
||||
elif subtype == 'Type3':
|
||||
# Type3 Font
|
||||
font = PDFType3Font(spec)
|
||||
elif subtype in ('CIDFontType0', 'CIDFontType2'):
|
||||
# CID Font
|
||||
font = PDFCIDFont(spec)
|
||||
elif subtype == 'Type0':
|
||||
# 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:
|
||||
if settings.STRICT:
|
||||
raise PDFFontError('Invalid Font spec: %r' % spec)
|
||||
font = PDFType1Font(spec) # this is so wrong!
|
||||
if objid:
|
||||
cached_fonts[objid] = font
|
||||
return font
|
||||
|
||||
|
||||
|
||||
@@ -1,4 +0,0 @@
|
||||
from pdfmajor.parser.PDFStream import PDFException
|
||||
|
||||
class PDFFontError(PDFException): pass
|
||||
class PDFUnicodeNotDefined(PDFFontError): pass
|
||||
@@ -1,175 +0,0 @@
|
||||
from io import BytesIO
|
||||
|
||||
from pdfmajor.parser.PSStackParser import literal_name
|
||||
from pdfmajor.parser.PDFStream import int_value
|
||||
from pdfmajor.parser.PDFStream import num_value
|
||||
from pdfmajor.parser.PDFStream import list_value
|
||||
from pdfmajor.parser.PDFStream import dict_value
|
||||
from pdfmajor.parser.PDFStream import PDFStream
|
||||
from pdfmajor.parser.PDFStream import resolve1
|
||||
from pdfmajor.parser.cmapdb import CMap, CMapDB, CMapParser
|
||||
from pdfmajor.parser.cmapdb import FileUnicodeMap
|
||||
from pdfmajor.utils import settings, apply_matrix_norm
|
||||
|
||||
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):
|
||||
|
||||
def __init__(self, spec):
|
||||
try:
|
||||
self.basefont = literal_name(spec['BaseFont'])
|
||||
except KeyError:
|
||||
if settings.STRICT:
|
||||
raise PDFFontError('BaseFont is missing')
|
||||
self.basefont = 'unknown'
|
||||
try:
|
||||
(descriptor, widths) = FontMetricsDB.get_metrics(self.basefont)
|
||||
except KeyError:
|
||||
descriptor = dict_value(spec.get('FontDescriptor', {}))
|
||||
firstchar = int_value(spec.get('FirstChar', 0))
|
||||
#lastchar = int_value(spec.get('LastChar', 255))
|
||||
widths = list_value(spec.get('Widths', [0]*256))
|
||||
widths = dict((i+firstchar, w) for (i, w) in enumerate(widths))
|
||||
PDFSimpleFont.__init__(self, descriptor, widths, spec)
|
||||
if 'Encoding' not in spec and 'FontFile' in descriptor:
|
||||
# try to recover the missing encoding info from the font file.
|
||||
self.fontfile = PDFStream.validated_stream(descriptor.get('FontFile'))
|
||||
length1 = int_value(self.fontfile['Length1'])
|
||||
data = self.fontfile.get_data()[:length1]
|
||||
parser = Type1FontHeaderParser(BytesIO(data))
|
||||
self.cid2unicode = parser.get_encoding()
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFType1Font: basefont=%r>' % self.basefont
|
||||
|
||||
|
||||
# PDFTrueTypeFont
|
||||
class PDFTrueTypeFont(PDFType1Font):
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFTrueTypeFont: basefont=%r>' % self.basefont
|
||||
|
||||
|
||||
# PDFType3Font
|
||||
class PDFType3Font(PDFSimpleFont):
|
||||
|
||||
def __init__(self, spec):
|
||||
firstchar = int_value(spec.get('FirstChar', 0))
|
||||
#lastchar = int_value(spec.get('LastChar', 0))
|
||||
widths = list_value(spec.get('Widths', [0]*256))
|
||||
widths = dict((i+firstchar, w) for (i, w) in enumerate(widths))
|
||||
if 'FontDescriptor' in spec:
|
||||
descriptor = dict_value(spec['FontDescriptor'])
|
||||
else:
|
||||
descriptor = {'Ascent': 0, 'Descent': 0,
|
||||
'FontBBox': spec['FontBBox']}
|
||||
PDFSimpleFont.__init__(self, descriptor, widths, spec)
|
||||
self.matrix = tuple(list_value(spec.get('FontMatrix')))
|
||||
(_, self.descent, _, self.ascent) = self.bbox
|
||||
(self.hscale, self.vscale) = apply_matrix_norm(self.matrix, (1, 1))
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFType3Font>'
|
||||
|
||||
|
||||
# PDFCIDFont
|
||||
class PDFCIDFont(PDFFont):
|
||||
|
||||
def __init__(self, spec, strict=settings.STRICT):
|
||||
try:
|
||||
self.basefont = literal_name(spec['BaseFont'])
|
||||
except KeyError:
|
||||
if strict:
|
||||
raise PDFFontError('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"),
|
||||
resolve1(self.cidsysteminfo.get('Ordering', b'unknown')).decode("latin1"))
|
||||
try:
|
||||
name = literal_name(spec['Encoding'])
|
||||
except KeyError:
|
||||
if strict:
|
||||
raise PDFFontError('Encoding is unspecified')
|
||||
name = 'unknown'
|
||||
try:
|
||||
self.cmap = CMapDB.get_cmap(name)
|
||||
except CMapDB.CMapNotFound as e:
|
||||
if strict:
|
||||
raise PDFFontError(e)
|
||||
self.cmap = CMap()
|
||||
try:
|
||||
descriptor = dict_value(spec['FontDescriptor'])
|
||||
except KeyError:
|
||||
if strict:
|
||||
raise PDFFontError('FontDescriptor is missing')
|
||||
descriptor = {}
|
||||
ttf = None
|
||||
if 'FontFile2' in descriptor:
|
||||
self.fontfile = PDFStream.validated_stream(descriptor.get('FontFile2'))
|
||||
ttf = TrueTypeFont(self.basefont,
|
||||
BytesIO(self.fontfile.get_data()))
|
||||
self.unicode_map = None
|
||||
if 'ToUnicode' in spec:
|
||||
strm = PDFStream.validated_stream(spec['ToUnicode'])
|
||||
self.unicode_map = FileUnicodeMap()
|
||||
CMapParser(self.unicode_map, BytesIO(strm.get_data())).run()
|
||||
elif self.cidcoding in ('Adobe-Identity', 'Adobe-UCS'):
|
||||
if ttf:
|
||||
try:
|
||||
self.unicode_map = ttf.create_unicode_map()
|
||||
except TrueTypeFont.CMapNotFound:
|
||||
pass
|
||||
else:
|
||||
try:
|
||||
self.unicode_map = CMapDB.get_unicode_map(self.cidcoding, self.cmap.is_vertical())
|
||||
except CMapDB.CMapNotFound as e:
|
||||
pass
|
||||
|
||||
self.vertical = self.cmap.is_vertical()
|
||||
if self.vertical:
|
||||
# writing mode: vertical
|
||||
widths = get_widths2(list_value(spec.get('W2', [])))
|
||||
self.disps = dict((cid, (vx, vy)) for (cid, (_, (vx, vy))) in iter(widths.items()))
|
||||
(vy, w) = spec.get('DW2', [880, -1000])
|
||||
self.default_disp = (None, vy)
|
||||
widths = dict((cid, w) for (cid, (w, _)) in iter(widths.items()))
|
||||
default_width = w
|
||||
else:
|
||||
# writing mode: horizontal
|
||||
self.disps = {}
|
||||
self.default_disp = 0
|
||||
widths = get_widths(list_value(spec.get('W', [])))
|
||||
default_width = spec.get('DW', 1000)
|
||||
PDFFont.__init__(self, descriptor, widths, default_width=default_width)
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFCIDFont: basefont=%r, cidcoding=%r>' % (self.basefont, self.cidcoding)
|
||||
|
||||
def is_vertical(self):
|
||||
return self.vertical
|
||||
|
||||
def is_multibyte(self):
|
||||
return True
|
||||
|
||||
def decode(self, bytes):
|
||||
return self.cmap.decode(bytes)
|
||||
|
||||
def char_disp(self, cid):
|
||||
"Returns an integer for horizontal fonts, a tuple for vertical fonts."
|
||||
return self.disps.get(cid, self.default_disp)
|
||||
|
||||
def to_unichr(self, cid):
|
||||
try:
|
||||
if not self.unicode_map:
|
||||
raise KeyError(cid)
|
||||
return self.unicode_map.get_unichr(cid)
|
||||
except KeyError:
|
||||
raise PDFUnicodeNotDefined(self.cidcoding, cid)
|
||||
@@ -1,57 +0,0 @@
|
||||
from pdfmajor.utils import FONT_METRICS, choplist, isnumber
|
||||
|
||||
|
||||
def get_widths(seq):
|
||||
widths = {}
|
||||
r = []
|
||||
for v in seq:
|
||||
if isinstance(v, list):
|
||||
if r:
|
||||
char1 = r[-1]
|
||||
for (i, w) in enumerate(v):
|
||||
widths[char1+i] = w
|
||||
r = []
|
||||
elif isnumber(v):
|
||||
r.append(v)
|
||||
if len(r) == 3:
|
||||
(char1, char2, w) = r
|
||||
for i in range(char1, char2+1):
|
||||
widths[i] = w
|
||||
r = []
|
||||
return widths
|
||||
assert get_widths([1]) == {}
|
||||
assert get_widths([1,2,3]) == {1:3, 2:3}
|
||||
assert get_widths([1,[2,3],6,[7,8]]) == {1:2,2:3, 6:7,7:8}
|
||||
|
||||
def get_widths2(seq):
|
||||
widths = {}
|
||||
r = []
|
||||
for v in seq:
|
||||
if isinstance(v, list):
|
||||
if r:
|
||||
char1 = r[-1]
|
||||
for (i, (w, vx, vy)) in enumerate(choplist(3, v)):
|
||||
widths[char1+i] = (w, (vx, vy))
|
||||
r = []
|
||||
elif isnumber(v):
|
||||
r.append(v)
|
||||
if len(r) == 5:
|
||||
(char1, char2, w, vx, vy) = r # pylint: disable=E0632
|
||||
for i in range(char1, char2+1):
|
||||
widths[i] = (w, (vx, vy))
|
||||
r = []
|
||||
return widths
|
||||
assert get_widths2([1]) == {}
|
||||
assert get_widths2([1,2,3,4,5]) == {1:(3, (4,5)), 2:(3, (4,5))}
|
||||
assert get_widths2([1,[2,3,4,5],6,[7,8,9]]) == {1:(2, (3,4)), 6:(7, (8,9))}
|
||||
|
||||
|
||||
## FontMetricsDB
|
||||
##
|
||||
class FontMetricsDB(object):
|
||||
|
||||
@classmethod
|
||||
def get_metrics(klass, fontname):
|
||||
return FONT_METRICS[fontname]
|
||||
|
||||
|
||||
@@ -1,63 +0,0 @@
|
||||
from pdfmajor.utils import MATRIX_IDENTITY
|
||||
from .PDFFont import PDFFont, get_font
|
||||
from .PDFFont.execptions import PDFUnicodeNotDefined, PDFFontError
|
||||
|
||||
## PDFTextState
|
||||
##
|
||||
class PDFTextState(object):
|
||||
|
||||
def __init__(self):
|
||||
self.font: PDFFont = None
|
||||
self.fontsize: int = 0
|
||||
self.charspace: int = 0
|
||||
self.wordspace: int = 0
|
||||
self.scaling: int = 100
|
||||
self.leading: int = 0
|
||||
self.render: int = 0
|
||||
self.rise: int = 0
|
||||
self.matrix = MATRIX_IDENTITY
|
||||
self.linematrix = [0, 0]
|
||||
self.ignore_bad_chars = False
|
||||
|
||||
def __repr__(self):
|
||||
return ('<PDFTextState: font=%r, fontsize=%r, charspace=%r, wordspace=%r, '
|
||||
' scaling=%r, leading=%r, render=%r, rise=%r, '
|
||||
' matrix=%r, linematrix=%r ignore_bad_chars=%r>' %
|
||||
(self.font, self.fontsize, self.charspace, self.wordspace,
|
||||
self.scaling, self.leading, self.render, self.rise,
|
||||
self.matrix, self.linematrix, self.ignore_bad_chars))
|
||||
|
||||
def to_unichr(self, cid: int) -> str:
|
||||
if self.font is None:
|
||||
raise PDFFontError("Missing font")
|
||||
try:
|
||||
return self.font.to_unichr(cid)
|
||||
except PDFUnicodeNotDefined as e:
|
||||
if self.ignore_bad_chars:
|
||||
return ""
|
||||
else:
|
||||
raise e
|
||||
|
||||
|
||||
def copy(self):
|
||||
obj = self.__class__()
|
||||
obj.font = self.font
|
||||
obj.fontsize = self.fontsize
|
||||
obj.charspace = self.charspace
|
||||
obj.wordspace = self.wordspace
|
||||
obj.scaling = self.scaling
|
||||
obj.leading = self.leading
|
||||
obj.render = self.render
|
||||
obj.rise = self.rise
|
||||
obj.matrix = self.matrix
|
||||
obj.linematrix = self.linematrix
|
||||
obj.ignore_bad_chars = self.ignore_bad_chars
|
||||
return obj
|
||||
|
||||
def reset_matrices(self):
|
||||
self.matrix = MATRIX_IDENTITY
|
||||
self.linematrix = [0, 0]
|
||||
|
||||
@property
|
||||
def is_upright(self):
|
||||
return (0 < self.matrix[:,0].prod()*self.scaling and self.matrix[0,1:].prod() <= 0)
|
||||
@@ -1,40 +0,0 @@
|
||||
from typing import List
|
||||
from pdfmajor.utils import MATRIX_IDENTITY
|
||||
|
||||
from .PDFGraphicState import PDFGraphicState
|
||||
from .PDFGraphicState.PDFColor import PDFColor
|
||||
from .PDFGraphicState.PDFColorSpace import PREDEFINED_COLORSPACE, OrderedDict, PDFColorSpace
|
||||
|
||||
from .PDFTextState import PDFTextState, PDFFont, get_font
|
||||
|
||||
from .Curves import CurvePath
|
||||
|
||||
from .layout import LTItem, LTComponent, LTContainer
|
||||
from .layout import LTTextBlock, LTCharBlock, LTChar
|
||||
from .layout import LTCurve, LTLine, LTHorizontalLine, LTVerticalLine, LTRect
|
||||
from .layout import LTXObject
|
||||
from .layout import LTImage
|
||||
|
||||
from .layout import make_char_block, make_curve, make_image, make_xobject
|
||||
|
||||
class PDFStateStack:
|
||||
def __init__(self):
|
||||
self.t_matrix = MATRIX_IDENTITY
|
||||
self.text = PDFTextState()
|
||||
self.graphics = PDFGraphicState()
|
||||
self.gstack : list = []
|
||||
self.curvestacks: List[CurvePath] = []
|
||||
self.argstack: List[bytes] = []
|
||||
self.complete_layout_items : List[LTItem] = []
|
||||
self.colorspace_map: OrderedDict = PREDEFINED_COLORSPACE.copy()
|
||||
self.fontmap = {}
|
||||
self.xobjmap = {}
|
||||
self.resources = {}
|
||||
self.current_textblock: LTTextBlock = None
|
||||
|
||||
def pop(self, n: int) -> bytearray:
|
||||
if n == 0:
|
||||
return []
|
||||
x = self.argstack[-n:]
|
||||
self.argstack = self.argstack[:-n]
|
||||
return x
|
||||
@@ -1,46 +0,0 @@
|
||||
from ._base import LTComponent
|
||||
from pdfmajor.utils import apply_matrix_norm, apply_matrix_pt, matrix2str, Bbox
|
||||
from ..PDFGraphicState import PDFColor
|
||||
from ..PDFTextState import PDFTextState, PDFFont
|
||||
|
||||
## LTChar
|
||||
##
|
||||
class LTChar(LTComponent):
|
||||
|
||||
def __init__(self,
|
||||
bbox: Bbox,
|
||||
char: str,
|
||||
textstate: PDFTextState,
|
||||
color: PDFColor
|
||||
):
|
||||
self._text = char
|
||||
self.textstate = textstate
|
||||
self.color = color
|
||||
LTComponent.__init__(self, bbox)
|
||||
if self.textstate.font.is_vertical():
|
||||
self.size = self.width
|
||||
else:
|
||||
self.size = self.height
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return (
|
||||
'<%s %s font=%r text=%r>' %
|
||||
(
|
||||
self.__class__.__name__,
|
||||
str(self.bbox),
|
||||
self.fontname,
|
||||
self.get_text()
|
||||
)
|
||||
)
|
||||
|
||||
def get_text(self):
|
||||
return self._text
|
||||
|
||||
@property
|
||||
def font(self):
|
||||
return self.textstate.font
|
||||
|
||||
@property
|
||||
def fontname(self) -> str:
|
||||
return self.font.fontname
|
||||
Loaded 100 of 225 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user