Compare commits
151
Commits
v1.3.0
...
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 | ||
|
|
152d3aaf55 | ||
|
|
36a9371657 | ||
|
|
a29d465ea4 | ||
|
|
841576d9b8 | ||
|
|
bfc0b6ba34 | ||
|
|
336f5f1fba | ||
|
|
1b1db13b5b | ||
|
|
3f561f3488 | ||
|
|
989de3122e | ||
|
|
20be0aa49e | ||
|
|
d37b56a685 | ||
|
|
9e923de7ec | ||
|
|
2c9593ac21 | ||
|
|
057cc0cf28 | ||
|
|
82b47f1b19 | ||
|
|
290de97cb5 | ||
|
|
b32aef7fda | ||
|
|
14ba20be55 | ||
|
|
18938d91ea | ||
|
|
eb38854076 | ||
|
|
671ae5bc4a | ||
|
|
844408c6e3 | ||
|
|
bab104885f | ||
|
|
98f18c3e32 | ||
|
|
ac2c462561 | ||
|
|
19712f1f0f | ||
|
|
ec02a7d38b | ||
|
|
0345ca01ba | ||
|
|
b36f6bc907 | ||
|
|
f9f9a59793 | ||
|
|
b7026793d7 | ||
|
|
addd59ed0f | ||
|
|
d43b617309 | ||
|
|
17b25c7d9b | ||
|
|
b7fab64801 | ||
|
|
609bcda76a | ||
|
|
ef230847ac | ||
|
|
d1d1b23f2f | ||
|
|
abfbe98897 | ||
|
|
e7701ce2ac | ||
|
|
c239f79b2c |
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
|
||||
+10
-2
@@ -8,6 +8,14 @@ docs/_build
|
||||
tests/*.xml
|
||||
tests/*.txt
|
||||
.idea/
|
||||
.vscode
|
||||
tests/samples/output
|
||||
**__pycache**
|
||||
./samples
|
||||
**__pycache**\
|
||||
.mypy_cache
|
||||
.ipynb_checkpoints
|
||||
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>
|
||||
@@ -11,15 +27,15 @@
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
PDF-Major is a fork of `PDFMiner.six`. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.
|
||||
PDF-Major is a **complete re-write** of `PDFMiner.six`. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.
|
||||
|
||||
## Documentation
|
||||
|
||||
See documentation [here](https://asosnovsky.github.io/pdfmajor/).
|
||||
See [full API documentation here](https://asosnovsky.github.io/pdfmajor/api/).
|
||||
|
||||
## Basic Example
|
||||
```py
|
||||
from pdfmajor.interpreter import PageInterpreter
|
||||
from pdfmajor.interpreter import PDFInterpreter
|
||||
|
||||
for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
print("page start", page.page_num)
|
||||
@@ -29,9 +45,9 @@ for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
|
||||
```
|
||||
|
||||
## Why Another Fork?
|
||||
## Why a re-write?
|
||||
|
||||
`PDFMiner` was designed to run in python 2.7>, `PDFMiner.six` was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon `PDFMiner.six` I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.
|
||||
`PDFMiner` was designed to run in python 2.7, `PDFMiner.six` was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon `PDFMiner.six` I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.
|
||||
|
||||
## Features
|
||||
|
||||
|
||||
@@ -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,18 +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
|
||||
|
||||
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/*
|
||||
+6
-103
@@ -2,109 +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 PageInterpreter
|
||||
|
||||
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
|
||||
- `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
|
||||
|
||||
#### 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
|
||||
+1
-1
@@ -19,7 +19,7 @@ See documentation [here](https://asosnovsky.github.io/pdfmajor/).
|
||||
|
||||
## Basic Example
|
||||
```py
|
||||
from pdfmajor.interpreter import PageInterpreter
|
||||
from pdfmajor.interpreter import PDFInterpreter
|
||||
|
||||
for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
print("page start", page.page_num)
|
||||
|
||||
+72
-65
@@ -62,14 +62,14 @@
|
||||
|
||||
<ul>
|
||||
|
||||
<li><a class="toctree-l3" href="#parser">parser</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#interpreter">interpreter</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#converters">converters</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#imagewriter">imagewriter</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#layouts">layouts</a></li>
|
||||
|
||||
</ul>
|
||||
|
||||
|
||||
@@ -111,37 +111,83 @@
|
||||
<h1 id="api">API</h1>
|
||||
<p>The library is constructed from 4 base modules:</p>
|
||||
<ul>
|
||||
<li><strong>interpreter</strong>: contains low-level classes for extracting fundamental data-structures from the documents</li>
|
||||
<li><strong>converters</strong>: contains high-level classes for conversion of the fundamental pdf structures to other formats</li>
|
||||
<li><strong>parser</strong>: contains low-level classes for extracting fundamental data-structures from the documents</li>
|
||||
<li><strong>interpreter</strong>: a interpreter of the pdf-standard commands</li>
|
||||
<li><strong>converters</strong>: contains high-level functions for conversion of the fundamental pdf structures to other formats</li>
|
||||
<li><strong>imagewriter</strong>: contains a simple implementation for converting PDF Image Streams to png/bmp/img formats</li>
|
||||
<li><strong>layouts</strong>: contains an abstraction layer for the data-structures found in the pdf</li>
|
||||
</ul>
|
||||
<h2 id="parser">parser</h2>
|
||||
<p>WIP</p>
|
||||
<h2 id="interpreter">interpreter</h2>
|
||||
<pre><code>WIP
|
||||
</code></pre>
|
||||
<h2 id="converters">converters</h2>
|
||||
<p>Contains high-level classes for conversion of the fundamental pdf structures to other formats. This library includes 4 high-level conversion classes:</p>
|
||||
<ul>
|
||||
<li>HTMLConverter</li>
|
||||
<li>JSONConverter</li>
|
||||
<li>XMLConverter</li>
|
||||
<li>TextConverter</li>
|
||||
</ul>
|
||||
<p>These classes all extend the <a href="#converters.PDFConverter">PDFConverter</a>. To use them simply call the static method <a href="#converterspdfconverterparse_fileinput_file-output_file-image_folder_path-codec-maxpages-password-caching-check_extractable-pagenos">parse_file</a>.</p>
|
||||
<p>a interpreter of the pdf-standard commands</p>
|
||||
<h3 id="example">Example</h3>
|
||||
<pre><code class="py">from pdfmajor.converters import HTMLConverter
|
||||
<pre><code class="py">from pdfmajor.interpreter import PDFInterpreter
|
||||
|
||||
input_file = open('path/to/input/file.pdf', 'rb')
|
||||
output_file = open('path/to/output/file.html', 'wb')
|
||||
HTMLConverter.parse_file(
|
||||
input_file,
|
||||
output_file
|
||||
)
|
||||
input_file.close()
|
||||
output_file.close()
|
||||
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)
|
||||
</code></pre>
|
||||
|
||||
<h3 id="convertersconvert_fileinput_file-output_file-image_folder_path-codec-maxpages-password-caching-check_extractable-pagenos-out_type">converters.convert_file(input_file, output_file, image_folder_path, codec, maxpages, password, caching, check_extractable, pagenos, out_type)</h3>
|
||||
<h3 id="interpreterpdfinterpreter">interpreter.PDFInterpreter</h3>
|
||||
<p>This generator-function yields individual pages which contain their respected items.</p>
|
||||
<h4 id="arguments">Arguments</h4>
|
||||
<ul>
|
||||
<li><code>input_file_path</code>: <a href="#">str</a></li>
|
||||
<li><code>preload</code>: <a href="#">bool</a> defaults to False</li>
|
||||
<li><code>maxpages</code>: <a href="#">int</a> defaults to 0 </li>
|
||||
<li><code>password</code>: <a href="#">str</a> defaults to None </li>
|
||||
<li><code>caching</code>: <a href="#">bool</a> defaults to True </li>
|
||||
<li><code>check_extractable</code>: <a href="#">bool</a> defaults to True</li>
|
||||
<li><code>ignore_bad_chars</code>: <a href="#">bool</a> defaults to False</li>
|
||||
<li><code>pagenos</code>: <a href="#">List[int]</a> defaults to None</li>
|
||||
<li><code>debug_level</code>: <a href="#https://docs.python.org/3/library/logging.html#levels">logging.levels</a> defaults logging.WARNING</li>
|
||||
</ul>
|
||||
<h4 id="yield-value">Yield Value</h4>
|
||||
<p>This function returns a generator that yields <a href="#interpreterpageinterpreter">PDFInterpreter</a>.</p>
|
||||
<h3 id="interpreterpageinterpreter">interpreter.PageInterpreter</h3>
|
||||
<p>This generator-function-class yields individual <a href="#layout-items">layout items</a>.</p>
|
||||
<h3 id="layout-items">Layout Items</h3>
|
||||
<p>All layout items extend the <code>LTItem</code> class. There are two kinds of layout items:</p>
|
||||
<ul>
|
||||
<li>LTComponent: extends the base <code>LTItem</code> class, this class will have additional values such as boundary boxes, height and width</li>
|
||||
<li>LTContainer: extends the <code>LTComponent</code> 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.</li>
|
||||
</ul>
|
||||
<h4 id="layout-containers">Layout Containers</h4>
|
||||
<p>All of these classes extend the LTContainer class.</p>
|
||||
<ul>
|
||||
<li>LTXObject: a layout item containing other additional layout items</li>
|
||||
<li>LTCharBlock: a layout item containing LTChars, this corresponds to whenever a <code>TJ</code> or <code>Tj</code> operators is issued within a text object.</li>
|
||||
<li>LTTextBlock: a layout item containing LTCharBlocks, note that this directly corresponds to the <code>BT</code> and <code>ET</code> operators pair in the pdf standard</li>
|
||||
</ul>
|
||||
<h4 id="layout-components">Layout Components</h4>
|
||||
<p>All of these classes extend the LTComponent class.</p>
|
||||
<ul>
|
||||
<li>LTChar: an individual character</li>
|
||||
<li>LTCurves: represents a collection of svg-paths (available under <code>self.paths</code>)</li>
|
||||
<li>LTImage: a component containing information regarding an image</li>
|
||||
</ul>
|
||||
<h2 id="converters">converters</h2>
|
||||
<p>Contains high-level functions for conversion of the fundamental pdf structures to other formats. This library includes 4 high-level conversion cases:</p>
|
||||
<ul>
|
||||
<li>HTML</li>
|
||||
<li>JSON</li>
|
||||
<li>XML</li>
|
||||
<li>Text</li>
|
||||
</ul>
|
||||
<p>These formats are all generated using the <a href="#PDFInterpreter">PageInterpreter</a>. To use them simply call the static method <a href="#converterspdfconverter">parse_file</a>.</p>
|
||||
<h3 id="example_1">Example</h3>
|
||||
<pre><code class="py">from pdfmajor.converters import convert_file
|
||||
|
||||
convert_file(
|
||||
"path/to/input/file.pdf",
|
||||
"path/to/output/file.html",
|
||||
out_type="html"
|
||||
)
|
||||
</code></pre>
|
||||
|
||||
<h3 id="convertersconvert_file">converters.convert_file</h3>
|
||||
<p>A high-level abstraction for the conversion classes.</p>
|
||||
<ul>
|
||||
<li><code>input_file</code>: <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper">TextIOWrapper</a> </li>
|
||||
@@ -155,46 +201,7 @@ output_file.close()
|
||||
<li><code>pagenos</code>: <a href="#">List[int]</a> defaults to None</li>
|
||||
<li><code>out_type</code>: <a href="#">str</a> defaults to 'html'</li>
|
||||
</ul>
|
||||
<h3 id="example-convertersconvert_file">Example (converters.convert_file)</h3>
|
||||
<pre><code class="py">from pdfmajor.converters import convert_file
|
||||
|
||||
input_file = open('path/to/input/file.pdf', 'rb')
|
||||
output_file = open('path/to/output/file.html', 'wb')
|
||||
convert_file(
|
||||
input_file,
|
||||
output_file
|
||||
)
|
||||
input_file.close()
|
||||
output_file.close()
|
||||
</code></pre>
|
||||
|
||||
<h3 id="converterspdfconverter">converters.PDFConverter</h3>
|
||||
<p>Extends <code>layouts.PDFLayoutAnalyzer</code>.</p>
|
||||
<h4 id="converterspdfconverter9595init9595rsrcmgr-outfp-imagewriter-codec-pageno">converters.PDFConverter.__init__(rsrcmgr, outfp, imagewriter, codec, pageno)</h4>
|
||||
<ul>
|
||||
<li><code>rsrcmgr</code>: <a href="#interpreter.PDFResourceManager">PDFResourceManager</a></li>
|
||||
<li><code>outfp</code>: <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper">TextIOWrapper</a></li>
|
||||
<li><code>imagewriter</code>: <a href="#imagewriter.ImageWriter">ImageWriter</a></li>
|
||||
<li><code>codec</code>: <a href="#">str</a> defaults to 'utf-8'</li>
|
||||
<li><code>pageno</code>: <a href="#">int</a> defaults to 1</li>
|
||||
</ul>
|
||||
<p>initialization function for the class</p>
|
||||
<h4 id="converterspdfconverterparse_fileinput_file-output_file-image_folder_path-codec-maxpages-password-caching-check_extractable-pagenos">converters.PDFConverter.parse_file(input_file, output_file, image_folder_path, codec, maxpages, password, caching, check_extractable, pagenos)</h4>
|
||||
<p>returns the output file <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper">TextIOWrapper</a>.</p>
|
||||
<ul>
|
||||
<li><code>input_file</code>: <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper">TextIOWrapper</a> </li>
|
||||
<li><code>output_file</code>: <a href="https://docs.python.org/3/library/io.html#io.TextIOWrapper">TextIOWrapper</a> </li>
|
||||
<li><code>image_folder_path</code>: <a href="#">str</a> defaults to None</li>
|
||||
<li><code>codec</code>: <a href="#">str</a> defaults to 'utf-8'</li>
|
||||
<li><code>maxpages</code>: <a href="#">int</a> defaults to 0 </li>
|
||||
<li><code>password</code>: <a href="#">str</a> defaults to None </li>
|
||||
<li><code>caching</code>: <a href="#">bool</a> defaults to True </li>
|
||||
<li><code>check_extractable</code>: <a href="#">bool</a> defaults to True</li>
|
||||
<li><code>pagenos</code>: <a href="#">List[int]</a> defaults to None</li>
|
||||
</ul>
|
||||
<h2 id="imagewriter">imagewriter</h2>
|
||||
<p>WIP </p>
|
||||
<h2 id="layouts">layouts</h2>
|
||||
<p>WIP </p>
|
||||
|
||||
</div>
|
||||
|
||||
+20
-7
@@ -59,6 +59,8 @@
|
||||
|
||||
<li><a class="toctree-l3" href="#documentation">Documentation</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#basic-example">Basic Example</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#why-another-fork">Why Another Fork?</a></li>
|
||||
|
||||
<li><a class="toctree-l3" href="#features">Features</a></li>
|
||||
@@ -122,23 +124,34 @@
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
<p>PDF-Major is a fork of <code>PDFMiner.six</code>. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. Additionally, this version intends to be more up to date with recent versions of python and make liberal use of the typing capabilities of python for improved future maintainability.</p>
|
||||
<p>PDF-Major is a fork of <code>PDFMiner.six</code>. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.</p>
|
||||
<h2 id="documentation">Documentation</h2>
|
||||
<p>See documentation <a href="https://asosnovsky.github.io/pdfmajor/">here</a>.</p>
|
||||
<h2 id="basic-example">Basic Example</h2>
|
||||
<pre><code class="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)
|
||||
|
||||
</code></pre>
|
||||
|
||||
<h2 id="why-another-fork">Why Another Fork?</h2>
|
||||
<p><code>PDFMiner</code> was designed to run in python 2.7>, <code>PDFMiner.six</code> was written to bring cross-version support for python 2 and 3. This versions intends to make use of the latest improvement in the python language while remaining fairly simple to develop with. </p>
|
||||
<p><code>PDFMiner</code> was designed to run in python 2.7>, <code>PDFMiner.six</code> was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon <code>PDFMiner.six</code> I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.</p>
|
||||
<h2 id="features">Features</h2>
|
||||
<ul>
|
||||
<li>Written entirely in Python.</li>
|
||||
<li>Functional extraction method based on generators</li>
|
||||
<li>Parse, analyze, and convert PDF documents.</li>
|
||||
<li>PDF-1.7 specification support. (well, almost)</li>
|
||||
<li>Font-Color extraction</li>
|
||||
<li>Shape fill and stroke color extraction</li>
|
||||
<li>CJK languages and vertical writing scripts support.</li>
|
||||
<li>Various font types (Type1, TrueType, Type3, and CID) support.</li>
|
||||
<li>Basic encryption (RC4) support.</li>
|
||||
<li>Font-Color extraction</li>
|
||||
<li>Shape fill and stroke color extraction</li>
|
||||
</ul>
|
||||
<p><strong>Note</strong>: We took out the layout-analysis process in this version (there is no more LTTextHorizontal or LTTextVertical). While the mathematics behind the grouping process was sound, the coupling of the layout-analysis process with the parsing and interpretation process produced unfriendly-code. This feature could be brought back by extending the <code>pdfmajor.layouts.PDFLayoutAnalyzer</code> class, but at the current time is not supported.</p>
|
||||
<p><strong>Note</strong>: We took out the layout-analysis process in this version (there is no more LTTextHorizontal or LTTextVertical). While the mathematics behind the grouping process was sound, the coupling of the layout-analysis process with the parsing and interpretation process produced unfriendly-code. This feature could be brought back by running your own implementation of it on the <code>pdfmajor.interpreter.PageInterpreter</code> class, but at the current time is not supported.</p>
|
||||
<h2 id="how-to-install">How to Install</h2>
|
||||
<h3 id="source">Source</h3>
|
||||
<ul>
|
||||
@@ -227,5 +240,5 @@ SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.</p>
|
||||
|
||||
<!--
|
||||
MkDocs version : 1.0.4
|
||||
Build Date UTC : 2018-11-04 21:27:38
|
||||
Build Date UTC : 2019-12-08 19:44:26
|
||||
-->
|
||||
@@ -1 +1 @@
|
||||
{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"PDFMajor Latest Release PDF-Major is a fork of PDFMiner.six . It is meant to be a more light-weight implementation that makes fewer assumptions on the data. Additionally, this version intends to be more up to date with recent versions of python and make liberal use of the typing capabilities of python for improved future maintainability. Documentation See documentation here . Why Another Fork? PDFMiner was designed to run in python 2.7>, PDFMiner.six was written to bring cross-version support for python 2 and 3. This versions intends to make use of the latest improvement in the python language while remaining fairly simple to develop with. Features Written entirely in Python. Parse, analyze, and convert PDF documents. PDF-1.7 specification support. (well, almost) CJK languages and vertical writing scripts support. Various font types (Type1, TrueType, Type3, and CID) support. Basic encryption (RC4) support. Font-Color extraction Shape fill and stroke color extraction Note : We took out the layout-analysis process in this version (there is no more LTTextHorizontal or LTTextVertical). While the mathematics behind the grouping process was sound, the coupling of the layout-analysis process with the parsing and interpretation process produced unfriendly-code. This feature could be brought back by extending the pdfmajor.layouts.PDFLayoutAnalyzer class, but at the current time is not supported. How to Install Source Install Python 3.6.4 or newer. clone this repo git clone https://github.com/asosnovsky/pdfmajor * install repo python setup.py install Pypi Install Python 3.6.4 or newer. install repo pip install pdfmajor Terms and Conditions (This is so-called MIT/X License) Copyright (c) 2018-2019 Ariel Sosnovsky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","title":"Home"},{"location":"#pdfmajor","text":"Latest Release PDF-Major is a fork of PDFMiner.six . It is meant to be a more light-weight implementation that makes fewer assumptions on the data. Additionally, this version intends to be more up to date with recent versions of python and make liberal use of the typing capabilities of python for improved future maintainability.","title":"PDFMajor"},{"location":"#documentation","text":"See documentation here .","title":"Documentation"},{"location":"#why-another-fork","text":"PDFMiner was designed to run in python 2.7>, PDFMiner.six was written to bring cross-version support for python 2 and 3. This versions intends to make use of the latest improvement in the python language while remaining fairly simple to develop with.","title":"Why Another Fork?"},{"location":"#features","text":"Written entirely in Python. Parse, analyze, and convert PDF documents. PDF-1.7 specification support. (well, almost) CJK languages and vertical writing scripts support. Various font types (Type1, TrueType, Type3, and CID) support. Basic encryption (RC4) support. Font-Color extraction Shape fill and stroke color extraction Note : We took out the layout-analysis process in this version (there is no more LTTextHorizontal or LTTextVertical). While the mathematics behind the grouping process was sound, the coupling of the layout-analysis process with the parsing and interpretation process produced unfriendly-code. This feature could be brought back by extending the pdfmajor.layouts.PDFLayoutAnalyzer class, but at the current time is not supported.","title":"Features"},{"location":"#how-to-install","text":"","title":"How to Install"},{"location":"#source","text":"Install Python 3.6.4 or newer. clone this repo git clone https://github.com/asosnovsky/pdfmajor * install repo python setup.py install","title":"Source"},{"location":"#pypi","text":"Install Python 3.6.4 or newer. install repo pip install pdfmajor","title":"Pypi"},{"location":"#terms-and-conditions","text":"(This is so-called MIT/X License) Copyright (c) 2018-2019 Ariel Sosnovsky Permission is hereby granted, free of chargeLine truncated
|
||||
{"config":{"lang":["en"],"prebuild_index":false,"separator":"[\\s\\-]+"},"docs":[{"location":"","text":"PDFMajor Latest Release PDF-Major is a fork of PDFMiner.six . It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon. Documentation See documentation here . Basic Example 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) Why Another Fork? PDFMiner was designed to run in python 2.7>, PDFMiner.six was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon PDFMiner.six I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports. Features Functional extraction method based on generators Parse, analyze, and convert PDF documents. PDF-1.7 specification support. (well, almost) Font-Color extraction Shape fill and stroke color extraction CJK languages and vertical writing scripts support. Various font types (Type1, TrueType, Type3, and CID) support. Basic encryption (RC4) support. Note : We took out the layout-analysis process in this version (there is no more LTTextHorizontal or LTTextVertical). While the mathematics behind the grouping process was sound, the coupling of the layout-analysis process with the parsing and interpretation process produced unfriendly-code. This feature could be brought back by running your own implementation of it on the pdfmajor.interpreter.PageInterpreter class, but at the current time is not supported. How to Install Source Install Python 3.6.4 or newer. clone this repo git clone https://github.com/asosnovsky/pdfmajor * install repo python setup.py install Pypi Install Python 3.6.4 or newer. install repo pip install pdfmajor Terms and Conditions (This is so-called MIT/X License) Copyright (c) 2018-2019 Ariel Sosnovsky Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the \"Software\"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.","title":"Home"},{"location":"#pdfmajor","text":"Latest Release PDF-Major is a fork of PDFMiner.six . It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.","title":"PDFMajor"},{"location":"#documentation","text":"See documentation here .","title":"Documentation"},{"location":"#basic-example","text":"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)","title":"Basic Example"},{"location":"#why-another-fork","text":"PDFMiner was designed to run in python 2.7>, PDFMiner.six was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon PDFMiner.six I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.","title":"Why Another Fork?"},{"location":"#features","text":"Functional extraction method based on generators Parse, analyze, and convert PDF documents. PDF-1.7 specification support. (well, almost) Font-Color extraction Shape fill and stroke color extraction CJK languages and vertical writing scripts support. Various font types (Type1, TrueType, Type3, and CID) support. Basic encryption (RC4) support. Note : We took out the layout-analysis process in this version (there is no more LTTexLine truncated
|
||||
+2
-2
@@ -2,12 +2,12 @@
|
||||
<urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9">
|
||||
<url>
|
||||
<loc>None</loc>
|
||||
<lastmod>2018-11-04</lastmod>
|
||||
<lastmod>2019-12-08</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
<url>
|
||||
<loc>None</loc>
|
||||
<lastmod>2018-11-04</lastmod>
|
||||
<lastmod>2019-12-08</lastmod>
|
||||
<changefreq>daily</changefreq>
|
||||
</url>
|
||||
</urlset>
|
||||
Binary file not shown.
@@ -0,0 +1,5 @@
|
||||
[mypy]
|
||||
python_version = 3.7
|
||||
warn_return_any = True
|
||||
warn_unused_configs = True
|
||||
|
||||
+10
-13
@@ -1,7 +1,6 @@
|
||||
|
||||
#
|
||||
#
|
||||
# DO NOT EDIT THIS PAGE
|
||||
#
|
||||
#
|
||||
"""
|
||||
# PDFMajor
|
||||
|
||||
@@ -16,15 +15,15 @@
|
||||
</tr>
|
||||
</table>
|
||||
|
||||
PDF-Major is a fork of `PDFMiner.six`. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.
|
||||
PDF-Major is a **complete re-write** of `PDFMiner.six`. It is meant to be a more light-weight implementation that makes fewer assumptions on the data. The ultimate goal of this project is to provide a simpler, faster and more functional library that both casual and low-level developers could build upon.
|
||||
|
||||
## Documentation
|
||||
|
||||
See documentation [here](https://asosnovsky.github.io/pdfmajor/).
|
||||
See [full API documentation here](https://asosnovsky.github.io/pdfmajor/api/).
|
||||
|
||||
## Basic Example
|
||||
```py
|
||||
from pdfmajor.interpreter import PageInterpreter
|
||||
from pdfmajor.interpreter import PDFInterpreter
|
||||
|
||||
for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
print("page start", page.page_num)
|
||||
@@ -34,9 +33,9 @@ for page in PDFInterpreter("/path/to/pdf.pdf"):
|
||||
|
||||
```
|
||||
|
||||
## Why Another Fork?
|
||||
## Why a re-write?
|
||||
|
||||
`PDFMiner` was designed to run in python 2.7>, `PDFMiner.six` was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon `PDFMiner.six` I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.
|
||||
`PDFMiner` was designed to run in python 2.7, `PDFMiner.six` was written to bring cross-version support for python 2 and 3. However, after attempting to build and extend upon `PDFMiner.six` I found it rather difficult to extend and identify additional details regarding the items encoded in the pdf. This library will attempt to expose as much information as possible to end-users, without having them solely rely on to-xml or to-json exports.
|
||||
|
||||
## Features
|
||||
|
||||
@@ -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, 0)
|
||||
__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,92 +0,0 @@
|
||||
import io
|
||||
import os
|
||||
import re
|
||||
|
||||
from typing import List
|
||||
|
||||
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 ..utils import logging
|
||||
|
||||
def convert_file(
|
||||
input_file: str,
|
||||
output_file: str = None,
|
||||
image_folder_path: str = None,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = None,
|
||||
caching: bool = True,
|
||||
check_extractable: bool = True,
|
||||
pagenos: List[int] = None,
|
||||
dont_export_images: 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.name),
|
||||
os.path.basename(
|
||||
re.sub(r"\.\w+$", "."+out_type, input_file.name)
|
||||
)
|
||||
)
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
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,
|
||||
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'")
|
||||
@@ -1,189 +0,0 @@
|
||||
from typing import List
|
||||
from .writers.html import HTMLMaker
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, LTCharBlock, LTChar, LTCurve, LTXObject
|
||||
from ..interpreter.commands import LTItem
|
||||
from ..interpreter.commands.state import CurvePath, PDFColor
|
||||
|
||||
def convert_to_html(
|
||||
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,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
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):
|
||||
if isinstance(item, LTCurve):
|
||||
render_curve(html, item)
|
||||
elif isinstance(item, LTXObject):
|
||||
with html.elm('div', { "class": 'xobject' }, {
|
||||
'position': 'absolute',
|
||||
'left': f'{item.x0}px',
|
||||
'bottom': f'{item.y0}px',
|
||||
'width': f'{item.width}px',
|
||||
'height': f'{item.height}px',
|
||||
}):
|
||||
for child in item:
|
||||
render(child)
|
||||
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': item.width,
|
||||
'min-width': item.width,
|
||||
'max-width': item.width,
|
||||
'height': item.height,
|
||||
'min-height': item.height,
|
||||
'max-height': item.height,
|
||||
}):
|
||||
html.write(item.get_text())
|
||||
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': item.width,
|
||||
'min-width': item.width,
|
||||
'max-width': item.width,
|
||||
'height': item.height,
|
||||
'min-height': item.height,
|
||||
'max-height': item.height,
|
||||
'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, item: LTCurve):
|
||||
css = {
|
||||
'position': 'absolute',
|
||||
'left': f'{item.x0}px',
|
||||
'bottom': f'{item.y0}px',
|
||||
'width': f'{item.width}px',
|
||||
'height': f'{item.height}px',
|
||||
}
|
||||
path = ""
|
||||
svg_attr = {
|
||||
'class': 'curve',
|
||||
'z-index': 2
|
||||
}
|
||||
path_css = {
|
||||
|
||||
}
|
||||
|
||||
# Compute ViewBox
|
||||
p_vals = { "x": [], "y": [] }
|
||||
|
||||
for p in item.paths:
|
||||
for pt in p.points:
|
||||
p_vals['x'].append(pt.x)
|
||||
p_vals['y'].append(pt.y)
|
||||
|
||||
mx_x = max([*p_vals['x'], 1])
|
||||
mn_x = min([*p_vals['x'], 0])
|
||||
mx_y = max([*p_vals['y'], 1])
|
||||
mn_y = min([*p_vals['y'], 0])
|
||||
|
||||
if mx_x == mn_x:
|
||||
mn_x -= 1
|
||||
if mx_y == mn_y:
|
||||
mn_y -= 1
|
||||
|
||||
dx = 1/( mx_x - mn_x )
|
||||
dy = (item.height/item.width)/( mx_y - mn_y )
|
||||
ROUND_VAL = 5
|
||||
svg_attr.update({
|
||||
# "viewBox": f"{min(p_vals['x'])} {min(p_vals['y'])} {max(p_vals['x'])} {max(p_vals['y'])}",
|
||||
"viewBox": f"{round(mn_x*dx, ROUND_VAL)} {round(mn_y*dy, ROUND_VAL)} {round(mx_x*dx , ROUND_VAL)} {round(mx_y*dy, ROUND_VAL)}",
|
||||
})
|
||||
|
||||
# Compute shape
|
||||
for p in item.paths:
|
||||
if p.method == CurvePath.METHOD.MOVE_TO:
|
||||
path += f'M{" ".join( f"{round(dx*pt.x, ROUND_VAL)} {round(dy*pt.y, ROUND_VAL)}" for pt in p.points )} '
|
||||
if p.method == CurvePath.METHOD.LINE_TO:
|
||||
path += f'L{" ".join( f"{round(dx*pt.x, ROUND_VAL)} {round(dy*pt.y, ROUND_VAL)}" for pt in p.points )} '
|
||||
if p.method == CurvePath.METHOD.CLOSE_PATH:
|
||||
path += 'Z'
|
||||
|
||||
stroke_col = get_color(item.stroke)
|
||||
fill_col = get_color(item.fill)
|
||||
if fill_col:
|
||||
path_css['fill'] = fill_col
|
||||
if stroke_col:
|
||||
path_css['stroke'] = stroke_col
|
||||
|
||||
with html.elm('svg', svg_attr, css):
|
||||
html.singleton('path', {
|
||||
"d": path,
|
||||
**path_css
|
||||
}, {
|
||||
**path_css
|
||||
})
|
||||
@@ -1,134 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from .writers.json import JSONMaker, JSONMakerObject, JSONMakerArray
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTImage, 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
|
||||
|
||||
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: str = None,
|
||||
dont_export_images: bool = False,
|
||||
codec: str = 'utf-8',
|
||||
maxpages: int = 0,
|
||||
password: str = None,
|
||||
caching: bool = True,
|
||||
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,
|
||||
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, LTCharBlock):
|
||||
place_char_block(json, item)
|
||||
|
||||
def place_char_block(json: JSONMakerObject, char_block: LTCharBlock):
|
||||
json.string("type", 'char-block')
|
||||
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,39 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from ..interpreter import PDFInterpreter, PageInterpreter, logging
|
||||
from ..interpreter import LTCharBlock, 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,
|
||||
pagenos: List[int] = None,
|
||||
debug_level: int = logging.WARNING,
|
||||
):
|
||||
intepreter = PDFInterpreter(input_file_path,
|
||||
maxpages=maxpages,
|
||||
password=password,
|
||||
caching=caching,
|
||||
check_extractable=check_extractable,
|
||||
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, LTCharBlock):
|
||||
for char in item:
|
||||
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 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: 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 = " ".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, css: dict = None):
|
||||
with self.elm(tag_name, attrs, css, singleton=True):
|
||||
pass
|
||||
|
||||
@@ -1,129 +0,0 @@
|
||||
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()
|
||||
|
||||
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):
|
||||
self.write_prop(key, f'"{val}"')
|
||||
|
||||
@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):
|
||||
self.write_prop(f'"{val}"')
|
||||
|
||||
@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,142 +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, 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,
|
||||
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,
|
||||
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, LTCharBlock):
|
||||
place_char_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_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 })
|
||||
@@ -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
|
||||
@@ -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,127 +0,0 @@
|
||||
|
||||
import struct
|
||||
import os
|
||||
import os.path
|
||||
from io import BytesIO
|
||||
from ..interpreter.PDFStream import LITERALS_DCT_DECODE
|
||||
from ..interpreter.PDFColorSpace import LITERAL_DEVICE_GRAY
|
||||
from ..interpreter.PDFColorSpace import LITERAL_DEVICE_RGB
|
||||
from ..interpreter.PDFColorSpace import LITERAL_DEVICE_CMYK
|
||||
from ..layouts import LTImage
|
||||
|
||||
def align32(x):
|
||||
return ((x+3)//4)*4
|
||||
|
||||
## BMPWriter
|
||||
##
|
||||
class BMPWriter(object):
|
||||
|
||||
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
|
||||
|
||||
|
||||
## ImageWriter
|
||||
##
|
||||
class ImageWriter(object):
|
||||
|
||||
def __init__(self, outdir: str = None):
|
||||
if outdir is None:
|
||||
self.inactive = True
|
||||
else:
|
||||
self.inactive = False
|
||||
self.outdir = outdir
|
||||
if not os.path.exists(self.outdir):
|
||||
os.makedirs(self.outdir)
|
||||
|
||||
def export_image(self, image: LTImage) -> str:
|
||||
if self.inactive:
|
||||
return "N/A"
|
||||
|
||||
stream = image.stream
|
||||
filters = stream.get_filters()
|
||||
(width, height) = image.srcsize
|
||||
if len(filters) == 1 and filters[0][0] in LITERALS_DCT_DECODE:
|
||||
ext = '.jpg'
|
||||
elif (image.bits == 1 or
|
||||
image.bits == 8 and image.colorspace in (LITERAL_DEVICE_RGB, LITERAL_DEVICE_GRAY)):
|
||||
ext = '.%dx%d.bmp' % (width, height)
|
||||
else:
|
||||
ext = '.%d.%dx%d.img' % (image.bits, width, height)
|
||||
name = image.name+ext
|
||||
path = os.path.join(self.outdir, name)
|
||||
fp=open(path, 'wb')
|
||||
if ext == '.jpg':
|
||||
raw_data = stream.get_rawdata()
|
||||
if LITERAL_DEVICE_CMYK in image.colorspace:
|
||||
from PIL import Image
|
||||
from PIL import ImageChops
|
||||
ifp = BytesIO(raw_data)
|
||||
i = Image.open(ifp)
|
||||
i = ImageChops.invert(i)
|
||||
i = i.convert('RGB')
|
||||
i.save(fp, 'JPEG')
|
||||
else:
|
||||
fp.write(raw_data)
|
||||
elif image.bits == 1:
|
||||
bmp = BMPWriter(fp, 1, width, height)
|
||||
data = stream.get_data()
|
||||
i = 0
|
||||
width = (width+7)//8
|
||||
for y in range(height):
|
||||
bmp.write_line(y, data[i:i+width])
|
||||
i += width
|
||||
elif image.bits == 8 and image.colorspace is LITERAL_DEVICE_RGB:
|
||||
bmp = BMPWriter(fp, 24, width, height)
|
||||
data = stream.get_data()
|
||||
i = 0
|
||||
width = width*3
|
||||
for y in range(height):
|
||||
bmp.write_line(y, data[i:i+width])
|
||||
i += width
|
||||
elif image.bits == 8 and image.colorspace is LITERAL_DEVICE_GRAY:
|
||||
bmp = BMPWriter(fp, 8, width, height)
|
||||
data = stream.get_data()
|
||||
i = 0
|
||||
for y in range(height):
|
||||
bmp.write_line(y, data[i:i+width])
|
||||
i += width
|
||||
else:
|
||||
fp.write(stream.get_data())
|
||||
fp.close()
|
||||
return name
|
||||
@@ -1,82 +0,0 @@
|
||||
from pdfmajor.parser.PDFPage import PDFPage
|
||||
from pdfmajor.parser.PDFStream import list_value
|
||||
from pdfmajor.parser.PDFContentParser import PDFContentParser
|
||||
from pdfmajor.parser.PSStackParser import PSKeyword
|
||||
from pdfmajor.parser.PSStackParser import keyword_name
|
||||
|
||||
from .commands import PDFStateStack, PDFCommands
|
||||
from .commands import LTXObject
|
||||
from .utils import init_resources
|
||||
from .XObjectInterpreter import XObjectInterpreter
|
||||
|
||||
class PageInterpreter:
|
||||
class PDFInterpreterError(Exception): pass
|
||||
|
||||
def __init__(self, page: PDFPage, page_num: int, font_cache: dict = {}):
|
||||
(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
|
||||
self.page = page
|
||||
self.page_num = page_num
|
||||
self.height = y1-y0
|
||||
self.width = x1-x0
|
||||
|
||||
# Init State
|
||||
self.state: PDFStateStack = PDFStateStack()
|
||||
self.state.t_matrix = ctm
|
||||
self.state.resources = page.resources
|
||||
# set some global states.
|
||||
self.state.graphics.ncolspace = self.state.graphics.scolspace = None
|
||||
if self.state.colorspace_map:
|
||||
col_space = next(iter(self.state.colorspace_map.values()))
|
||||
self.state.graphics.ncolspace = self.state.graphics.scolspace = col_space
|
||||
# Init Resources
|
||||
init_resources(self.state, self.font_cache)
|
||||
|
||||
def __iter__(self):
|
||||
parser = PDFContentParser(list_value(self.page.contents))
|
||||
history = []
|
||||
for obj in parser:
|
||||
history.append(obj)
|
||||
if isinstance(obj, PSKeyword):
|
||||
name = keyword_name(obj)
|
||||
method = name.replace('*', '_a').replace('"', '_w').replace("'", '_q')
|
||||
if method in PDFCommands.commands.keys():
|
||||
func = PDFCommands.commands.get(method)
|
||||
nargs = func.__code__.co_argcount-1
|
||||
if nargs:
|
||||
args = self.state.pop(nargs)
|
||||
if len(args) == nargs:
|
||||
func(self.state, *args)
|
||||
else:
|
||||
raise self.PDFInterpreterError(f"Invalid Number of Args provided {method}")
|
||||
else:
|
||||
# log.debug('exec: %s', name)
|
||||
func(self.state)
|
||||
else:
|
||||
raise self.PDFInterpreterError('Unknown operator: %r' % name)
|
||||
else:
|
||||
self.state.argstack.append(obj)
|
||||
|
||||
for complete_item in self.state.complete_layout_items:
|
||||
if isinstance(complete_item, LTXObject):
|
||||
interpeter = XObjectInterpreter(
|
||||
streams=[complete_item.stream],
|
||||
resources=complete_item.resources,
|
||||
ctm=complete_item.t_matrix
|
||||
)
|
||||
for item in interpeter:
|
||||
complete_item.add(item)
|
||||
yield complete_item
|
||||
self.state.complete_layout_items = []
|
||||
def __repr__(self) -> str:
|
||||
return f"<Page:{self.page_num}/>"
|
||||
@@ -1,70 +0,0 @@
|
||||
from pdfmajor.utils import MATRIX_IDENTITY
|
||||
from pdfmajor.parser.PSStackParser import literal_name
|
||||
from pdfmajor.parser.PDFParser import PDFStream
|
||||
from pdfmajor.parser.PSStackParser import PSEOF
|
||||
from pdfmajor.parser.PSStackParser import PSKeyword
|
||||
from pdfmajor.parser.PSStackParser import keyword_name
|
||||
from pdfmajor.parser.PSStackParser import PSStackParser
|
||||
from pdfmajor.parser.constants import LITERAL_PDF, LITERAL_TEXT, LITERAL_FONT
|
||||
|
||||
from pdfmajor.parser.PDFStream import resolve1, list_value, dict_value
|
||||
from pdfmajor.parser.PDFStream.PDFObjRef import PDFObjRef
|
||||
from pdfmajor.parser.PDFContentParser import PDFContentParser
|
||||
|
||||
from .commands.state import PDFStateStack, PDFColorSpace, PREDEFINED_COLORSPACE
|
||||
from .commands import PDFCommands, LTXObject
|
||||
from .utils import init_resources
|
||||
|
||||
class XObjectInterpreter:
|
||||
|
||||
class PDFInterpreterError(Exception): pass
|
||||
|
||||
def __init__(self, streams, resources, ctm):
|
||||
self.streams = streams
|
||||
self.font_cache = {}
|
||||
|
||||
self.state = PDFStateStack()
|
||||
self.state.t_matrix = ctm
|
||||
self.state.resources = resources
|
||||
|
||||
# set some global states.
|
||||
self.state.graphics.ncolspace = self.state.graphics.scolspace = None
|
||||
if self.state.colorspace_map:
|
||||
col_space = next(iter(self.state.colorspace_map.values()))
|
||||
self.state.graphics.ncolspace = self.state.graphics.scolspace = col_space
|
||||
init_resources(self.state, self.font_cache)
|
||||
|
||||
def __iter__(self):
|
||||
parser = PDFContentParser(self.streams)
|
||||
for obj in parser:
|
||||
if isinstance(obj, PSKeyword):
|
||||
name = keyword_name(obj)
|
||||
method = name.replace('*', '_a').replace('"', '_w').replace("'", '_q')
|
||||
if method in PDFCommands.commands.keys():
|
||||
func = PDFCommands.commands.get(method)
|
||||
nargs = func.__code__.co_argcount-1
|
||||
if nargs:
|
||||
args = self.state.pop(nargs)
|
||||
if len(args) == nargs:
|
||||
func(self.state, *args)
|
||||
else:
|
||||
raise self.PDFInterpreterError(f"Invalid Number of Args provided {method}")
|
||||
else:
|
||||
# log.debug('exec: %s', name)
|
||||
func(self.state)
|
||||
else:
|
||||
raise self.PDFInterpreterError('Unknown operator: %r' % name)
|
||||
else:
|
||||
self.state.argstack.append(obj)
|
||||
|
||||
for complete_item in self.state.complete_layout_items:
|
||||
if isinstance(complete_item, LTXObject):
|
||||
interpeter = self.__class__(
|
||||
streams=[complete_item.stream],
|
||||
resources=complete_item.resources,
|
||||
ctm=complete_item.t_matrix
|
||||
)
|
||||
for item in interpeter:
|
||||
complete_item.add(item)
|
||||
yield complete_item
|
||||
self.state.complete_layout_items = []
|
||||
@@ -1,72 +0,0 @@
|
||||
from typing import List
|
||||
|
||||
from tqdm import tqdm
|
||||
|
||||
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 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,
|
||||
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.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 tqdm(enumerate(pages), desc="Reading pages...", disable=self.debug_level > logging.INFO):
|
||||
self.__pages.append(PageInterpreter(page, page_num, font_cache))
|
||||
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 tqdm(self.__pages, desc="Reading pages from store...", disable=self.debug_level > logging.INFO):
|
||||
yield page
|
||||
set_log_level(logging.WARNING)
|
||||
else:
|
||||
for page in self.__load_pages():
|
||||
yield page
|
||||
@@ -1,30 +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 PDFCommands:
|
||||
commands = {}
|
||||
class InvalidOperation(Exception): pass
|
||||
class RepeatedCommand(Exception): pass
|
||||
|
||||
@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 cls.RepeatedCommand(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,9 +0,0 @@
|
||||
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 LTCharBlock, LTChar
|
||||
from .state import LTCurve, LTLine, LTHorizontalLine, LTVerticalLine, LTRect
|
||||
from .state import LTImage
|
||||
from .state import LTXObject
|
||||
from .state import LTItem, LTComponent, LTContainer
|
||||
@@ -1,486 +0,0 @@
|
||||
from pdfmajor.utils import mult_matrix, MATRIX_IDENTITY, apply_matrix_pt
|
||||
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
|
||||
from .state import PDFStateStack, PDFGraphicState
|
||||
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
|
||||
|
||||
# No Support
|
||||
@PDFCommands.add('W','W_a', 'sh', 'ET', 'BX', 'EX' ,'BI', 'ID', 'gs')
|
||||
def do_no_support(stack: PDFStateStack) -> PDFStateStack:
|
||||
return stack
|
||||
|
||||
# marked content operators
|
||||
@PDFCommands.add('MP', 'DP')
|
||||
def do_MP(stack: PDFStateStack) -> PDFStateStack:
|
||||
# self.device.do_tag(tag)
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('BMC', 'BDC')
|
||||
def do_BMC(stack: PDFStateStack) -> PDFStateStack:
|
||||
# self.device.begin_tag(tag)
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('EMC')
|
||||
def do_EMC(stack: PDFStateStack) -> PDFStateStack:
|
||||
# self.device.end_tag(tag)
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('q')
|
||||
def do_q(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.gstack.append([
|
||||
stack.t_matrix,
|
||||
stack.text.copy(),
|
||||
stack.graphics.copy()
|
||||
])
|
||||
return stack
|
||||
|
||||
@PDFCommands.add('Q')
|
||||
def do_Q(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 do_cm(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 do_w(stack: PDFStateStack, linewidth) -> PDFStateStack:
|
||||
stack.graphics.linewidth = linewidth
|
||||
return stack
|
||||
|
||||
# setlinecap
|
||||
@PDFCommands.add('J')
|
||||
def do_J(stack: PDFStateStack, linecap) -> PDFStateStack:
|
||||
stack.graphics.linecap = linecap
|
||||
return stack
|
||||
|
||||
# setlinejoin
|
||||
@PDFCommands.add('j')
|
||||
def do_j(stack: PDFStateStack, linejoin) -> PDFStateStack:
|
||||
stack.graphics.linejoin = linejoin
|
||||
return stack
|
||||
|
||||
# setmiterlimit
|
||||
@PDFCommands.add('M')
|
||||
def do_M(stack: PDFStateStack, miterlimit) -> PDFStateStack:
|
||||
stack.graphics.miterlimit = miterlimit
|
||||
return stack
|
||||
|
||||
# setdash
|
||||
@PDFCommands.add('d')
|
||||
def do_d(stack: PDFStateStack, dash, phase) -> PDFStateStack:
|
||||
stack.graphics.dash = (dash, phase)
|
||||
return stack
|
||||
|
||||
# setintent
|
||||
@PDFCommands.add('ri')
|
||||
def do_ri(stack: PDFStateStack, intent) -> PDFStateStack:
|
||||
stack.graphics.intent = intent
|
||||
return stack
|
||||
|
||||
# setflatness
|
||||
@PDFCommands.add('i')
|
||||
def do_i(stack: PDFStateStack, flatness) -> PDFStateStack:
|
||||
stack.graphics.flatness = flatness
|
||||
return stack
|
||||
|
||||
# moveto
|
||||
@PDFCommands.add('m')
|
||||
def do_m(stack: PDFStateStack, x: float, y: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.MOVE_TO,
|
||||
CurvePoint(x, y)
|
||||
))
|
||||
return stack
|
||||
|
||||
# lineto
|
||||
@PDFCommands.add('l')
|
||||
def do_l(stack: PDFStateStack, x: float, y: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.LINE_TO,
|
||||
CurvePoint(x, y)
|
||||
))
|
||||
return stack
|
||||
|
||||
# curveto
|
||||
@PDFCommands.add('c')
|
||||
def do_c(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(x1, y1),
|
||||
CurvePoint(x2, y2),
|
||||
CurvePoint(x3, y3),
|
||||
))
|
||||
return stack
|
||||
|
||||
# urveto
|
||||
@PDFCommands.add('v')
|
||||
def do_v(stack: PDFStateStack,
|
||||
x2: float, y2: float,
|
||||
x3: float, y3: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CURVE_NEXT_TO,
|
||||
CurvePoint(x2, y2),
|
||||
CurvePoint(x3, y3),
|
||||
))
|
||||
return stack
|
||||
|
||||
# rveto
|
||||
@PDFCommands.add('y')
|
||||
def do_y(stack: PDFStateStack,
|
||||
x1: float, y1: float,
|
||||
x3: float, y3: float) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(
|
||||
CurvePath.METHOD.CURVE_FIRST_TO,
|
||||
CurvePoint(x1, y1),
|
||||
CurvePoint(x3, y3)
|
||||
))
|
||||
return stack
|
||||
|
||||
# closepath
|
||||
@PDFCommands.add('h')
|
||||
def do_h(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks.append(CurvePath(CurvePath.METHOD.CLOSE_PATH))
|
||||
return stack
|
||||
|
||||
# rectangle
|
||||
@PDFCommands.add('re')
|
||||
def do_re(stack: PDFStateStack, x, y, w, h) -> PDFStateStack:
|
||||
stack.curvestacks.extend([
|
||||
CurvePath(CurvePath.METHOD.MOVE_TO, CurvePoint(x, y) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(x+w, y) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(x+w, y+h) ),
|
||||
CurvePath(CurvePath.METHOD.LINE_TO, CurvePoint(x, y+h) ),
|
||||
CurvePath(CurvePath.METHOD.CLOSE_PATH)
|
||||
])
|
||||
return stack
|
||||
|
||||
# stroke, fill
|
||||
@PDFCommands.add('S', 'f', 'F', 'B')
|
||||
def do_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 do_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 do_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 do_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 do_n(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.curvestacks = []
|
||||
return stack
|
||||
|
||||
|
||||
# setcolorspace-stroking
|
||||
@PDFCommands.add('CS')
|
||||
def do_CS(stack: PDFStateStack, name: str) -> PDFStateStack:
|
||||
try:
|
||||
stack.graphics.scolspace = stack.colorspace_map[literal_name(name)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommands.InvalidOperation('Undefined ColorSpace: %r' % name)
|
||||
|
||||
# setcolorspace-non-strokine
|
||||
@PDFCommands.add('cs')
|
||||
def do_cs(stack: PDFStateStack, name: str) -> PDFStateStack:
|
||||
try:
|
||||
stack.graphics.ncolspace = stack.colorspace_map[literal_name(name)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommands.InvalidOperation('Undefined ColorSpace: %r' % name)
|
||||
|
||||
# setgray-stroking
|
||||
@PDFCommands.add('G')
|
||||
def do_G(stack: PDFStateStack, gray: float) -> PDFStateStack:
|
||||
stack.graphics.set_stroke_color(
|
||||
stack.colorspace_map['DeviceGray'],
|
||||
gray
|
||||
)
|
||||
return stack
|
||||
|
||||
# setgray-non-stroking
|
||||
@PDFCommands.add('g')
|
||||
def do_g(stack: PDFStateStack, gray: float) -> PDFStateStack:
|
||||
stack.graphics.set_nostroke_color(
|
||||
stack.colorspace_map['DeviceGray'],
|
||||
gray
|
||||
)
|
||||
return stack
|
||||
|
||||
|
||||
# setrgb-stroking
|
||||
@PDFCommands.add('RG')
|
||||
def do_RG(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 do_rg(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 do_K(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 do_k(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 do_SCN(stack: PDFStateStack) -> PDFStateStack:
|
||||
if stack.graphics.scolspace is None:
|
||||
raise PDFCommands.InvalidOperation('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 do_scn(stack: PDFStateStack) -> PDFStateStack:
|
||||
if stack.graphics.ncolspace is None:
|
||||
raise PDFCommands.InvalidOperation('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 do_BT(stack: PDFStateStack) -> PDFStateStack:
|
||||
stack.text.matrix = MATRIX_IDENTITY
|
||||
stack.text.linematrix = [0, 0]
|
||||
return stack
|
||||
|
||||
# setcharspace
|
||||
@PDFCommands.add('Tc')
|
||||
def do_Tc(stack: PDFStateStack, charspace) -> PDFStateStack:
|
||||
stack.text.charspace = charspace
|
||||
return stack
|
||||
|
||||
# setwordspace
|
||||
@PDFCommands.add('Tw')
|
||||
def do_Tw(stack: PDFStateStack, wordspace) -> PDFStateStack:
|
||||
stack.text.wordspace = wordspace
|
||||
return stack
|
||||
|
||||
# textscale
|
||||
@PDFCommands.add('Tz')
|
||||
def do_Tz(stack: PDFStateStack, scaling) -> PDFStateStack:
|
||||
stack.text.scaling = scaling
|
||||
return stack
|
||||
|
||||
# setleading
|
||||
@PDFCommands.add('TL')
|
||||
def do_TL(stack: PDFStateStack, leading) -> PDFStateStack:
|
||||
stack.text.leading = -leading
|
||||
return stack
|
||||
|
||||
# selectfont
|
||||
@PDFCommands.add('Tf')
|
||||
def do_Tf(stack: PDFStateStack, fontid, fontsize) -> PDFStateStack:
|
||||
stack.text.fontsize = fontsize
|
||||
try:
|
||||
stack.text.font = stack.fontmap[literal_name(fontid)]
|
||||
return stack
|
||||
except KeyError:
|
||||
raise PDFCommands.InvalidOperation('Undefined Font id: %r' % fontid)
|
||||
|
||||
# setrendering
|
||||
@PDFCommands.add('Tr')
|
||||
def do_Tr(stack: PDFStateStack, render) -> PDFStateStack:
|
||||
stack.text.render = render
|
||||
return stack
|
||||
|
||||
# settextrise
|
||||
@PDFCommands.add('Ts')
|
||||
def do_Ts(stack: PDFStateStack, rise) -> PDFStateStack:
|
||||
stack.text.rise = rise
|
||||
return stack
|
||||
|
||||
# text-move
|
||||
@PDFCommands.add('Td')
|
||||
def do_Td(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 do_TD(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 do_Tm(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 do_T_a(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 do_TJ(stack: PDFStateStack, seq: bytearray) -> PDFStateStack:
|
||||
if stack.text.font is None:
|
||||
raise PDFCommands.InvalidOperation("No Font Specified")
|
||||
stack.complete_layout_items.append(make_char_block(
|
||||
seq,
|
||||
stack.t_matrix,
|
||||
stack.text.copy(),
|
||||
stack.graphics.ncolor.copy()
|
||||
))
|
||||
return stack
|
||||
|
||||
# show
|
||||
@PDFCommands.add('Tj')
|
||||
def do_Tj(stack: PDFStateStack, b: bytes) -> PDFStateStack:
|
||||
return do_TJ(stack, [b])
|
||||
|
||||
# quote
|
||||
@PDFCommands.add('_q')
|
||||
def do__q(stack: PDFStateStack, b: bytes) -> PDFStateStack:
|
||||
return do_TJ(do_T_a(stack), [b])
|
||||
|
||||
# doublequote
|
||||
@PDFCommands.add('_w')
|
||||
def do__w(stack: PDFStateStack, wordspace, charspace, b) -> PDFStateStack:
|
||||
stack.text.wordspace = wordspace
|
||||
stack.text.charspace = charspace
|
||||
return do_TJ(stack, [b])
|
||||
|
||||
@PDFCommands.add('EI')
|
||||
def do_EI(stack: PDFStateStack, obj) -> PDFStateStack:
|
||||
if 'W' in obj and 'H' in obj:
|
||||
stack.complete_layout_items.append(make_image(
|
||||
obj, stack.ctm
|
||||
))
|
||||
return stack
|
||||
|
||||
# invoke an XObject
|
||||
@PDFCommands.add('Do')
|
||||
def do_Do(stack: PDFStateStack, xobjid) -> PDFStateStack:
|
||||
xobjid = literal_name(xobjid)
|
||||
try:
|
||||
xobj = PDFStream.validated_stream(stack.xobjmap[xobjid])
|
||||
except KeyError:
|
||||
raise PDFCommands.InvalidOperation('Undefined xobject id: %r' % xobjid)
|
||||
# log.info('Processing xobj: %r', xobj)
|
||||
subtype = xobj.get('Subtype')
|
||||
if subtype is LITERAL_FORM and 'BBox' in xobj:
|
||||
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,27 +0,0 @@
|
||||
from enum import Enum
|
||||
from typing import List
|
||||
|
||||
class CurvePoint:
|
||||
def __init__(self, x: float, y: float):
|
||||
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,16 +0,0 @@
|
||||
from typing import List
|
||||
from .PDFColorSpace import PDFColorSpace
|
||||
|
||||
class PDFColor:
|
||||
def __init__(self, color_space: PDFColorSpace, *values: List[float]):
|
||||
self.color_space: PDFColorSpace = color_space
|
||||
self.values: list = values
|
||||
|
||||
def copy(self):
|
||||
return self.__class__(
|
||||
self.color_space,
|
||||
*self.values
|
||||
)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<PDFColor space={self.color_space} values={self.values}/>"
|
||||
@@ -1,27 +0,0 @@
|
||||
from collections import OrderedDict
|
||||
|
||||
class PDFColorSpace(object):
|
||||
|
||||
def __init__(self, name: str, ncomponents: int):
|
||||
self.name: str = name
|
||||
self.ncomponents: int = ncomponents
|
||||
return
|
||||
|
||||
def __repr__(self):
|
||||
return '<PDFColorSpace: %s, ncomponents=%d>' % (self.name, self.ncomponents)
|
||||
|
||||
|
||||
PREDEFINED_COLORSPACE = 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,55 +0,0 @@
|
||||
from .PDFColor import PDFColor, PDFColorSpace
|
||||
from .PDFColorSpace import PREDEFINED_COLORSPACE
|
||||
|
||||
class PDFGraphicState(object):
|
||||
class InvalidOperation(Exception): pass
|
||||
|
||||
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.font.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.font.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,140 +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 PDFException
|
||||
from pdfmajor.parser.PDFStream import PDFStream
|
||||
from pdfmajor.parser.cmapdb import FileUnicodeMap
|
||||
from pdfmajor.parser.cmapdb import CMapParser
|
||||
|
||||
## Literals
|
||||
##
|
||||
LITERAL_STANDARD_ENCODING = LIT('StandardEncoding')
|
||||
LITERAL_TYPE1C = LIT('Type1C')
|
||||
|
||||
|
||||
class PDFFont(object):
|
||||
class PDFFontError(PDFException): pass
|
||||
class PDFUnicodeNotDefined(PDFFontError): pass
|
||||
|
||||
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, self.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 self.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,57 +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 .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 PDFFont.PDFFontError('Type is not /Font')
|
||||
# Create a Font object.
|
||||
if 'Subtype' in spec:
|
||||
subtype = literal_name(spec['Subtype'])
|
||||
else:
|
||||
if settings.STRICT:
|
||||
raise PDFFont.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 PDFFont.PDFFontError('Invalid Font spec: %r' % spec)
|
||||
font = PDFType1Font(spec) # this is so wrong!
|
||||
if objid:
|
||||
cached_fonts[objid] = font
|
||||
return font
|
||||
|
||||
|
||||
|
||||
@@ -1,174 +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
|
||||
|
||||
# PDFType1Font
|
||||
class PDFType1Font(PDFSimpleFont):
|
||||
|
||||
def __init__(self, spec):
|
||||
try:
|
||||
self.basefont = literal_name(spec['BaseFont'])
|
||||
except KeyError:
|
||||
if settings.STRICT:
|
||||
raise self.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 self.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 self.PDFFontError('Encoding is unspecified')
|
||||
name = 'unknown'
|
||||
try:
|
||||
self.cmap = CMapDB.get_cmap(name)
|
||||
except CMapDB.CMapNotFound as e:
|
||||
if strict:
|
||||
raise self.PDFFontError(e)
|
||||
self.cmap = CMap()
|
||||
try:
|
||||
descriptor = dict_value(spec['FontDescriptor'])
|
||||
except KeyError:
|
||||
if strict:
|
||||
raise self.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 self.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,48 +0,0 @@
|
||||
from .PDFFont import PDFFont, get_font
|
||||
from pdfmajor.utils import MATRIX_IDENTITY
|
||||
|
||||
## 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]
|
||||
|
||||
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>' %
|
||||
(self.font, self.fontsize, self.charspace, self.wordspace,
|
||||
self.scaling, self.leading, self.render, self.rise,
|
||||
self.matrix, self.linematrix))
|
||||
|
||||
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
|
||||
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,39 +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 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 = {}
|
||||
|
||||
def pop(self, n: int) -> bytearray:
|
||||
if n == 0:
|
||||
return []
|
||||
x = self.argstack[-n:]
|
||||
self.argstack = self.argstack[:-n]
|
||||
return x
|
||||
Loaded 100 of 231 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user