coreidml 0.0.8__py3-none-win_arm64.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.
coreidml/__init__.py ADDED
@@ -0,0 +1,19 @@
1
+ """Create, read and edit Adobe InDesign IDML files, through the Native AOT build of the CoreIdml library.
2
+
3
+ The C API (include/coreidml.h) is called with ctypes, so there is nothing to compile::
4
+
5
+ import coreidml
6
+
7
+ with coreidml.Document.open("template.idml") as doc:
8
+ doc.fill({"text": {"name": "Ana"}})
9
+ doc.save_file("out.idml")
10
+ doc.export_pdf("out.pdf", {"fontDirectories": ["fonts"]})
11
+
12
+ The native library is found on its own (see ``coreidml.load``); ``COREIDML_LIBRARY`` names another one.
13
+ """
14
+
15
+ from ._abi import ABI_VERSION, Status
16
+ from ._document import Document, ProgressCallback
17
+ from ._native import IdmlError, library_path, load, version
18
+
19
+ __all__ = ["ABI_VERSION", "Document", "IdmlError", "ProgressCallback", "Status", "library_path", "load", "version"]
coreidml/_abi.py ADDED
@@ -0,0 +1,65 @@
1
+ # <auto-generated>
2
+ # Generated by tools/CoreIdml.AbiGen from include/coreidml.h. Do not edit: change the header and run
3
+ # `dotnet run --project tools/CoreIdml.AbiGen`.
4
+ # </auto-generated>
5
+ """ctypes signatures of the C API (include/coreidml.h)."""
6
+
7
+ import ctypes
8
+ import enum
9
+
10
+ #: COREIDML_ABI_VERSION of the header this file was generated from.
11
+ ABI_VERSION = 1
12
+
13
+
14
+ class Status(enum.IntEnum):
15
+ """Status codes of the library (COREIDML_OK, COREIDML_ERR_*)."""
16
+
17
+ OK = 0
18
+ FAILED = -1
19
+ INVALID_HANDLE = -2
20
+ INVALID_ARGUMENT = -3
21
+ CANCELLED = -4
22
+ INVALID_FORMAT = -5
23
+ NOT_FOUND = -6
24
+ UNSUPPORTED = -7
25
+ INVALID_OPERATION = -8
26
+ IO = -9
27
+
28
+
29
+ #: coreidml_progress_callback: return 0 to continue, anything else to cancel.
30
+ PROGRESS_CALLBACK = ctypes.CFUNCTYPE(ctypes.c_int32, ctypes.c_int32, ctypes.c_int32, ctypes.c_void_p)
31
+
32
+ #: Every function of coreidml.h: name -> (restype, argtypes).
33
+ SIGNATURES = {
34
+ "coreidml_abi_version": (ctypes.c_int32, ()),
35
+ "coreidml_version": (ctypes.c_char_p, ()),
36
+ "coreidml_last_error_code": (ctypes.c_int32, ()),
37
+ "coreidml_last_error_message": (ctypes.c_char_p, ()),
38
+ "coreidml_free": (None, (ctypes.c_void_p,)),
39
+ "coreidml_document_open": (ctypes.c_int32, (ctypes.c_char_p, ctypes.c_size_t, ctypes.POINTER(ctypes.c_ssize_t))),
40
+ "coreidml_document_open_file": (ctypes.c_int32, (ctypes.c_char_p, ctypes.POINTER(ctypes.c_ssize_t))),
41
+ "coreidml_document_info": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_void_p))),
42
+ "coreidml_document_read_part": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t))),
43
+ "coreidml_document_write_part": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_size_t)),
44
+ "coreidml_document_save": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t))),
45
+ "coreidml_document_save_file": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p)),
46
+ "coreidml_document_close": (None, (ctypes.c_ssize_t,)),
47
+ "coreidml_document_create": (ctypes.c_int32, (ctypes.c_char_p, ctypes.POINTER(ctypes.c_ssize_t))),
48
+ "coreidml_document_apply": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p)),
49
+ "coreidml_document_summary": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p))),
50
+ "coreidml_document_story": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p))),
51
+ "coreidml_document_xml_structure": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_void_p))),
52
+ "coreidml_document_export_xml": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p))),
53
+ "coreidml_document_validate": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_void_p))),
54
+ "coreidml_document_diff": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_void_p))),
55
+ "coreidml_document_fill": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p))),
56
+ "coreidml_document_replace_text": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_int32))),
57
+ "coreidml_document_set_run_text": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_int32, ctypes.c_char_p, ctypes.c_int32)),
58
+ "coreidml_document_relink": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_int32)),
59
+ "coreidml_document_import_xml": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, ctypes.c_char_p, ctypes.POINTER(ctypes.c_void_p))),
60
+ "coreidml_document_import_pages": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_ssize_t, ctypes.POINTER(ctypes.c_int32), ctypes.c_size_t, ctypes.POINTER(ctypes.c_int32))),
61
+ "coreidml_document_export_pdf": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, ctypes.c_char_p, PROGRESS_CALLBACK, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p))),
62
+ "coreidml_document_export_pdf_bytes": (ctypes.c_int32, (ctypes.c_ssize_t, ctypes.c_char_p, PROGRESS_CALLBACK, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p), ctypes.POINTER(ctypes.c_size_t), ctypes.POINTER(ctypes.c_void_p))),
63
+ "coreidml_pdf_import": (ctypes.c_int32, (ctypes.c_char_p, ctypes.c_size_t, ctypes.c_char_p, PROGRESS_CALLBACK, ctypes.c_void_p, ctypes.POINTER(ctypes.c_ssize_t), ctypes.POINTER(ctypes.c_void_p))),
64
+ "coreidml_pdf_import_file": (ctypes.c_int32, (ctypes.c_char_p, ctypes.c_char_p, PROGRESS_CALLBACK, ctypes.c_void_p, ctypes.POINTER(ctypes.c_ssize_t), ctypes.POINTER(ctypes.c_void_p))),
65
+ }
coreidml/_document.py ADDED
@@ -0,0 +1,412 @@
1
+ """The document API over the C functions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import json
7
+ import os
8
+ from collections.abc import Iterable, Mapping
9
+ from typing import Any, Callable, Optional, Union, cast
10
+
11
+ from ._abi import PROGRESS_CALLBACK, Status
12
+ from ._native import IdmlError, check, native, release, take_bytes, take_text
13
+
14
+ _Bytes = Union[bytes, bytearray, memoryview]
15
+ _Path = Union[str, "os.PathLike[str]"]
16
+ #: A JSON argument: a dict (or list) that is serialized, or JSON text passed as it is.
17
+ _Json = Union[Mapping[str, Any], str]
18
+
19
+ #: ``progress(done, total)``, called after each page; returning ``False`` cancels the call.
20
+ ProgressCallback = Callable[[int, int], Optional[bool]]
21
+
22
+
23
+ class Document:
24
+ """An InDesign document held by the library.
25
+
26
+ Open one with ``Document.open``, ``Document.create`` or ``Document.import_pdf`` and close it with ``close()`` or a
27
+ ``with`` block; a document that is forgotten is released when it is garbage collected. A document may be used
28
+ from any thread; calls on it are serialized.
29
+ """
30
+
31
+ def __init__(self, handle: int):
32
+ self._handle = handle
33
+
34
+ # ---- Opening and creating ------------------------------------------------------------------------------------
35
+
36
+ @classmethod
37
+ def open(cls, source: Union[_Path, _Bytes]) -> "Document":
38
+ """Opens an .idml file from a path, or from its bytes (which are not kept)."""
39
+ lib = native()
40
+ handle = ctypes.c_ssize_t(0)
41
+ if isinstance(source, (bytes, bytearray, memoryview)):
42
+ data = bytes(source)
43
+ check(lib.coreidml_document_open(data, len(data), ctypes.byref(handle)))
44
+ elif isinstance(source, (str, os.PathLike)):
45
+ check(lib.coreidml_document_open_file(_file(source), ctypes.byref(handle)))
46
+ else:
47
+ raise IdmlError("source must be a path or the bytes of an .idml file.", Status.INVALID_ARGUMENT)
48
+ return cls(handle.value)
49
+
50
+ @classmethod
51
+ def create(cls, spec: Optional[_Json] = None) -> "Document":
52
+ """Creates a document from a document spec (a dict or its JSON text): page size, colours, styles, and pages of
53
+ text, images, tables and shapes. Without one, the document is one blank A4 page."""
54
+ handle = ctypes.c_ssize_t(0)
55
+ check(native().coreidml_document_create(_json(spec, "spec"), ctypes.byref(handle)))
56
+ return cls(handle.value)
57
+
58
+ @classmethod
59
+ def import_pdf(
60
+ cls,
61
+ source: Union[_Path, _Bytes],
62
+ options: Optional[_Json] = None,
63
+ progress: Optional[ProgressCallback] = None,
64
+ ) -> tuple["Document", dict[str, Any]]:
65
+ """Builds an editable document from a PDF (a path, or its bytes): text frames with inferred styles, image
66
+ frames and shapes. Returns the document and the import report (frames, images, fonts, warnings).
67
+
68
+ Options: ``pages`` (1-based), ``imageDirectory`` (where the images are written, since IDML links them),
69
+ ``preserveLineBreaks``, ``importShapes``, ``fontDirectories``.
70
+ """
71
+ lib = native()
72
+ handle, report = ctypes.c_ssize_t(0), ctypes.c_void_p()
73
+ options_json = _json(options, "options")
74
+ with _Progress(progress) as callback:
75
+ if isinstance(source, (bytes, bytearray, memoryview)):
76
+ data = bytes(source)
77
+ status = lib.coreidml_pdf_import(data, len(data), options_json, callback.function, None, ctypes.byref(handle), ctypes.byref(report))
78
+ elif isinstance(source, (str, os.PathLike)):
79
+ status = lib.coreidml_pdf_import_file(_file(source), options_json, callback.function, None, ctypes.byref(handle), ctypes.byref(report))
80
+ else:
81
+ raise IdmlError("source must be a path or the bytes of a PDF file.", Status.INVALID_ARGUMENT)
82
+ # The error message is read before anything else is called: it is valid only until the next call.
83
+ try:
84
+ callback.check(status)
85
+ except BaseException:
86
+ release(report)
87
+ if handle.value:
88
+ lib.coreidml_document_close(handle.value)
89
+ raise
90
+ document = cls(handle.value)
91
+ try:
92
+ result = _take_json(report)
93
+ except BaseException:
94
+ document.close()
95
+ raise
96
+ return document, result
97
+
98
+ @property
99
+ def closed(self) -> bool:
100
+ """Whether ``close()`` was called."""
101
+ return self._handle == 0
102
+
103
+ # ---- Package parts -------------------------------------------------------------------------------------------
104
+
105
+ def info(self) -> dict[str, Any]:
106
+ """The parts of the package and the manifest: ``domVersion``, ``parts``, ``spreads``, ``masterSpreads``, ``stories``."""
107
+ text = ctypes.c_void_p()
108
+ check(native().coreidml_document_info(self._open_handle(), ctypes.byref(text)))
109
+ return _take_json(text)
110
+
111
+ def read_part(self, path: str) -> bytes:
112
+ """The bytes of one part (e.g. ``Stories/Story_u188.xml``) as they would be saved now."""
113
+ data, length = ctypes.c_void_p(), ctypes.c_size_t(0)
114
+ check(native().coreidml_document_read_part(self._open_handle(), _path(path), ctypes.byref(data), ctypes.byref(length)))
115
+ return take_bytes(data, length.value)
116
+
117
+ def read_text(self, path: str) -> str:
118
+ """One part as text (parts are UTF-8 XML, except images a template may embed)."""
119
+ return self.read_part(path).decode("utf-8")
120
+
121
+ def write_part(self, path: str, data: Union[str, _Bytes]) -> None:
122
+ """Adds or replaces one part. Text is written as UTF-8."""
123
+ if isinstance(data, str):
124
+ content = data.encode("utf-8")
125
+ elif isinstance(data, (bytes, bytearray, memoryview)):
126
+ content = bytes(data)
127
+ else:
128
+ raise IdmlError("data must be text or bytes.", Status.INVALID_ARGUMENT)
129
+ check(native().coreidml_document_write_part(self._open_handle(), _path(path), content, len(content)))
130
+
131
+ # ---- Reading -------------------------------------------------------------------------------------------------
132
+
133
+ def summary(self, options: Optional[_Json] = None) -> dict[str, Any]:
134
+ """A summary for programs and agents: pages, frames with positions and text, stories, links, styles, swatches,
135
+ tags. Options: ``maxTextLength`` (200), ``includeRuns`` (False), ``includeResources`` (True), ``pages``
136
+ (0-based indices) and ``sections`` (any of ``pages``, ``stories``, ``links``, ``offPage``, ``resources``)."""
137
+ text = ctypes.c_void_p()
138
+ check(native().coreidml_document_summary(self._open_handle(), _json(options, "options"), ctypes.byref(text)))
139
+ return _take_json(text)
140
+
141
+ def story(self, story_id: str) -> dict[str, Any]:
142
+ """One story in full: its text, frames, and every content run with its index, styles and scope."""
143
+ text = ctypes.c_void_p()
144
+ check(native().coreidml_document_story(self._open_handle(), _text(story_id, "story_id"), ctypes.byref(text)))
145
+ return _take_json(text)
146
+
147
+ def xml_structure(self) -> Optional[dict[str, Any]]:
148
+ """The XML structure as a tree of dicts (``tag``, ``id``, ``path``, ``boundTo``, ``attributes``, ``text``,
149
+ ``children``), or ``None`` when the document has none."""
150
+ text = ctypes.c_void_p()
151
+ check(native().coreidml_document_xml_structure(self._open_handle(), ctypes.byref(text)))
152
+ return cast("Optional[dict[str, Any]]", _take_json_value(text))
153
+
154
+ def export_xml(self, at: Optional[str] = None) -> str:
155
+ """The XML structure as XML, or only the subtree at a path such as ``/Root/article[2]``."""
156
+ text = ctypes.c_void_p()
157
+ check(native().coreidml_document_export_xml(self._open_handle(), _optional_text(at, "at"), ctypes.byref(text)))
158
+ return take_text(text)
159
+
160
+ def validate(self) -> dict[str, Any]:
161
+ """Checks references, ids, layers, threads and XML bindings: ``{"isValid": True, "issues": [...]}``."""
162
+ text = ctypes.c_void_p()
163
+ check(native().coreidml_document_validate(self._open_handle(), ctypes.byref(text)))
164
+ return _take_json(text)
165
+
166
+ def diff(self, other: "Document") -> dict[str, Any]:
167
+ """What changed from this document to ``other``: stories run by run, links, page count."""
168
+ text = ctypes.c_void_p()
169
+ check(native().coreidml_document_diff(self._open_handle(), _document(other, "other"), ctypes.byref(text)))
170
+ return _take_json(text)
171
+
172
+ # ---- Editing -------------------------------------------------------------------------------------------------
173
+
174
+ def apply(self, spec: _Json) -> None:
175
+ """Adds the colours, styles and pages of a document spec (a dict or its JSON text); its pages are appended."""
176
+ check(native().coreidml_document_apply(self._open_handle(), _json(spec, "spec", required=True)))
177
+
178
+ def fill(self, data: _Json) -> dict[str, Any]:
179
+ """Fills a template: ``{"text": {"key": "value"}, "images": {"key": "/path/photo.jpg"}}``. Keys match frame
180
+ names, script labels, XML tags and ``{{placeholders}}``. Returns the report (``filled``, ``missing``)."""
181
+ text = ctypes.c_void_p()
182
+ check(native().coreidml_document_fill(self._open_handle(), _json(data, "data", required=True), ctypes.byref(text)))
183
+ return _take_json(text)
184
+
185
+ def replace_text(self, find: str, replacement: str) -> int:
186
+ """Replaces text in every story; returns the number of replacements."""
187
+ count = ctypes.c_int32(0)
188
+ check(native().coreidml_document_replace_text(
189
+ self._open_handle(), _text(find, "find"), _text(replacement, "replacement"), ctypes.byref(count)))
190
+ return count.value
191
+
192
+ def set_run_text(self, story_id: str, run_index: int, text: str, force: bool = False) -> None:
193
+ """Sets the text of one content run of a story (indices from ``story()``), keeping its formatting. A run that
194
+ holds special characters (a page number) is only overwritten with ``force``."""
195
+ check(native().coreidml_document_set_run_text(
196
+ self._open_handle(), _text(story_id, "story_id"), _int32(run_index, "run_index"), _text(text, "text"), 1 if force else 0))
197
+
198
+ def relink(self, link_id: str, uri_or_path: _Path, refit: bool = False) -> None:
199
+ """Points a link (an id from the summary's ``links``) at another file: a URI or a local path. With ``refit``
200
+ and a readable local JPEG or PNG, the image is measured again and fitted to its frame."""
201
+ target = os.fspath(uri_or_path) if isinstance(uri_or_path, os.PathLike) else uri_or_path
202
+ check(native().coreidml_document_relink(
203
+ self._open_handle(), _text(link_id, "link_id"), _text(target, "uri_or_path"), 1 if refit else 0))
204
+
205
+ def import_xml(self, xml: Union[str, _Bytes], at: Optional[str] = None, options: Optional[_Json] = None) -> dict[str, Any]:
206
+ """Imports XML onto the structure element at a path (the root without one), with SimpleIDML's semantics
207
+ (``simpleidml-setcontent``, ``-ignorecontent``, ``-forcecontent``, ``href``). Options: ``fit``,
208
+ ``characterStyles`` (tag -> style), ``relinkOnly``. Returns the report (``updated``, ``added``, ``deleted``,
209
+ ``unmatched``, ``warnings``)."""
210
+ if isinstance(xml, (bytes, bytearray, memoryview)):
211
+ content = bytes(xml)
212
+ if b"\0" in content:
213
+ raise IdmlError("xml must not contain NUL characters.", Status.INVALID_ARGUMENT)
214
+ else:
215
+ content = _text(xml, "xml")
216
+ text = ctypes.c_void_p()
217
+ check(native().coreidml_document_import_xml(
218
+ self._open_handle(), content, _optional_text(at, "at"), _json(options, "options"), ctypes.byref(text)))
219
+ return _take_json(text)
220
+
221
+ def import_pages(self, source: "Document", pages: Iterable[int] = ()) -> int:
222
+ """Appends pages of ``source`` (0-based indices; none: every page), remapping every id; styles, swatches and
223
+ tags are merged once. ``source`` may be this document. Returns the number of pages added."""
224
+ if isinstance(pages, (str, bytes)) or not isinstance(pages, Iterable):
225
+ raise IdmlError("pages must be an iterable of page indices.", Status.INVALID_ARGUMENT)
226
+ indices = [_int32(page, "pages") for page in pages]
227
+ array = (ctypes.c_int32 * len(indices))(*indices) if indices else None
228
+ added = ctypes.c_int32(0)
229
+ check(native().coreidml_document_import_pages(
230
+ self._open_handle(), _document(source, "source"), array, len(indices), ctypes.byref(added)))
231
+ return added.value
232
+
233
+ # ---- Saving and PDF ------------------------------------------------------------------------------------------
234
+
235
+ def save(self) -> bytes:
236
+ """The document as the bytes of an .idml file. Parts that were not changed are written byte for byte."""
237
+ data, length = ctypes.c_void_p(), ctypes.c_size_t(0)
238
+ check(native().coreidml_document_save(self._open_handle(), ctypes.byref(data), ctypes.byref(length)))
239
+ return take_bytes(data, length.value)
240
+
241
+ def save_file(self, path: _Path) -> None:
242
+ """Saves the document as an .idml file."""
243
+ check(native().coreidml_document_save_file(self._open_handle(), _file(path)))
244
+
245
+ def export_pdf(self, path: _Path, options: Optional[_Json] = None, progress: Optional[ProgressCallback] = None) -> dict[str, Any]:
246
+ """Renders the document to a PDF file. Returns the report: ``pageCount``, ``missingFonts``, ``missingImages``,
247
+ ``oversetStories``, ``warnings``.
248
+
249
+ Options: ``pages`` (1-based), ``fontDirectories``, ``useSystemFonts`` (True), ``substitutions`` (font ->
250
+ font), ``linkDirectories``, ``linkRemap``, ``documentPath``, ``maxImageDpi``, ``jpegQuality``.
251
+ ``progress(done, total)`` is called after each page; returning ``False`` cancels (``Status.CANCELLED``).
252
+ """
253
+ handle, file, options_json = self._open_handle(), _file(path), _json(options, "options")
254
+ report = ctypes.c_void_p()
255
+ with _Progress(progress) as callback:
256
+ status = native().coreidml_document_export_pdf(handle, file, options_json, callback.function, None, ctypes.byref(report))
257
+ try:
258
+ callback.check(status) # reads the error message before anything is released
259
+ except BaseException:
260
+ release(report)
261
+ raise
262
+ return _take_json(report)
263
+
264
+ def export_pdf_bytes(self, options: Optional[_Json] = None, progress: Optional[ProgressCallback] = None) -> tuple[bytes, dict[str, Any]]:
265
+ """Renders the document to a PDF in memory. Returns ``(pdf, report)``; options and report as for
266
+ ``export_pdf``."""
267
+ handle, options_json = self._open_handle(), _json(options, "options")
268
+ data, length, report = ctypes.c_void_p(), ctypes.c_size_t(0), ctypes.c_void_p()
269
+ with _Progress(progress) as callback:
270
+ status = native().coreidml_document_export_pdf_bytes(
271
+ handle, options_json, callback.function, None, ctypes.byref(data), ctypes.byref(length), ctypes.byref(report))
272
+ try:
273
+ callback.check(status) # reads the error message before anything is released
274
+ except BaseException:
275
+ release(data, report)
276
+ raise
277
+ try:
278
+ pdf = take_bytes(data, length.value)
279
+ except BaseException:
280
+ release(report)
281
+ raise
282
+ return pdf, _take_json(report)
283
+
284
+ # ---- Lifetime ------------------------------------------------------------------------------------------------
285
+
286
+ def close(self) -> None:
287
+ """Releases the document. Calling it again does nothing."""
288
+ handle, self._handle = self._handle, 0
289
+ if handle:
290
+ native().coreidml_document_close(handle)
291
+
292
+ def _open_handle(self) -> int:
293
+ if not self._handle:
294
+ raise IdmlError("The document is closed.", Status.INVALID_HANDLE)
295
+ return self._handle
296
+
297
+ def __enter__(self) -> "Document":
298
+ return self
299
+
300
+ def __exit__(self, *_: object) -> None:
301
+ self.close()
302
+
303
+ def __del__(self) -> None:
304
+ try:
305
+ self.close()
306
+ except Exception: # the interpreter may be shutting down
307
+ pass
308
+
309
+
310
+ class _Progress:
311
+ """The C progress callback of one call, kept alive by the ``with`` block around the call.
312
+
313
+ An exception raised by the Python callback cannot cross the C frames: it cancels the call, and ``check`` raises it
314
+ again once the call has returned. Without a callback the C function gets NULL.
315
+ """
316
+
317
+ def __init__(self, callback: Optional[ProgressCallback]):
318
+ if callback is not None and not callable(callback):
319
+ raise IdmlError("progress must be callable.", Status.INVALID_ARGUMENT)
320
+ self._callback = callback
321
+ self._error: Optional[BaseException] = None
322
+ self.function = PROGRESS_CALLBACK(self._call) if callback is not None else PROGRESS_CALLBACK()
323
+
324
+ def _call(self, done: int, total: int, _user_data: Optional[int]) -> int:
325
+ if self._error is not None or self._callback is None:
326
+ return 1
327
+ try:
328
+ return 1 if self._callback(done, total) is False else 0
329
+ except BaseException as error: # re-raised by check(), after the native call has unwound
330
+ self._error = error
331
+ return 1
332
+
333
+ def check(self, status: int) -> None:
334
+ if self._error is not None:
335
+ error, self._error = self._error, None
336
+ raise error
337
+ check(status)
338
+
339
+ def __enter__(self) -> "_Progress":
340
+ return self
341
+
342
+ def __exit__(self, *_: object) -> None:
343
+ # Only now may the function pointer be collected: the library calls it until the call returns.
344
+ self.function = PROGRESS_CALLBACK()
345
+ self._callback = None
346
+
347
+
348
+ def _take_json(pointer: ctypes.c_void_p) -> dict[str, Any]:
349
+ """Parses and releases a JSON object the library handed out (``{}`` when there is none: a failed call)."""
350
+ return cast("dict[str, Any]", _take_json_value(pointer) or {})
351
+
352
+
353
+ def _take_json_value(pointer: ctypes.c_void_p) -> Any:
354
+ """Parses and releases a JSON string the library handed out; ``None`` for JSON null or no string at all."""
355
+ text = take_text(pointer)
356
+ return json.loads(text) if text else None
357
+
358
+
359
+ def _json(value: Optional[_Json], name: str, required: bool = False) -> Optional[bytes]:
360
+ if value is None:
361
+ if required:
362
+ raise IdmlError(f"{name} is required.", Status.INVALID_ARGUMENT)
363
+ return None
364
+ if isinstance(value, str):
365
+ return _text(value, name)
366
+ if not isinstance(value, (Mapping, list, tuple)):
367
+ raise IdmlError(f"{name} must be a dict or JSON text.", Status.INVALID_ARGUMENT)
368
+ try:
369
+ text = json.dumps(value, ensure_ascii=False, default=_json_default)
370
+ except (TypeError, ValueError) as error:
371
+ raise IdmlError(f"{name} cannot be written as JSON: {error}", Status.INVALID_ARGUMENT) from error
372
+ return _text(text, name)
373
+
374
+
375
+ def _json_default(value: object) -> Any:
376
+ if isinstance(value, os.PathLike): # paths in options (fontDirectories, imageDirectory, ...)
377
+ return os.fspath(value)
378
+ raise TypeError(f"{type(value).__name__} is not JSON serializable")
379
+
380
+
381
+ def _text(value: str, name: str) -> bytes:
382
+ if not isinstance(value, str):
383
+ raise IdmlError(f"{name} must be a string.", Status.INVALID_ARGUMENT)
384
+ if "\0" in value:
385
+ raise IdmlError(f"{name} must not contain NUL characters.", Status.INVALID_ARGUMENT)
386
+ return value.encode("utf-8")
387
+
388
+
389
+ def _optional_text(value: Optional[str], name: str) -> Optional[bytes]:
390
+ return None if value is None else _text(value, name)
391
+
392
+
393
+ def _path(path: str) -> bytes:
394
+ return _text(path, "path")
395
+
396
+
397
+ def _file(path: _Path) -> bytes:
398
+ if not isinstance(path, (str, os.PathLike)):
399
+ raise IdmlError("path must be a str or os.PathLike.", Status.INVALID_ARGUMENT)
400
+ return _text(os.fspath(path), "path")
401
+
402
+
403
+ def _int32(value: int, name: str) -> int:
404
+ if isinstance(value, bool) or not isinstance(value, int) or not -(2**31) <= value < 2**31:
405
+ raise IdmlError(f"{name} must be a 32-bit integer.", Status.INVALID_ARGUMENT)
406
+ return value
407
+
408
+
409
+ def _document(value: "Document", name: str) -> int:
410
+ if not isinstance(value, Document):
411
+ raise IdmlError(f"{name} must be a Document.", Status.INVALID_ARGUMENT)
412
+ return value._open_handle()
Binary file
coreidml/_native.py ADDED
@@ -0,0 +1,170 @@
1
+ """Finds and loads the native library, and turns its status codes into exceptions."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import ctypes
6
+ import os
7
+ import platform
8
+ import sys
9
+ from pathlib import Path
10
+ from typing import Optional, Union
11
+
12
+ from ._abi import ABI_VERSION, SIGNATURES, Status
13
+
14
+ #: Environment variable with the full path of the native library; it wins over every other location.
15
+ LIBRARY_ENV = "COREIDML_LIBRARY"
16
+
17
+ _lib: Optional[ctypes.CDLL] = None
18
+ _path: Optional[str] = None
19
+
20
+
21
+ class IdmlError(Exception):
22
+ """A failed call into the library. ``code`` is a ``Status``, the same in every CoreIdml binding."""
23
+
24
+ def __init__(self, message: str, code: Status = Status.FAILED):
25
+ super().__init__(message)
26
+ self.code = code
27
+
28
+
29
+ def library_file_name() -> str:
30
+ """File name of the native library on this platform."""
31
+ if sys.platform == "win32":
32
+ return "coreidml.dll"
33
+ if sys.platform == "darwin":
34
+ return "libcoreidml.dylib"
35
+ return "libcoreidml.so"
36
+
37
+
38
+ def _runtime_identifier() -> Optional[str]:
39
+ """The .NET runtime identifier of this platform (the folder name under artifacts/native), if there is one."""
40
+ system = {"win32": "win", "darwin": "osx", "linux": "linux"}.get(sys.platform)
41
+ machine = {"amd64": "x64", "x86_64": "x64", "arm64": "arm64", "aarch64": "arm64"}.get(platform.machine().lower())
42
+ return f"{system}-{machine}" if system and machine else None
43
+
44
+
45
+ def _candidates() -> list[tuple[str, str]]:
46
+ """Where to look, in order: (path, where it came from)."""
47
+ name = library_file_name()
48
+ here = Path(__file__).resolve().parent
49
+ found: list[tuple[str, str]] = []
50
+
51
+ packaged = here / "_lib" / name # a platform wheel carries the library here
52
+ if packaged.is_file():
53
+ found.append((str(packaged), "the installed package"))
54
+
55
+ # bindings/python/src/coreidml -> the repository root, when running from a source checkout
56
+ root = here.parents[3] if len(here.parents) > 3 else None
57
+ rid = _runtime_identifier()
58
+ if root is not None and rid and (root / "include" / "coreidml.h").is_file():
59
+ local = root / "artifacts" / "native" / rid / name
60
+ if local.is_file():
61
+ found.append((str(local), "the local build"))
62
+
63
+ found.append((name, "the operating system's library search path"))
64
+ return found
65
+
66
+
67
+ def load(path: Union[str, "os.PathLike[str]", None] = None) -> ctypes.CDLL:
68
+ """Loads the native library and checks its ABI. Called on first use; call it first to choose the library.
69
+
70
+ Without ``path`` the library is searched for: the ``COREIDML_LIBRARY`` environment variable, the installed
71
+ package, a local build in ``artifacts/native`` of a source checkout, then the system's library search path.
72
+ A path or the environment variable is the only place tried: if that file does not load, that is the error.
73
+ """
74
+ global _lib, _path
75
+ explicit = os.fspath(path) if path is not None else os.environ.get(LIBRARY_ENV)
76
+ if _lib is not None:
77
+ if explicit is not None and os.path.abspath(explicit) != os.path.abspath(_path or ""):
78
+ raise IdmlError(f"The native library is already loaded from {_path}; a process can use only one.", Status.INVALID_OPERATION)
79
+ return _lib
80
+
81
+ candidates = [(explicit, "the given path" if path is not None else f"the {LIBRARY_ENV} environment variable")] if explicit else _candidates()
82
+ failures = []
83
+ for candidate, source in candidates:
84
+ try:
85
+ library = ctypes.CDLL(candidate)
86
+ except OSError as error:
87
+ failures.append(f" - {source}: {candidate} ({error})")
88
+ continue
89
+ _bind(library, candidate, source)
90
+ _lib, _path = library, candidate
91
+ return library
92
+
93
+ rid = _runtime_identifier() or "this platform"
94
+ raise IdmlError(
95
+ f"Could not load the CoreIdml native library ({library_file_name()}). Tried:\n" + "\n".join(failures) + "\n"
96
+ f"Set {LIBRARY_ENV} to its full path, or build it: dotnet publish src/CoreIdml.Native -c Release -r {rid}"
97
+ )
98
+
99
+
100
+ def _bind(library: ctypes.CDLL, path: str, source: str) -> None:
101
+ """Checks the ABI, then gives every function its signature (from the generated table)."""
102
+ try:
103
+ abi = library.coreidml_abi_version
104
+ except AttributeError as error:
105
+ raise IdmlError(f"{path} (from {source}) is not the CoreIdml native library: it has no coreidml_abi_version.") from error
106
+ abi.restype, abi.argtypes = SIGNATURES["coreidml_abi_version"]
107
+ if abi() != ABI_VERSION:
108
+ raise IdmlError(
109
+ f"The native library at {path} (from {source}) has ABI version {abi()}; this package needs {ABI_VERSION}. "
110
+ "Use the library and the package from the same release."
111
+ )
112
+ for name, (restype, argtypes) in SIGNATURES.items():
113
+ try:
114
+ function = getattr(library, name)
115
+ except AttributeError as error:
116
+ raise IdmlError(f"The native library at {path} (from {source}) has no {name}; it is older than this package.") from error
117
+ function.restype = restype
118
+ function.argtypes = argtypes
119
+
120
+
121
+ def native() -> ctypes.CDLL:
122
+ """The loaded library (loads it if needed)."""
123
+ return _lib if _lib is not None else load()
124
+
125
+
126
+ def version() -> str:
127
+ """Version of the native library."""
128
+ text: bytes = native().coreidml_version()
129
+ return text.decode("utf-8")
130
+
131
+
132
+ def library_path() -> str:
133
+ """Path the native library was loaded from."""
134
+ native()
135
+ return _path or ""
136
+
137
+
138
+ def check(status: int) -> None:
139
+ """Raises the ``IdmlError`` of a failed call; the message is read on the thread that made the call."""
140
+ if status == Status.OK:
141
+ return
142
+ message = native().coreidml_last_error_message()
143
+ try:
144
+ code = Status(status)
145
+ except ValueError: # a status newer than this package
146
+ code = Status.FAILED
147
+ raise IdmlError(message.decode("utf-8") if message else f"The call failed with status {status}.", code)
148
+
149
+
150
+ def release(*pointers: ctypes.c_void_p) -> None:
151
+ """Releases what a failed call handed out, without reading it (the error was read first)."""
152
+ for pointer in pointers:
153
+ if pointer.value:
154
+ native().coreidml_free(pointer)
155
+
156
+
157
+ def take_bytes(pointer: ctypes.c_void_p, length: int) -> bytes:
158
+ """Copies a buffer the library handed out, and releases it."""
159
+ try:
160
+ return ctypes.string_at(pointer.value, length) if pointer.value and length else b""
161
+ finally:
162
+ native().coreidml_free(pointer)
163
+
164
+
165
+ def take_text(pointer: ctypes.c_void_p) -> str:
166
+ """Copies a NUL-terminated UTF-8 string the library handed out, and releases it."""
167
+ try:
168
+ return ctypes.string_at(pointer.value).decode("utf-8") if pointer.value else ""
169
+ finally:
170
+ native().coreidml_free(pointer)
coreidml/py.typed ADDED
File without changes
@@ -0,0 +1,317 @@
1
+ Metadata-Version: 2.4
2
+ Name: coreidml
3
+ Version: 0.0.8
4
+ Summary: Create, read, edit and print Adobe InDesign IDML files without InDesign: templates, stories, links, XML, PDF export and import.
5
+ Author: Eduard Paul
6
+ License-Expression: MIT
7
+ Project-URL: Homepage, https://github.com/eduardpaul/CoreIdml
8
+ Project-URL: Repository, https://github.com/eduardpaul/CoreIdml
9
+ Project-URL: Issues, https://github.com/eduardpaul/CoreIdml/issues
10
+ Keywords: indesign,idml,adobe,dtp,print,publishing,layout,pdf,template
11
+ Classifier: Development Status :: 3 - Alpha
12
+ Classifier: Intended Audience :: Developers
13
+ Classifier: Programming Language :: Python :: 3
14
+ Classifier: Topic :: Multimedia :: Graphics
15
+ Classifier: Topic :: Printing
16
+ Classifier: Topic :: Text Processing :: Markup :: XML
17
+ Classifier: Typing :: Typed
18
+ Requires-Python: >=3.10
19
+ Description-Content-Type: text/markdown
20
+ License-File: LICENSE
21
+ Dynamic: license-file
22
+
23
+ # coreidml
24
+
25
+ **Create, read, edit and print Adobe InDesign IDML files from Python, without InDesign.**
26
+
27
+ IDML is InDesign's open interchange format: a zip package of XML parts (spreads, stories, styles). CoreIdml builds
28
+ documents from a JSON-like spec, fills templates, edits stories, links and XML, merges pages, renders PDFs and turns
29
+ PDFs back into editable documents, and writes files that InDesign opens as if nothing but your edit had happened.
30
+
31
+ ```sh
32
+ pip install coreidml
33
+ ```
34
+
35
+ ```python
36
+ import coreidml
37
+
38
+ with coreidml.Document.open("brochure.idml") as doc:
39
+ doc.fill({"text": {"customer": "Ana Pérez", "date": "18 Nov 2026"}})
40
+ doc.replace_text("2025", "2026")
41
+ doc.save_file("brochure-ana.idml")
42
+ report = doc.export_pdf("brochure-ana.pdf", {"fontDirectories": ["fonts"]})
43
+ print(report["pageCount"], "pages;", len(report["missingFonts"]), "fonts substituted")
44
+ ```
45
+
46
+ ## Why CoreIdml
47
+
48
+ - **Surgical edits.** A part you do not touch is written back byte for byte. Change one story, and the designer's
49
+ file differs in exactly that story. (Unzipping and re-zipping with `zipfile` rewrites every entry.)
50
+ - **Output InDesign accepts.** `mimetype` first and uncompressed, InDesign's own formatting for what you change.
51
+ - **Built for programs and agents.** A size-controlled JSON summary of pages, frames, stories and links; indexed
52
+ text runs to edit; a validator and a diff to check the result.
53
+ - **PDF both ways, no InDesign.** Its own PDF writer with font embedding, and a PDF importer that rebuilds editable
54
+ frames and styles.
55
+ - **Safe with files from anywhere.** Checksums verified on read, document type declarations refused, typed errors.
56
+ - **Nothing to compile.** The engine is a prebuilt native library inside the wheel, called with `ctypes`. No
57
+ dependencies, no .NET runtime, no InDesign.
58
+
59
+ Type hints are included (`py.typed`).
60
+
61
+ ## API
62
+
63
+ ### Getting a document
64
+
65
+ ```python
66
+ from coreidml import Document
67
+
68
+ doc = Document.open("brochure.idml") # a str or os.PathLike
69
+ doc = Document.open(data) # bytes, bytearray or memoryview; not kept after the call
70
+ doc = Document.create(spec) # from a document spec (below); Document.create() is one blank A4 page
71
+ doc, report = Document.import_pdf("flyer.pdf", {"imageDirectory": "flyer-links"}) # see PDF
72
+ ```
73
+
74
+ A document is a context manager; outside a `with` block, call `doc.close()` when you are done. One that is
75
+ forgotten is released when it is garbage collected.
76
+
77
+ Options, specs and fill data are `dict`s (or the same as JSON text) with the camelCase keys shown here; results are
78
+ `dict`s. Paths are `str` or `os.PathLike`.
79
+
80
+ ### `Document`
81
+
82
+ | Member | |
83
+ | --- | --- |
84
+ | **Reading** | |
85
+ | `summary(options=None)` | Pages, frames with positions and text, stories, links, styles, swatches, layers, tags, fonts. |
86
+ | `story(story_id)` | One story in full: its text, frames and every content run with its index and styles. |
87
+ | `xml_structure()` | The XML structure as a tree of `dict`s, or `None` when there is none. |
88
+ | `export_xml(at=None)` | The XML structure as XML, or the subtree at a path such as `"/Root/article[2]"`. |
89
+ | `validate()` | Checks references, ids, layers, threads and XML bindings: `{"isValid": True, "issues": []}`. |
90
+ | `diff(other)` | What changed from this document to `other`: stories run by run, links, page count. |
91
+ | **Editing** | |
92
+ | `fill(data)` | Fills a template; returns which keys were `filled` and which are `missing`. |
93
+ | `replace_text(find, replacement)` | Replaces text in every story; returns how many times. |
94
+ | `set_run_text(story_id, run_index, text, force=False)` | Sets one run's text and keeps its formatting. |
95
+ | `relink(link_id, uri_or_path, refit=False)` | Points an image link at another file. |
96
+ | `import_xml(xml, at=None, options=None)` | Imports XML onto the structure; returns a report. |
97
+ | `import_pages(source, pages=())` | Appends pages of another document, or of itself; returns how many. |
98
+ | `apply(spec)` | Adds the colours, styles and pages of a spec to the document. |
99
+ | **Saving** | |
100
+ | `save()` | The document as the `bytes` of an .idml file. |
101
+ | `save_file(path)` | Writes the .idml file. |
102
+ | `export_pdf(path, options=None, progress=None)` | Renders a PDF file; returns a report. |
103
+ | `export_pdf_bytes(options=None, progress=None)` | Renders a PDF in memory; returns `(pdf_bytes, report)`. |
104
+ | **Package parts** | |
105
+ | `info()` | The parts of the package and the manifest (`domVersion`, `parts`, `spreads`, `masterSpreads`, `stories`). |
106
+ | `read_part(path)`, `read_text(path)` | One part (e.g. `"Stories/Story_u188.xml"`) as `bytes` or `str`, exactly as it would be saved now. |
107
+ | `write_part(path, data)` | Adds or replaces a part with a `str` (written as UTF-8) or bytes. |
108
+ | `close()`, `closed` | Releases the document; whether it was released. |
109
+
110
+ ### Creating documents
111
+
112
+ A spec describes the page, colours, styles and pages of items: text, images, tables, rectangles and lines.
113
+
114
+ ```python
115
+ spec = {
116
+ "unit": "mm", # pt (default), mm, cm or in
117
+ "page": {"size": "A4", "margins": {"all": 15}},
118
+ "colors": [{"name": "Brand", "cmyk": [75, 45, 0, 10]}, {"name": "Web", "hex": "#2E86C1"}],
119
+ "paragraphStyles": [{"name": "Title", "size": 22, "fontStyle": "Bold", "color": "Brand"}],
120
+ "characterStyles": [{"name": "Strong", "fontStyle": "Bold"}],
121
+ "pages": [{"items": [
122
+ {"type": "text", "name": "title", "x": 15, "y": 15, "width": 180, "height": 15,
123
+ "text": "Order {{number}}", "style": "Title"},
124
+ {"type": "text", "x": 15, "y": 35, "width": 180, "height": 10,
125
+ "paragraphs": [{"runs": [{"text": "Status: "}, {"text": "paid", "style": "Strong"}]}]},
126
+ {"type": "table", "x": 15, "y": 50, "width": 120, "height": 30, "headerRows": 1,
127
+ "rows": [["Item", "Qty"], ["Poster A2", "3"]]},
128
+ {"type": "rectangle", "x": 0, "y": 287, "width": 210, "height": 10, "fill": "Brand"},
129
+ {"type": "line", "x": 15, "y": 45, "x2": 195, "y2": 45, "stroke": "Brand", "strokeWeight": 0.5},
130
+ ]}],
131
+ }
132
+
133
+ with Document.create(spec) as doc:
134
+ doc.fill({"text": {"number": "F-001"}})
135
+ doc.save_file("order.idml")
136
+ ```
137
+
138
+ Images are `{"type": "image", "path": "/photos/a.jpg", "fit": "fill", ...}`; IDML links images, so ship the files
139
+ with the document. Every item also takes `name`, `label`, `tag` (to appear in the XML structure), `layer`,
140
+ `fill`, `stroke`, `strokeWeight` and `rotation`. `doc.apply(spec)` adds a spec's styles and pages to an existing
141
+ document.
142
+
143
+ ### Templates and text
144
+
145
+ ```python
146
+ with Document.open("certificate.idml") as doc:
147
+ report = doc.fill({
148
+ "text": {"name": "Ana Pérez", "course": "Typography"}, # frame names, script labels, XML tags, {{placeholders}}
149
+ "images": {"photo": "/photos/ana.jpg"}, # the file must exist: it is measured to fit
150
+ })
151
+ # {"filled": {"name": 1, "course": 1, "photo": 1}, "missing": []}
152
+
153
+ summary = doc.summary({"pages": [0], "sections": ["pages", "stories"], "maxTextLength": 80})
154
+ for item in summary["pages"][0]["items"]:
155
+ print(item["kind"], item.get("name"), item.get("text"))
156
+
157
+ story_id = summary["stories"][0]["id"]
158
+ for run in doc.story(story_id)["runs"]:
159
+ print(run["index"], run["characterStyle"], run["text"])
160
+ doc.set_run_text(story_id, 0, "Ana Pérez García") # keeps the run's formatting
161
+ ```
162
+
163
+ Summary options: `maxTextLength` (200), `includeRuns` (`False`), `includeResources` (`True`), `pages` (0-based
164
+ indices) and `sections` (any of `"pages"`, `"stories"`, `"links"`, `"offPage"`, `"resources"`). A run holding special
165
+ characters, such as a page number, is only overwritten with `force=True`.
166
+
167
+ ### Links
168
+
169
+ ```python
170
+ for link in doc.summary({"sections": ["links"]})["links"]:
171
+ print(link["id"], link["uri"], link["effectivePpi"])
172
+
173
+ doc.relink("u21a", "/photos/new-cover.jpg", refit=True) # a local path or a URI
174
+ ```
175
+
176
+ With `refit=True` and a readable local JPEG or PNG, the image is measured again and fitted to its frame.
177
+
178
+ ### XML
179
+
180
+ Tagged templates work as in SimpleIDML: `simpleidml-setcontent`, `-ignorecontent`, `-forcecontent` and `href`.
181
+
182
+ ```python
183
+ with Document.open("article.idml") as doc:
184
+ doc.xml_structure() # {"tag": "Root", "path": "/Root", "children": [...]}
185
+ report = doc.import_xml(xml_text, at="/Root/module", options={"characterStyles": {"b": "Bold"}})
186
+ # {"updated": 6, "added": 0, "deleted": 0, "unmatched": [], "warnings": []}
187
+ print(doc.export_xml("/Root/module/headline"))
188
+ ```
189
+
190
+ `xml` is a `str` or UTF-8 bytes. Import options: `fit`, `characterStyles` (an inline tag to a character style of
191
+ the document, here `<b>` to `Bold`) and `relinkOnly`.
192
+
193
+ ### Merging pages, checking the result
194
+
195
+ ```python
196
+ with Document.open("catalog.idml") as doc, Document.open("insert.idml") as insert:
197
+ doc.import_pages(insert) # every page; styles, swatches and tags are merged once
198
+ doc.import_pages(doc, [0]) # a copy of its own first page, at the end
199
+ assert doc.validate()["isValid"]
200
+ with Document.open("catalog.idml") as before:
201
+ print(before.diff(doc)["changes"])
202
+ ```
203
+
204
+ ### PDF
205
+
206
+ ```python
207
+ with Document.open("brochure.idml") as doc:
208
+ report = doc.export_pdf("brochure.pdf", {
209
+ "fontDirectories": ["fonts"], # .ttf/.otf files the document uses
210
+ "substitutions": {"Minion Pro": "Liberation Serif"}, # family replacements
211
+ "linkDirectories": ["photos"], # linked images are found by file name
212
+ })
213
+ pdf, report = doc.export_pdf_bytes({"pages": [1], "useSystemFonts": False})
214
+ ```
215
+
216
+ The report says what to check: `pageCount`, `missingFonts` (each with the font used instead, its pages and
217
+ stories), `missingImages`, `oversetStories` and `warnings`.
218
+
219
+ - **Fonts.** Fonts are embedded (TrueType as subsets). They are searched in `fontDirectories` and, unless
220
+ `useSystemFonts` is `False`, in the fonts installed on the machine. Without any match, a standard PDF font stands
221
+ in, not embedded. For the same output on every machine, ship the fonts and pass `"useSystemFonts": False`.
222
+ - **Links.** IDML links images. They are found at their recorded location, by file name in `linkDirectories`, or
223
+ through `linkRemap` (`{"old.jpg": "/new/path.jpg"}`). `documentPath`, where the .idml file lives, resolves relative
224
+ links and adds that folder and its `Links` subfolder to the search.
225
+ `maxImageDpi` and `jpegQuality` keep the PDF small.
226
+ - **Pages.** `pages` lists 1-based page numbers.
227
+
228
+ The other way, `Document.import_pdf` rebuilds an editable document from a PDF path or bytes: text frames with
229
+ inferred paragraph and character styles, image frames and shapes. Images are written to `imageDirectory`.
230
+
231
+ ```python
232
+ doc, report = Document.import_pdf(pdf_bytes, {"imageDirectory": "imported-links", "fontDirectories": ["fonts"]})
233
+ with doc:
234
+ doc.save_file("imported.idml")
235
+ # report: textFrames, imageFrames, shapes, images, fonts (and whether each is available), warnings
236
+ ```
237
+
238
+ Import options: `pages` (1-based), `imageDirectory`, `preserveLineBreaks`, `importShapes` and `fontDirectories`.
239
+
240
+ #### Progress and cancelling
241
+
242
+ The PDF calls take `progress(done, total)`, called after each page on the calling thread. Return `False` to cancel;
243
+ the call then raises `IdmlError` with `Status.CANCELLED`. An exception raised in the callback also cancels, and is
244
+ raised again from the call.
245
+
246
+ ```python
247
+ def progress(done, total):
248
+ print(f"page {done} of {total}")
249
+ return not stop_requested.is_set()
250
+
251
+ pdf, report = doc.export_pdf_bytes(progress=progress)
252
+ ```
253
+
254
+ ### Errors
255
+
256
+ Every failure is a `coreidml.IdmlError` with a `code`, a member of `coreidml.Status`, and a message that says what
257
+ went wrong:
258
+
259
+ ```python
260
+ from coreidml import Document, IdmlError, Status
261
+
262
+ try:
263
+ doc.set_run_text(story_id, 3, "New text")
264
+ except IdmlError as error:
265
+ if error.code == Status.NOT_FOUND:
266
+ ... # str(error): 'Story "u10a" has 1 content run(s); run index 3 does not exist.'
267
+ ```
268
+
269
+ | `Status` | Meaning |
270
+ | --- | --- |
271
+ | `INVALID_FORMAT` | The input is not a usable IDML package. |
272
+ | `NOT_FOUND` | Something you named does not exist: a part, story, run, link, page or XML element. |
273
+ | `INVALID_ARGUMENT` | An argument is missing or malformed, such as an option that is not valid JSON. |
274
+ | `INVALID_HANDLE` | The document was closed. |
275
+ | `CANCELLED` | A progress callback cancelled the call. |
276
+ | `IO` | Reading or writing a file failed. |
277
+ | `INVALID_OPERATION` | The call is not valid right now, such as importing XML that is not well-formed. |
278
+ | `UNSUPPORTED` | The document uses something the library does not handle. |
279
+ | `FAILED` | Anything unexpected; the message names it. |
280
+
281
+ ### The library
282
+
283
+ ```python
284
+ coreidml.version() # version of the engine
285
+ coreidml.library_path() # where the native library was loaded from
286
+ ```
287
+
288
+ ## Platforms
289
+
290
+ Wheels carry the native library for Windows x64 and Linux x64 (glibc).
291
+
292
+ Python 3.10 or later; the wheels are not tied to a Python version. x64 processors need x86-64-v2 (anything from
293
+ the last decade).
294
+
295
+ On another platform, or to use a library you built yourself, point the package at it before first use:
296
+
297
+ ```sh
298
+ COREIDML_LIBRARY=/path/to/libcoreidml.so python app.py
299
+ ```
300
+
301
+ ```python
302
+ coreidml.load("/path/to/libcoreidml.so")
303
+ ```
304
+
305
+ ## Good to know
306
+
307
+ - A document may be used from several threads; calls on one document are serialized. The engine does its work
308
+ outside the GIL.
309
+ - A process uses one copy of the library.
310
+ - The PDF export is not InDesign: the line breaker is greedy (InDesign's default is the paragraph composer), and a
311
+ missing font changes line breaks. Check `missingFonts` and `oversetStories` in the report.
312
+ - Images are linked, not embedded, as IDML always does: send generated files together with their images.
313
+
314
+ Source, other languages (.NET, Node.js, the browser, Dart/Flutter, C) and issues:
315
+ [github.com/eduardpaul/CoreIdml](https://github.com/eduardpaul/CoreIdml).
316
+
317
+ MIT licensed. CoreIdml is an independent project and is not affiliated with Adobe.
@@ -0,0 +1,11 @@
1
+ coreidml/__init__.py,sha256=a_UMv8g7DnT63-MfFwH2oEE0yXDrimdEc-VgwFSpHo4,792
2
+ coreidml/_abi.py,sha256=-31A0Ob5lh0b8zavSGn0-kAyo-l15DqeNIVZQgYeKj8,4613
3
+ coreidml/_document.py,sha256=H56Gje_h0qdVUUq7rl3uauyyh9nk_nmtsHzYMUbyQso,20570
4
+ coreidml/_native.py,sha256=FGO4DZlrX_tt1V9HV1t2d65HcXqyRyyby2Dmcor_rh4,6784
5
+ coreidml/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
6
+ coreidml/_lib/coreidml.dll,sha256=gFLsIyh5coMhPii7n44MC5Xa2BJ_u8nQ4HpJDOPr7Qk,16810496
7
+ coreidml-0.0.8.dist-info/licenses/LICENSE,sha256=p1Pq_UPnDSHVt8w81qKhn9BUl_FycD9b1wIezxlipRg,1068
8
+ coreidml-0.0.8.dist-info/METADATA,sha256=mKe5k1-He6rRSYyMHD-mO92MsyCTEJUy8N2wTPIbuJk,15263
9
+ coreidml-0.0.8.dist-info/WHEEL,sha256=MeHYnn3dJDyOdmwbmKeeTp6EsuI4RKEVPLYFUebszcw,98
10
+ coreidml-0.0.8.dist-info/top_level.txt,sha256=yE2WF6JMD_KgXV5-tRm3meZjGSQxqd0QzQNhMdTvw00,9
11
+ coreidml-0.0.8.dist-info/RECORD,,
@@ -0,0 +1,5 @@
1
+ Wheel-Version: 1.0
2
+ Generator: setuptools (84.2.1)
3
+ Root-Is-Purelib: false
4
+ Tag: py3-none-win_arm64
5
+
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Eduard Paul
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1 @@
1
+ coreidml