md2pdf 2.0.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.
md2pdf/__init__.py ADDED
@@ -0,0 +1,3 @@
1
+ """md2pdf root module."""
2
+
3
+ from .core import md2pdf # noqa
md2pdf/__main__.py ADDED
@@ -0,0 +1,13 @@
1
+ """md2pdf - Markdown to PDF conversion tool.
2
+
3
+ Usage: md2pdf [options] INPUT.MD OUTPUT.PDF
4
+
5
+ Options:
6
+ --css=STYLE.CSS
7
+ """
8
+
9
+ from . import cli
10
+
11
+ if __name__ == "__main__":
12
+ """Run the CLI."""
13
+ cli.cli()
md2pdf/cli.py ADDED
@@ -0,0 +1,26 @@
1
+ """md2pdf CLI."""
2
+
3
+ import logging
4
+ from importlib.metadata import version
5
+ from pathlib import Path
6
+ from typing import Optional
7
+
8
+ import click
9
+
10
+ from .core import md2pdf
11
+
12
+ logger = logging.getLogger(__name__)
13
+
14
+
15
+ @click.command(name="md2pdf")
16
+ @click.argument("md", type=click.Path(exists=True))
17
+ @click.argument("pdf", type=click.Path())
18
+ @click.option("--css", "css", type=click.Path(exists=True))
19
+ @click.option("--extras", "-e", "extras", multiple=True, type=str)
20
+ @click.version_option(version=version("md2pdf"))
21
+ def cli(md: Path, pdf: Path, css: Optional[Path], extras: list):
22
+ """md2pdf command line tool."""
23
+ if css is not None:
24
+ css = Path(css)
25
+
26
+ md2pdf(Path(pdf), md=Path(md), css=css, base_url=Path.cwd(), extras=list(extras))
md2pdf/conf.py ADDED
@@ -0,0 +1,8 @@
1
+ """Configuration for md2pdf."""
2
+
3
+ MARKDOWN_BASE_EXTENSIONS: list = [
4
+ "markdown.extensions.tables",
5
+ "pymdownx.magiclink",
6
+ "pymdownx.betterem",
7
+ "pymdownx.superfences",
8
+ ]
md2pdf/core.py ADDED
@@ -0,0 +1,84 @@
1
+ """md2pdf core module."""
2
+
3
+ import logging
4
+ from pathlib import Path
5
+ from typing import List, Optional
6
+
7
+ import frontmatter
8
+ from jinja2 import Template
9
+ from markdown import markdown
10
+ from weasyprint import CSS, HTML
11
+
12
+ from .conf import MARKDOWN_BASE_EXTENSIONS
13
+ from .exceptions import ValidationError
14
+
15
+ logger = logging.getLogger(__name__)
16
+
17
+
18
+ def md2pdf(
19
+ pdf: Path,
20
+ raw: Optional[str] = None,
21
+ md: Optional[Path] = None,
22
+ css: Optional[Path] = None,
23
+ base_url: Optional[Path] = None,
24
+ extras: Optional[List[str]] = None,
25
+ context: Optional[dict] = None,
26
+ ):
27
+ """Converts input markdown to styled HTML and renders it to a PDF file.
28
+
29
+ Args:
30
+ pdf: output PDF file path.
31
+ md: input markdown file path.
32
+ raw: input markdown raw string content.
33
+ css: input styles path (CSS).
34
+ base_url: absolute base path for markdown linked content (as images).
35
+ extras: supplementary markdown extensions to activate
36
+ context: input context to use for jinja template rendering
37
+
38
+ Returns:
39
+ None
40
+
41
+ Raises:
42
+ ValidationError: if md_content and md_file_path are empty.
43
+ """
44
+ context = context if context else {}
45
+
46
+ # Merge base extensions with extras extensions
47
+ extras = extras if extras and len(extras) else []
48
+
49
+ if md:
50
+ logger.debug("Reading markdown content from file %s", md)
51
+ raw = md.read_text()
52
+
53
+ if raw is None or not len(raw):
54
+ raise ValidationError(
55
+ "No markdown content to process (empty file or raw string)"
56
+ )
57
+
58
+ # Check if markdown file is a template
59
+ if frontmatter.checks(raw):
60
+ logger.info("Markdown input file contains frontmatter header")
61
+
62
+ # Get context and the template
63
+ ftmt_context, raw = frontmatter.parse(raw)
64
+ logger.debug("Frontmatter context %s", context)
65
+ context.update(ftmt_context)
66
+
67
+ # Render the template
68
+ raw = Template(raw).render(context)
69
+
70
+ extensions = MARKDOWN_BASE_EXTENSIONS + extras
71
+ raw_html = markdown(raw, extensions=extensions)
72
+
73
+ # Weasyprint HTML object
74
+ if base_url is None:
75
+ base_url = Path.cwd()
76
+ html: HTML = HTML(string=raw_html, base_url=str(base_url))
77
+
78
+ # Get styles
79
+ styles: list = []
80
+ if css:
81
+ styles.append(CSS(filename=css))
82
+
83
+ # Generate PDF
84
+ html.write_pdf(pdf, stylesheets=styles)
md2pdf/exceptions.py ADDED
@@ -0,0 +1,7 @@
1
+ """md2pdf exceptions."""
2
+
3
+
4
+ class ValidationError(Exception):
5
+ """md2pdf validation error."""
6
+
7
+ ...
@@ -0,0 +1,230 @@
1
+ Metadata-Version: 2.4
2
+ Name: md2pdf
3
+ Version: 2.0.0
4
+ Summary: The Markdown to PDF conversion tool with styles
5
+ Project-URL: Homepage, https://github.com/jmaupetit/md2pdf
6
+ Project-URL: Repository, https://github.com/jmaupetit/md2pdf
7
+ Author-email: Julien Maupetit <julien@maupetit.net>
8
+ License-Expression: MIT
9
+ License-File: LICENSE
10
+ Keywords: cli,css,html,markdown,pdf
11
+ Classifier: Development Status :: 5 - Production/Stable
12
+ Classifier: Environment :: Console
13
+ Classifier: Intended Audience :: Developers
14
+ Classifier: License :: OSI Approved :: MIT License
15
+ Classifier: Operating System :: MacOS
16
+ Classifier: Operating System :: Microsoft :: Windows
17
+ Classifier: Operating System :: POSIX
18
+ Classifier: Programming Language :: Python :: 3.10
19
+ Classifier: Programming Language :: Python :: 3.11
20
+ Classifier: Programming Language :: Python :: 3.12
21
+ Classifier: Programming Language :: Python :: 3.13
22
+ Classifier: Programming Language :: Python :: 3.14
23
+ Classifier: Topic :: Office/Business
24
+ Classifier: Topic :: Utilities
25
+ Requires-Python: >=3.10
26
+ Requires-Dist: click>=8.1
27
+ Requires-Dist: jinja2>=3
28
+ Requires-Dist: markdown>=3.5
29
+ Requires-Dist: pygments>=2.17
30
+ Requires-Dist: pymdown-extensions>=10
31
+ Requires-Dist: python-frontmatter>=1.1
32
+ Requires-Dist: weasyprint>=60
33
+ Description-Content-Type: text/markdown
34
+
35
+ ![md2pdf logo](https://github.com/jmaupetit/md2pdf/raw/main/assets/md2pdf-logo.png)
36
+
37
+ Convert Markdown files to PDF with styles.
38
+
39
+ ![GitHub Actions Workflow Status](https://img.shields.io/github/actions/workflow/status/jmaupetit/md2pdf/quality.yml)
40
+ ![PyPI - Version](https://img.shields.io/pypi/v/md2pdf)
41
+
42
+
43
+ ## Installation
44
+
45
+ The easiest way to test `md2pdf` is to use `uv`:
46
+
47
+ ```bash
48
+ $ uv tool install md2pdf
49
+ ```
50
+
51
+ _Nota bene:_ ensure, Weasyprint is fully functional before using md2pdf. You
52
+ will find installation instructions in the project documentation:
53
+ [https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation](https://doc.courtbouillon.org/weasyprint/stable/first_steps.html#installation)
54
+
55
+ ## Usage
56
+
57
+ ### As a CLI
58
+
59
+ ```
60
+ Usage: md2pdf [OPTIONS] MD PDF
61
+
62
+ md2pdf command line tool.
63
+
64
+ Options:
65
+ --css PATH
66
+ -e, --extras TEXT
67
+ --version Show the version and exit.
68
+ --help Show this message and exit.
69
+ ```
70
+
71
+ For example, try to generate the project documentation with:
72
+
73
+ ```bash
74
+ $ md2pdf README.md README.pdf
75
+ ```
76
+
77
+ Optionally, you may load an external style:
78
+
79
+ ```bash
80
+ $ md2pdf \
81
+ --css examples/custom-styles.css \
82
+ README.md \
83
+ README.pdf
84
+ ```
85
+
86
+ And activate [markdown extensions from
87
+ PyMdown](https://facelessuser.github.io/pymdown-extensions/):
88
+
89
+ ```bash
90
+ $ md2pdf \
91
+ --css examples/custom-styles-with-pygments.css \
92
+ --extras 'pymdownx.emoji' \
93
+ README.md \
94
+ README.pdf
95
+ ```
96
+
97
+ > Code blocks should be properly rendered when this extension is active.
98
+
99
+ ### As a library
100
+
101
+ If you have added `md2pdf` as a dependency for your python project, you can use
102
+ `md2pdf` in your code, like:
103
+
104
+ ```python
105
+ from md2pdf.core import md2pdf
106
+
107
+ md2pdf(pdf,
108
+ md=None,
109
+ raw=None,
110
+ css=None,
111
+ base_url=None,
112
+ extras=[],
113
+ context={"foo": 1}
114
+ )
115
+ ```
116
+
117
+ Function arguments:
118
+
119
+ * `pdf`: output PDF file path
120
+ * `raw`: input markdown raw string content (can contain Jinja instructions)
121
+ * `md`: input markdown file path (can contain Jinja instructions)
122
+ * `css`: input styles path (CSS)
123
+ * `base_url`: absolute base path for markdown linked content (as images)
124
+ * `extras`: [markdown extra
125
+ extensions](https://python-markdown.github.io/extensions/) that should be
126
+ activated
127
+ * `context`: variables to inject to rendered Jinja template
128
+
129
+ ### With Docker
130
+
131
+ Install [Docker](https://www.docker.com/)
132
+
133
+ Pull the image:
134
+
135
+ ```bash
136
+ $ docker pull jmaupetit/md2pdf
137
+ ```
138
+
139
+ Now run your image:
140
+
141
+ ```bash
142
+ $ docker run --rm \
143
+ -v $PWD:/app \
144
+ -u "$(id -u):$(id -g)" \
145
+ jmaupetit/md2pdf --css styles.css INPUT.MD OUTPUT.PDF
146
+ ```
147
+
148
+ ### Use Jinja templates as input
149
+
150
+ Your input markdown file or raw content can include
151
+ [Jinja](https://jinja.palletsprojects.com/en/stable/) template tags, and
152
+ context can be given in a frontmatter header:
153
+
154
+ ```md
155
+ ---
156
+ groceries:
157
+ - name: apple
158
+ quantity: 4
159
+ - name: orange
160
+ quantity: 10
161
+ - name: banana
162
+ quantity: 6
163
+ ---
164
+
165
+ # Groceries
166
+
167
+ | Item | Quantity |
168
+ | ---- | -------- |
169
+ {% for item in groceries -%}
170
+ | {{ item.name }} | {{ item.quantity }} |
171
+ {% endfor %}
172
+
173
+ ```
174
+
175
+ Or directly as a `md2pdf` argument (see library usage).
176
+
177
+ You can test this example using:
178
+
179
+ ```bash
180
+ $ md2pdf \
181
+ --css examples/gutenberg-modern.min.css \
182
+ examples/my-music.md.j2 \
183
+ examples/my-music.pdf
184
+ ```
185
+
186
+ ## Contributing
187
+
188
+ ### Hacking
189
+
190
+ Clone this project first:
191
+
192
+ ```bash
193
+ $ git clone git@github.com:jmaupetit/md2pdf.git
194
+ ```
195
+
196
+ Install md2pdf along with its dependencies (using
197
+ [uv](https://docs.astral.sh/uv/)):
198
+
199
+ ```bash
200
+ $ cd md2pdf
201
+ $ make bootstrap
202
+ ```
203
+
204
+ ### Running the test suite
205
+
206
+ To run the test suite:
207
+
208
+ ```bash
209
+ $ make test
210
+ ```
211
+
212
+ Lint the code via:
213
+
214
+ ```bash
215
+ $ make lint
216
+ ```
217
+
218
+ ### Ease your life
219
+
220
+ If you are familiar with GNU Make, we also automate daily tasks using this
221
+ lovely tool:
222
+
223
+ ```bash
224
+ $ make help
225
+ ```
226
+
227
+ ## License
228
+
229
+ `md2pdf` is released under the MIT License. See the bundled LICENSE file for
230
+ details.
@@ -0,0 +1,11 @@
1
+ md2pdf/__init__.py,sha256=svAmxcAHEh102PY0uskIMOzJvteyYcuVeSWm44bPbxA,60
2
+ md2pdf/__main__.py,sha256=TI5FLWwSUkU937m3mPdYtwFneAUhciXwAAwmO1OZj_w,208
3
+ md2pdf/cli.py,sha256=pud98L701q4gXuObgW1TMZZN_genE9MFsDumCO2xqRg,742
4
+ md2pdf/conf.py,sha256=gVvhpjhi44w4lLs3WB4qAqIk2FQD7OZNABneKA2RBus,183
5
+ md2pdf/core.py,sha256=55eYVbeoulaYtm3X0T1UfOex-FcU1BJFOl5N6yEQn7c,2352
6
+ md2pdf/exceptions.py,sha256=dmlkVvU8gcI5-FOUoxDKwfWWKI36ssyhYV-tD9v_0IQ,105
7
+ md2pdf-2.0.0.dist-info/METADATA,sha256=-XAVAtioacRrLUaHrk2_Uyk_schx-mZ2pNoaViRCkuk,5145
8
+ md2pdf-2.0.0.dist-info/WHEEL,sha256=WLgqFyCfm_KASv4WHyYy0P3pM_m7J5L9k2skdKLirC8,87
9
+ md2pdf-2.0.0.dist-info/entry_points.txt,sha256=a_JVhGnlXdKQbvjTVJRzzPuUym6YSKBUlRFWJL7wpbc,51
10
+ md2pdf-2.0.0.dist-info/licenses/LICENSE,sha256=1MSsMGGnW3w8Khbk5FBaWWuamw1lnTODJYHi5EknmgM,1064
11
+ md2pdf-2.0.0.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.28.0
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,2 @@
1
+ [console_scripts]
2
+ md2pdf = md2pdf.__main__:cli.cli
@@ -0,0 +1,18 @@
1
+ Copyright (C) 2013-2016 Julien Maupetit
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of
4
+ this software and associated documentation files (the "Software"), to deal in
5
+ the Software without restriction, including without limitation the rights to
6
+ use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
7
+ the Software, and to permit persons to whom the Software is furnished to do so,
8
+ subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in all
11
+ copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
15
+ FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
16
+ COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.