pdf2pdfa 0.1.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- pdf2pdfa/__init__.py +7 -0
- pdf2pdfa/cli.py +34 -0
- pdf2pdfa/converter.py +200 -0
- pdf2pdfa/data/sRGB.icc.b64 +122 -0
- pdf2pdfa/fonts.py +98 -0
- pdf2pdfa/icc.py +53 -0
- pdf2pdfa/metadata.py +59 -0
- pdf2pdfa-0.1.0.dist-info/METADATA +96 -0
- pdf2pdfa-0.1.0.dist-info/RECORD +13 -0
- pdf2pdfa-0.1.0.dist-info/WHEEL +5 -0
- pdf2pdfa-0.1.0.dist-info/entry_points.txt +2 -0
- pdf2pdfa-0.1.0.dist-info/licenses/LICENSE +25 -0
- pdf2pdfa-0.1.0.dist-info/top_level.txt +1 -0
pdf2pdfa/__init__.py
ADDED
pdf2pdfa/cli.py
ADDED
|
@@ -0,0 +1,34 @@
|
|
|
1
|
+
"""Command line interface for pdf2pdfa."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import click
|
|
9
|
+
|
|
10
|
+
from .converter import Converter
|
|
11
|
+
|
|
12
|
+
logging.basicConfig(level=logging.INFO)
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
@click.group()
|
|
17
|
+
def cli() -> None:
|
|
18
|
+
"""pdf2pdfa CLI"""
|
|
19
|
+
|
|
20
|
+
|
|
21
|
+
@cli.command()
|
|
22
|
+
@click.argument('input', type=click.Path(exists=True))
|
|
23
|
+
@click.argument('output', type=click.Path())
|
|
24
|
+
@click.option('--icc', type=click.Path(), default=None, help='Path to ICC profile')
|
|
25
|
+
def convert(input: str, output: str, icc: str) -> None:
|
|
26
|
+
"""Convert INPUT PDF to PDF/A-1b OUTPUT."""
|
|
27
|
+
conv = Converter(icc_path=icc)
|
|
28
|
+
conv.convert(input, output)
|
|
29
|
+
click.echo(f'Converted {input} \u2192 {output} as PDF/A-1b')
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
if __name__ == '__main__':
|
|
33
|
+
cli()
|
|
34
|
+
|
pdf2pdfa/converter.py
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
"""PDF/A-1b conversion logic."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
import datetime as dt
|
|
7
|
+
import sys
|
|
8
|
+
import os
|
|
9
|
+
from typing import Optional
|
|
10
|
+
|
|
11
|
+
try:
|
|
12
|
+
from importlib.resources import files
|
|
13
|
+
except ImportError: # Python <3.9
|
|
14
|
+
from importlib_resources import files
|
|
15
|
+
import pikepdf
|
|
16
|
+
from pikepdf import Pdf, Name, Dictionary, Array, String
|
|
17
|
+
|
|
18
|
+
from reportlab.pdfbase import pdfmetrics
|
|
19
|
+
from reportlab.pdfbase.ttfonts import TTFont
|
|
20
|
+
|
|
21
|
+
from .fonts import subset_and_embed_fonts
|
|
22
|
+
from .icc import embed_icc_profile
|
|
23
|
+
|
|
24
|
+
logger = logging.getLogger(__name__)
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
class Converter:
|
|
28
|
+
"""Convert arbitrary PDF to PDF/A-1b."""
|
|
29
|
+
|
|
30
|
+
def __init__(self, icc_path: Optional[str] = None) -> None:
|
|
31
|
+
if icc_path is not None:
|
|
32
|
+
self.icc_path = icc_path
|
|
33
|
+
else:
|
|
34
|
+
self.icc_path = str(files(__package__).joinpath('data/sRGB.icc.b64'))
|
|
35
|
+
logger.debug("Using ICC profile at %s", self.icc_path)
|
|
36
|
+
|
|
37
|
+
def convert(
|
|
38
|
+
self,
|
|
39
|
+
input_path: str,
|
|
40
|
+
output_path: str,
|
|
41
|
+
icc_profile: Optional[str] = None,
|
|
42
|
+
font_path: Optional[str] = None,
|
|
43
|
+
) -> None:
|
|
44
|
+
"""Convert *input_path* to PDF/A-1b and save as *output_path*.
|
|
45
|
+
|
|
46
|
+
Parameters
|
|
47
|
+
----------
|
|
48
|
+
input_path:
|
|
49
|
+
Source PDF file.
|
|
50
|
+
output_path:
|
|
51
|
+
Destination path for the PDF/A-1b file.
|
|
52
|
+
icc_profile:
|
|
53
|
+
Optional path to an ICC profile. If ``None`` the converter's
|
|
54
|
+
default sRGB profile is used.
|
|
55
|
+
font_path:
|
|
56
|
+
Optional path to a TrueType or OpenType font to embed when fonts
|
|
57
|
+
are missing from the source document.
|
|
58
|
+
"""
|
|
59
|
+
|
|
60
|
+
logger.info("Converting %s -> %s", input_path, output_path)
|
|
61
|
+
|
|
62
|
+
# ------------------------------------------------------------------
|
|
63
|
+
# Open the input PDF
|
|
64
|
+
# ------------------------------------------------------------------
|
|
65
|
+
try:
|
|
66
|
+
pdf = Pdf.open(input_path)
|
|
67
|
+
except Exception as exc:
|
|
68
|
+
logger.error("Failed to open PDF %s: %s", input_path, exc)
|
|
69
|
+
raise
|
|
70
|
+
|
|
71
|
+
# ------------------------------------------------------------------
|
|
72
|
+
# Determine a font to embed for missing resources
|
|
73
|
+
# ------------------------------------------------------------------
|
|
74
|
+
font_file = font_path
|
|
75
|
+
if font_file is None:
|
|
76
|
+
search: list[str]
|
|
77
|
+
if sys.platform.startswith("win"):
|
|
78
|
+
search = [
|
|
79
|
+
r"C:\\Windows\\Fonts\\arial.ttf",
|
|
80
|
+
r"C:\\Windows\\Fonts\\Arial.ttf",
|
|
81
|
+
]
|
|
82
|
+
elif sys.platform == "darwin":
|
|
83
|
+
search = [
|
|
84
|
+
"/System/Library/Fonts/Supplemental/Arial.ttf",
|
|
85
|
+
"/Library/Fonts/Arial.ttf",
|
|
86
|
+
]
|
|
87
|
+
else:
|
|
88
|
+
search = [
|
|
89
|
+
"/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf",
|
|
90
|
+
"/usr/share/fonts/truetype/liberation/LiberationSans-Regular.ttf",
|
|
91
|
+
]
|
|
92
|
+
for candidate in search:
|
|
93
|
+
if os.path.isfile(candidate):
|
|
94
|
+
font_file = candidate
|
|
95
|
+
break
|
|
96
|
+
|
|
97
|
+
if font_file and os.path.isfile(font_file):
|
|
98
|
+
logger.debug("Embedding fonts using %s", font_file)
|
|
99
|
+
try:
|
|
100
|
+
# Register with reportlab so fonttools can locate tables
|
|
101
|
+
pdfmetrics.registerFont(TTFont("embed", font_file))
|
|
102
|
+
except Exception:
|
|
103
|
+
pass # registration failure is non-fatal
|
|
104
|
+
subset_and_embed_fonts(pdf, font_file)
|
|
105
|
+
else:
|
|
106
|
+
logger.warning(
|
|
107
|
+
"No valid font found for embedding; fonts may remain unembedded"
|
|
108
|
+
)
|
|
109
|
+
|
|
110
|
+
# ------------------------------------------------------------------
|
|
111
|
+
# Embed ICC profile as OutputIntent
|
|
112
|
+
# ------------------------------------------------------------------
|
|
113
|
+
profile = icc_profile or self.icc_path
|
|
114
|
+
try:
|
|
115
|
+
embed_icc_profile(pdf, profile)
|
|
116
|
+
except FileNotFoundError as exc:
|
|
117
|
+
logger.error("ICC profile not found: %s", profile)
|
|
118
|
+
raise
|
|
119
|
+
|
|
120
|
+
# ------------------------------------------------------------------
|
|
121
|
+
# Set up document dates
|
|
122
|
+
# ------------------------------------------------------------------
|
|
123
|
+
now = dt.datetime.now(dt.timezone.utc).replace(microsecond=0)
|
|
124
|
+
xmp_date = now.isoformat()
|
|
125
|
+
|
|
126
|
+
# ------------------------------------------------------------------
|
|
127
|
+
# Existing info dictionary values
|
|
128
|
+
# ------------------------------------------------------------------
|
|
129
|
+
info = pdf.docinfo or Dictionary()
|
|
130
|
+
title = str(info.get(Name.Title, ""))
|
|
131
|
+
author = str(info.get(Name.Author, ""))
|
|
132
|
+
subject = str(info.get(Name.Subject, ""))
|
|
133
|
+
keywords = str(info.get(Name.Keywords, ""))
|
|
134
|
+
|
|
135
|
+
# ------------------------------------------------------------------
|
|
136
|
+
# Update XMP metadata
|
|
137
|
+
# ------------------------------------------------------------------
|
|
138
|
+
meta_ctx = pdf.open_metadata(set_pikepdf_as_editor=True)
|
|
139
|
+
|
|
140
|
+
# pikepdf will sync metadata from XMP to the document info dictionary on
|
|
141
|
+
# save. When metadata is opened with ``set_pikepdf_as_editor=True`` any
|
|
142
|
+
# direct edits to ``pdf.docinfo`` are ignored and raise warnings.
|
|
143
|
+
# Therefore all fields are written only through the XMP object.
|
|
144
|
+
with meta_ctx as md:
|
|
145
|
+
md["pdfaid:part"] = "1"
|
|
146
|
+
md["pdfaid:conformance"] = "B"
|
|
147
|
+
md["dc:format"] = "application/pdf"
|
|
148
|
+
if title:
|
|
149
|
+
md["dc:title"] = title
|
|
150
|
+
if author:
|
|
151
|
+
md["dc:creator"] = [author]
|
|
152
|
+
if subject:
|
|
153
|
+
md["dc:description"] = subject
|
|
154
|
+
if keywords:
|
|
155
|
+
md["pdf:Keywords"] = keywords
|
|
156
|
+
md["xmp:CreatorTool"] = "pdf2pdfa"
|
|
157
|
+
md["xmp:CreateDate"] = xmp_date
|
|
158
|
+
md["xmp:ModifyDate"] = xmp_date
|
|
159
|
+
|
|
160
|
+
# Reopen metadata without pikepdf injection to set Producer; doing this
|
|
161
|
+
# separately avoids warnings about the field being overwritten.
|
|
162
|
+
with pdf.open_metadata(set_pikepdf_as_editor=False) as md:
|
|
163
|
+
md["pdf:Producer"] = f"pikepdf {pikepdf.__version__} (pdf2pdfa)"
|
|
164
|
+
|
|
165
|
+
# ------------------------------------------------------------------
|
|
166
|
+
# Do not update ``pdf.docinfo`` directly when ``set_pikepdf_as_editor``
|
|
167
|
+
# is used. PikePDF will sync values from XMP on save and warns if we
|
|
168
|
+
# modify docinfo here, because any changes would be overwritten.
|
|
169
|
+
# ------------------------------------------------------------------
|
|
170
|
+
|
|
171
|
+
|
|
172
|
+
|
|
173
|
+
# ------------------------------------------------------------------
|
|
174
|
+
# Save PDF/A
|
|
175
|
+
# ------------------------------------------------------------------
|
|
176
|
+
try:
|
|
177
|
+
try:
|
|
178
|
+
pdf.save(output_path, optimize_version=True)
|
|
179
|
+
except TypeError:
|
|
180
|
+
# Older pikepdf versions do not support optimize_version
|
|
181
|
+
pdf.save(output_path)
|
|
182
|
+
except Exception as exc:
|
|
183
|
+
logger.error("Failed to save PDF %s: %s", output_path, exc)
|
|
184
|
+
raise
|
|
185
|
+
logger.info("Saved PDF/A-1b to %s", output_path)
|
|
186
|
+
|
|
187
|
+
# ------------------------------------------------------------------
|
|
188
|
+
# Verify that XMP and docinfo are in sync
|
|
189
|
+
# ------------------------------------------------------------------
|
|
190
|
+
with Pdf.open(output_path) as out_pdf:
|
|
191
|
+
with out_pdf.open_metadata() as md:
|
|
192
|
+
info = out_pdf.docinfo
|
|
193
|
+
title_md = md.get("dc:title")
|
|
194
|
+
assert str(info.get(Name.Title, "")) == str(title_md or "")
|
|
195
|
+
creators = md.get("dc:creator", [])
|
|
196
|
+
if creators:
|
|
197
|
+
assert str(info.get(Name.Author, "")) == creators[0]
|
|
198
|
+
descr_md = md.get("dc:description")
|
|
199
|
+
assert str(info.get(Name.Subject, "")) == str(descr_md or "")
|
|
200
|
+
|
|
@@ -0,0 +1,122 @@
|
|
|
1
|
+
AAAbCmxjbXMCMAAAbW50clJHQiBYWVogB9QACAANAAwAEgAGYWNzcE1TRlQAAAAAbGNtcwAAAAAA
|
|
2
|
+
AAAAAAAAAAAAAAAAAPbWAAEAAAAA0y1sY21zAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA
|
|
3
|
+
AAAAAAAAAAAAAAAAAAAAAAAMZG1uZAAAARQAAABqZGVzYwAAAYAAAABoZG1kZAAAAegAAABod3Rw
|
|
4
|
+
dAAAAlAAAAAUclhZWgAAAmQAAAAUYlhZWgAAAngAAAAUZ1hZWgAAAowAAAAUclRSQwAAAqAAAAgM
|
|
5
|
+
Z1RSQwAACqwAAAgMYlRSQwAAErgAAAgMY2hybQAAGsQAAAAkY3BydAAAGugAAAAhZGVzYwAAAAAA
|
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LCsziz
|
|
116
|
+
rrQltJy1E7WKtgG2ebbwt2i34LhZuNG5SrnCuju6tbsuu6e8IbybvRW9j74KvoS+/796v/XAcMDs
|
|
117
|
+
wWfB48JfwtvDWMPUxFHEzsVLxcjGRsbDx0HHv8g9yLzJOsm5yjjKt8s2y7bMNcy1zTXNtc42zrbP
|
|
118
|
+
N8+40DnQutE80b7SP9LB00TTxtRJ1MvVTtXR1lXW2Ndc1+DYZNjo2WzZ8dp22vvbgNwF3IrdEN2W
|
|
119
|
+
3hzeot8p36/gNuC94UThzOJT4tvjY+Pr5HPk/OWE5g3mlucf56noMui86Ubp0Opb6uXrcOv77Ibt
|
|
120
|
+
Ee2c7ijutO9A78zwWPDl8XLx//KM8xnzp/Q09ML1UPXe9m32+/eK+Bn4qPk4+cf6V/rn+3f8B/yY
|
|
121
|
+
/Sn9uv5L/tz/bf//Y2hybQAAAAAAAwAAAACj1wAAVHsAAEzNAACZmgAAJmYAAA9cdGV4dAAAAABu
|
|
122
|
+
byBjb3B5cmlnaHQsIHVzZSBmcmVlbHkACg==
|
pdf2pdfa/fonts.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
1
|
+
"""Font subsetting and embedding utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import logging
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Iterable
|
|
8
|
+
|
|
9
|
+
from fontTools import subset
|
|
10
|
+
from fontTools.ttLib import TTFont
|
|
11
|
+
from pikepdf import Pdf, Name, Dictionary, Array
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
DEFAULT_FONT_PATH = "/usr/share/fonts/truetype/dejavu/DejaVuSans.ttf"
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
def _extract_metrics(tt: TTFont) -> dict[str, object]:
|
|
20
|
+
"""Return metrics for *tt* scaled to 1000 units."""
|
|
21
|
+
upem = tt['head'].unitsPerEm
|
|
22
|
+
ascent = tt['hhea'].ascent
|
|
23
|
+
descent = tt['hhea'].descent
|
|
24
|
+
bbox = [tt['head'].xMin, tt['head'].yMin, tt['head'].xMax, tt['head'].yMax]
|
|
25
|
+
os2 = tt['OS/2'] if 'OS/2' in tt else None
|
|
26
|
+
cap_height = getattr(os2, 'sCapHeight', ascent)
|
|
27
|
+
italic_angle = tt['post'].italicAngle
|
|
28
|
+
widths = []
|
|
29
|
+
cmap = tt.getBestCmap()
|
|
30
|
+
hmtx = tt['hmtx'].metrics
|
|
31
|
+
for code in range(32, 256):
|
|
32
|
+
gname = cmap.get(code, '.notdef')
|
|
33
|
+
adv = hmtx.get(gname, hmtx.get('.notdef'))[0]
|
|
34
|
+
widths.append(int(round(adv * 1000 / upem)))
|
|
35
|
+
return {
|
|
36
|
+
'bbox': [int(round(v * 1000 / upem)) for v in bbox],
|
|
37
|
+
'ascent': int(round(ascent * 1000 / upem)),
|
|
38
|
+
'descent': int(round(descent * 1000 / upem)),
|
|
39
|
+
'cap_height': int(round(cap_height * 1000 / upem)),
|
|
40
|
+
'italic_angle': italic_angle,
|
|
41
|
+
'widths': widths,
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def subset_and_embed_fonts(pdf: Pdf, font_path: str = DEFAULT_FONT_PATH) -> None:
|
|
46
|
+
"""Embed all fonts used in *pdf*.
|
|
47
|
+
|
|
48
|
+
Fonts already embedded are left untouched. For fonts that are missing, a
|
|
49
|
+
generic TrueType font is embedded so that the resulting document contains
|
|
50
|
+
embedded font programs for all resources. This implementation is intentionally
|
|
51
|
+
simple and primarily intended for test documents.
|
|
52
|
+
"""
|
|
53
|
+
|
|
54
|
+
logger.debug("Embedding fonts using %s", font_path)
|
|
55
|
+
|
|
56
|
+
path = Path(font_path)
|
|
57
|
+
if not path.is_file():
|
|
58
|
+
logger.warning("Font file %s not found; fonts may remain unembedded", font_path)
|
|
59
|
+
return
|
|
60
|
+
|
|
61
|
+
font_data = path.read_bytes()
|
|
62
|
+
metrics = _extract_metrics(TTFont(str(path)))
|
|
63
|
+
|
|
64
|
+
for page in pdf.pages:
|
|
65
|
+
fonts = page.Resources.get('/Font')
|
|
66
|
+
if not fonts:
|
|
67
|
+
continue
|
|
68
|
+
for name in list(fonts.keys()):
|
|
69
|
+
font = fonts[name]
|
|
70
|
+
descriptor = font.get('/FontDescriptor')
|
|
71
|
+
if descriptor and any(k in descriptor for k in ('/FontFile', '/FontFile2', '/FontFile3')):
|
|
72
|
+
logger.debug("Font %s already embedded", descriptor.get('/FontName'))
|
|
73
|
+
continue
|
|
74
|
+
|
|
75
|
+
logger.debug("Embedding missing font %s", font.get('/BaseFont'))
|
|
76
|
+
stream = pdf.make_stream(font_data)
|
|
77
|
+
desc = Dictionary(
|
|
78
|
+
{
|
|
79
|
+
'/Type': Name('/FontDescriptor'),
|
|
80
|
+
'/FontName': font.get('/BaseFont', Name('/DejaVuSans')),
|
|
81
|
+
'/Flags': 32,
|
|
82
|
+
'/FontBBox': Array(metrics['bbox']),
|
|
83
|
+
'/Ascent': metrics['ascent'],
|
|
84
|
+
'/Descent': metrics['descent'],
|
|
85
|
+
'/CapHeight': metrics['cap_height'],
|
|
86
|
+
'/ItalicAngle': metrics['italic_angle'],
|
|
87
|
+
'/StemV': 80,
|
|
88
|
+
'/FontFile2': stream,
|
|
89
|
+
}
|
|
90
|
+
)
|
|
91
|
+
|
|
92
|
+
font['/Subtype'] = Name('/TrueType')
|
|
93
|
+
font['/FontDescriptor'] = desc
|
|
94
|
+
font['/FirstChar'] = 32
|
|
95
|
+
font['/LastChar'] = 255
|
|
96
|
+
font['/Widths'] = Array(metrics['widths'])
|
|
97
|
+
font['/Encoding'] = Name('/WinAnsiEncoding')
|
|
98
|
+
|
pdf2pdfa/icc.py
ADDED
|
@@ -0,0 +1,53 @@
|
|
|
1
|
+
"""ICC profile embedding utilities."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import base64
|
|
6
|
+
import logging
|
|
7
|
+
from pathlib import Path
|
|
8
|
+
|
|
9
|
+
from typing import Dict
|
|
10
|
+
|
|
11
|
+
from pikepdf import Pdf, Name, Dictionary, Array, String
|
|
12
|
+
|
|
13
|
+
logger = logging.getLogger(__name__)
|
|
14
|
+
|
|
15
|
+
|
|
16
|
+
def embed_icc_profile(pdf: Pdf, icc_path: str) -> None:
|
|
17
|
+
"""Add an OutputIntent referencing *icc_path* to the PDF."""
|
|
18
|
+
path = Path(icc_path)
|
|
19
|
+
if not path.is_file():
|
|
20
|
+
raise FileNotFoundError(f"ICC profile not found: {icc_path}")
|
|
21
|
+
|
|
22
|
+
logger.debug("Embedding ICC profile %s", icc_path)
|
|
23
|
+
data = path.read_bytes()
|
|
24
|
+
try:
|
|
25
|
+
text = data.decode('ascii')
|
|
26
|
+
if all(ch in 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=\n\r' for ch in text.strip()):
|
|
27
|
+
data = base64.b64decode(text)
|
|
28
|
+
except UnicodeDecodeError:
|
|
29
|
+
pass
|
|
30
|
+
icc_stream = pdf.make_stream(data)
|
|
31
|
+
|
|
32
|
+
def _num_components(icc: bytes) -> int:
|
|
33
|
+
if len(icc) < 20:
|
|
34
|
+
return 3
|
|
35
|
+
space = icc[16:20].decode('ascii', 'ignore')
|
|
36
|
+
return {
|
|
37
|
+
'RGB ': 3,
|
|
38
|
+
'GRAY': 1,
|
|
39
|
+
'CMYK': 4,
|
|
40
|
+
'XYZ ': 3,
|
|
41
|
+
'Lab ': 3,
|
|
42
|
+
}.get(space, 3)
|
|
43
|
+
|
|
44
|
+
outi = Dictionary({
|
|
45
|
+
'/Type': Name('/OutputIntent'),
|
|
46
|
+
'/S': Name('/GTS_PDFA1'),
|
|
47
|
+
'/OutputConditionIdentifier': String('sRGB IEC61966-2.1'),
|
|
48
|
+
'/DestOutputProfile': icc_stream,
|
|
49
|
+
'/N': _num_components(data),
|
|
50
|
+
})
|
|
51
|
+
pdf.Root.OutputIntents = Array([outi])
|
|
52
|
+
|
|
53
|
+
|
pdf2pdfa/metadata.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
"""XMP metadata generation for PDF/A."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import datetime as _dt
|
|
6
|
+
import logging
|
|
7
|
+
from typing import Dict
|
|
8
|
+
|
|
9
|
+
from lxml import etree
|
|
10
|
+
|
|
11
|
+
logger = logging.getLogger(__name__)
|
|
12
|
+
|
|
13
|
+
|
|
14
|
+
_NS = {
|
|
15
|
+
'rdf': 'http://www.w3.org/1999/02/22-rdf-syntax-ns#',
|
|
16
|
+
'pdfaid': 'http://www.aiim.org/pdfa/ns/id/',
|
|
17
|
+
'xmp': 'http://ns.adobe.com/xap/1.0/',
|
|
18
|
+
'dc': 'http://purl.org/dc/elements/1.1/',
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def generate_xmp_metadata() -> str:
|
|
23
|
+
"""Return a minimal PDF/A-1b compliant XMP packet."""
|
|
24
|
+
logger.debug("Generating XMP metadata")
|
|
25
|
+
now = _dt.datetime.utcnow().replace(microsecond=0).isoformat() + 'Z'
|
|
26
|
+
rdf = etree.Element('{%s}RDF' % _NS['rdf'], nsmap=_NS)
|
|
27
|
+
desc = etree.SubElement(rdf, '{%s}Description' % _NS['rdf'])
|
|
28
|
+
desc.set('{%s}about' % _NS['rdf'], '')
|
|
29
|
+
|
|
30
|
+
pdfaid = etree.SubElement(desc, '{%s}part' % _NS['pdfaid'])
|
|
31
|
+
pdfaid.text = '1'
|
|
32
|
+
conf = etree.SubElement(desc, '{%s}conformance' % _NS['pdfaid'])
|
|
33
|
+
conf.text = 'B'
|
|
34
|
+
|
|
35
|
+
created = etree.SubElement(desc, '{%s}CreateDate' % _NS['xmp'])
|
|
36
|
+
created.text = now
|
|
37
|
+
mod = etree.SubElement(desc, '{%s}ModifyDate' % _NS['xmp'])
|
|
38
|
+
mod.text = now
|
|
39
|
+
tool = etree.SubElement(desc, '{%s}CreatorTool' % _NS['xmp'])
|
|
40
|
+
tool.text = 'pdf2pdfa'
|
|
41
|
+
prod = etree.SubElement(desc, '{%s}Producer' % _NS['xmp'])
|
|
42
|
+
prod.text = 'pdf2pdfa'
|
|
43
|
+
|
|
44
|
+
dc_format = etree.SubElement(desc, '{%s}format' % _NS['dc'])
|
|
45
|
+
dc_format.text = 'application/pdf'
|
|
46
|
+
|
|
47
|
+
xml_bytes = etree.tostring(
|
|
48
|
+
rdf,
|
|
49
|
+
xml_declaration=False,
|
|
50
|
+
encoding='utf-8',
|
|
51
|
+
pretty_print=False,
|
|
52
|
+
)
|
|
53
|
+
packet = (
|
|
54
|
+
'<?xpacket begin="\ufeff" id="W5M0MpCehiHzreSzNTczkc9d"?>\n'
|
|
55
|
+
+ xml_bytes.decode('utf-8') +
|
|
56
|
+
'\n<?xpacket end="w"?>'
|
|
57
|
+
)
|
|
58
|
+
return packet
|
|
59
|
+
|
|
@@ -0,0 +1,96 @@
|
|
|
1
|
+
Metadata-Version: 2.4
|
|
2
|
+
Name: pdf2pdfa
|
|
3
|
+
Version: 0.1.0
|
|
4
|
+
Summary: Convert arbitrary PDF files to PDF/A-1b
|
|
5
|
+
Author: nks1990
|
|
6
|
+
Author-email: nks1990 <nks1990@example.com>
|
|
7
|
+
License: MIT
|
|
8
|
+
Classifier: Programming Language :: Python :: 3
|
|
9
|
+
Classifier: License :: OSI Approved :: MIT License
|
|
10
|
+
Requires-Python: >=3.7
|
|
11
|
+
Description-Content-Type: text/markdown
|
|
12
|
+
License-File: LICENSE
|
|
13
|
+
Requires-Dist: pikepdf>=4.0.0
|
|
14
|
+
Requires-Dist: fonttools>=4.0.0
|
|
15
|
+
Requires-Dist: lxml>=4.0.0
|
|
16
|
+
Requires-Dist: click>=7.0
|
|
17
|
+
Requires-Dist: importlib_resources; python_version < "3.9"
|
|
18
|
+
Requires-Dist: reportlab>=4.0.0
|
|
19
|
+
Provides-Extra: test
|
|
20
|
+
Requires-Dist: pytest>=6.0; extra == "test"
|
|
21
|
+
Dynamic: author
|
|
22
|
+
Dynamic: license-file
|
|
23
|
+
Dynamic: requires-python
|
|
24
|
+
|
|
25
|
+
# pdf2pdfa
|
|
26
|
+
|
|
27
|
+
**pdf2pdfa** converts ordinary PDF documents into fully compliant **PDF/A‑1b** files. The library offers both a simple command line tool and a Python API so that archival conversion can easily be automated or integrated into larger systems.
|
|
28
|
+
|
|
29
|
+
## Features
|
|
30
|
+
|
|
31
|
+
- Converts any PDF into valid PDF/A‑1b
|
|
32
|
+
- Embeds missing fonts automatically (using a fallback TrueType font)
|
|
33
|
+
- Attaches an sRGB ICC profile for consistent colour management
|
|
34
|
+
- Cleans and synchronises document metadata
|
|
35
|
+
- Usable from the command line or as a library
|
|
36
|
+
|
|
37
|
+
## Requirements
|
|
38
|
+
|
|
39
|
+
Python 3.7 or newer is needed. The following packages are installed automatically when using `pip`:
|
|
40
|
+
|
|
41
|
+
- [pikepdf](https://pikepdf.readthedocs.io/)
|
|
42
|
+
- [fonttools](https://github.com/fonttools/fonttools)
|
|
43
|
+
- [lxml](https://lxml.de/)
|
|
44
|
+
- [click](https://click.palletsprojects.com/)
|
|
45
|
+
|
|
46
|
+
For validation of the generated files you can optionally install [`verapdf`](https://github.com/veraPDF/veraPDF-library).
|
|
47
|
+
|
|
48
|
+
## Installation
|
|
49
|
+
|
|
50
|
+
Install the latest release from PyPI:
|
|
51
|
+
|
|
52
|
+
```bash
|
|
53
|
+
pip install pdf2pdfa
|
|
54
|
+
```
|
|
55
|
+
|
|
56
|
+
## Command line usage
|
|
57
|
+
|
|
58
|
+
```bash
|
|
59
|
+
pdf2pdfa convert input.pdf output.pdf
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
`--icc PATH` can be used to specify a custom ICC profile.
|
|
63
|
+
|
|
64
|
+
## Library usage
|
|
65
|
+
|
|
66
|
+
```python
|
|
67
|
+
from pdf2pdfa import Converter
|
|
68
|
+
|
|
69
|
+
conv = Converter()
|
|
70
|
+
conv.convert("input.pdf", "output.pdf")
|
|
71
|
+
```
|
|
72
|
+
|
|
73
|
+
If fonts are missing from the source PDF the converter tries to embed a common system font (e.g. DejaVu Sans). You may also supply a specific font path.
|
|
74
|
+
|
|
75
|
+
## Development and testing
|
|
76
|
+
|
|
77
|
+
Clone the repository and install the development requirements:
|
|
78
|
+
|
|
79
|
+
```bash
|
|
80
|
+
pip install -e .[test]
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
Run the unit tests using `pytest`. When `verapdf` is available the tests also check that the output conforms to PDF/A‑1b.
|
|
84
|
+
|
|
85
|
+
```bash
|
|
86
|
+
pytest
|
|
87
|
+
```
|
|
88
|
+
|
|
89
|
+
## License
|
|
90
|
+
|
|
91
|
+
This project is released under the MIT License. See [LICENSE](LICENSE) for details.
|
|
92
|
+
|
|
93
|
+
## Contributing
|
|
94
|
+
|
|
95
|
+
Contributions are very welcome. Feel free to open issues or submit pull requests on GitHub.
|
|
96
|
+
|
|
@@ -0,0 +1,13 @@
|
|
|
1
|
+
pdf2pdfa/__init__.py,sha256=v_CQII668LwrpVurdEvED_r-cnlk3jWgdD-dIna37fQ,146
|
|
2
|
+
pdf2pdfa/cli.py,sha256=q5A5nu2oOPyjnS0NhthnijSIMLG5SyGJ9j0H552H5Xs,782
|
|
3
|
+
pdf2pdfa/converter.py,sha256=w5vMqV6in3-2SyW1Z-qKSKLrKjDbnki5Y5g8KdjJQBI,7969
|
|
4
|
+
pdf2pdfa/fonts.py,sha256=qvYbJHeUTfsD-UV7R3pPhYXpi4z62w63qaFVXaQtMII,3552
|
|
5
|
+
pdf2pdfa/icc.py,sha256=_zFeN9C0OMwWEXiI7tqEMYliki3xuu1Y-yamSclXlbE,1468
|
|
6
|
+
pdf2pdfa/metadata.py,sha256=y8G06n_hhuiyIu6Q1fZmbqEZeMS3ANLHtTKVGHA_wOA,1745
|
|
7
|
+
pdf2pdfa/data/sRGB.icc.b64,sha256=ZXmZ2Fy_53E0ubtuhfpv8hvX3bF12PgAty6MRQKbXxY,9354
|
|
8
|
+
pdf2pdfa-0.1.0.dist-info/licenses/LICENSE,sha256=qFkZi1LpqMrp2RP2kyieZislwXYM0Wm5bK_-s0rjwHE,1094
|
|
9
|
+
pdf2pdfa-0.1.0.dist-info/METADATA,sha256=teaON1JGSnM68_ztKVe_StTmbfJIukwmfdKdDKqmFP0,2624
|
|
10
|
+
pdf2pdfa-0.1.0.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
|
|
11
|
+
pdf2pdfa-0.1.0.dist-info/entry_points.txt,sha256=smroPOvJV_Sry6zAm_c4P3q6E_9hd4ZqeK0UQnq6jc8,46
|
|
12
|
+
pdf2pdfa-0.1.0.dist-info/top_level.txt,sha256=rvMBJLWkHry7FIHd7TGnRD8ENSkEClpnx-1uyQGtjaQ,9
|
|
13
|
+
pdf2pdfa-0.1.0.dist-info/RECORD,,
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
The MIT License (MIT)
|
|
2
|
+
=====================
|
|
3
|
+
|
|
4
|
+
Copyright © 2025
|
|
5
|
+
|
|
6
|
+
Permission is hereby granted, free of charge, to any person
|
|
7
|
+
obtaining a copy of this software and associated documentation
|
|
8
|
+
files (the “Software”), to deal in the Software without
|
|
9
|
+
restriction, including without limitation the rights to use,
|
|
10
|
+
copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
11
|
+
copies of the Software, and to permit persons to whom the
|
|
12
|
+
Software is furnished to do so, subject to the following
|
|
13
|
+
conditions:
|
|
14
|
+
|
|
15
|
+
The above copyright notice and this permission notice shall be
|
|
16
|
+
included in all copies or substantial portions of the Software.
|
|
17
|
+
|
|
18
|
+
THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND,
|
|
19
|
+
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
|
|
20
|
+
OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
|
21
|
+
NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
|
|
22
|
+
HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
|
|
23
|
+
WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
|
24
|
+
FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
|
|
25
|
+
OTHER DEALINGS IN THE SOFTWARE.
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
pdf2pdfa
|