markdown-pdf 1.11__tar.gz → 1.13__tar.gz

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.
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: markdown_pdf
3
- Version: 1.11
3
+ Version: 1.13
4
4
  Summary: Markdown to pdf renderer
5
5
  Author-email: Vitaly Bogomolov <mail@vitaly-bogomolov.ru>
6
6
  License-Expression: AGPL-3.0-only
@@ -33,7 +33,7 @@ Dynamic: license-file
33
33
  [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/27b53043bff34f07bfb79ee1672b7ba0)](https://app.codacy.com/gh/vb64/markdown-pdf/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
34
34
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/markdown-pdf?label=pypi%20installs)](https://pypistats.org/packages/markdown-pdf)
35
35
 
36
- The free, open source Python module `markdown-pdf` will create a PDF file from your content in `markdown` format.
36
+ The free, open source Python module `markdown-pdf` will create a PDF file from your `markdown` content.
37
37
 
38
38
  When creating a PDF file you can:
39
39
 
@@ -45,7 +45,7 @@ When creating a PDF file you can:
45
45
  - Use different page sizes within single pdf
46
46
  - Create tables in `markdown`
47
47
  - Use clickable hyperlinks. Thanks a lot [@thongtmtrust](https://github.com/thongtmtrust) for ideas and collaboration.
48
- - Use the plantuml content plugin
48
+ - Render plantuml and mermaid code to pdf images with [plugins](plugins.md).
49
49
 
50
50
  The module utilizes the functions of two great libraries.
51
51
 
@@ -69,11 +69,15 @@ pdf = MarkdownPdf(toc_level=2, optimize=True)
69
69
  ```
70
70
 
71
71
  Add the first section to the pdf. The title is not included in the table of contents.
72
+ After adding a section to a pdf, the `page_count` property in the section contains the number of pdf pages created for the added section.
72
73
 
73
74
  ```python
74
75
  from markdown_pdf import Section
75
76
 
76
- pdf.add_section(Section("# Title\n", toc=False))
77
+ section = Section("# Title\n", toc=False)
78
+ assert section.page_count == 0
79
+ pdf.add_section(section)
80
+ assert section.page_count == 1
77
81
  ```
78
82
 
79
83
  Add a second section with external and internal hyperlinks.
@@ -124,6 +128,12 @@ css = "table, th, td {border: 1px solid black;}"
124
128
  pdf.add_section(Section(text), user_css=css)
125
129
  ```
126
130
 
131
+ The `sections` property of the `MarkdownPdf` class contains a list of added sections in the order in which they were added.
132
+
133
+ ```python
134
+ assert len(pdf.sections) > 1
135
+ ```
136
+
127
137
  Set the properties of the pdf document.
128
138
 
129
139
  ```python
@@ -234,6 +244,8 @@ In the created file `plantuml.pdf`, you will see the following result:
234
244
 
235
245
  ![With plantuml.jpg](img/with_plantuml.jpg)
236
246
 
247
+ You can find a more detailed description of the plugins [here](plugins.md).
248
+
237
249
  ## Example
238
250
 
239
251
  As an example, you can download the [pdf file](examples/markdown_pdf.pdf) created from this md file.
@@ -6,7 +6,7 @@
6
6
  [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/27b53043bff34f07bfb79ee1672b7ba0)](https://app.codacy.com/gh/vb64/markdown-pdf/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
7
7
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/markdown-pdf?label=pypi%20installs)](https://pypistats.org/packages/markdown-pdf)
8
8
 
9
- The free, open source Python module `markdown-pdf` will create a PDF file from your content in `markdown` format.
9
+ The free, open source Python module `markdown-pdf` will create a PDF file from your `markdown` content.
10
10
 
11
11
  When creating a PDF file you can:
12
12
 
@@ -18,7 +18,7 @@ When creating a PDF file you can:
18
18
  - Use different page sizes within single pdf
19
19
  - Create tables in `markdown`
20
20
  - Use clickable hyperlinks. Thanks a lot [@thongtmtrust](https://github.com/thongtmtrust) for ideas and collaboration.
21
- - Use the plantuml content plugin
21
+ - Render plantuml and mermaid code to pdf images with [plugins](plugins.md).
22
22
 
23
23
  The module utilizes the functions of two great libraries.
24
24
 
@@ -42,11 +42,15 @@ pdf = MarkdownPdf(toc_level=2, optimize=True)
42
42
  ```
43
43
 
44
44
  Add the first section to the pdf. The title is not included in the table of contents.
45
+ After adding a section to a pdf, the `page_count` property in the section contains the number of pdf pages created for the added section.
45
46
 
46
47
  ```python
47
48
  from markdown_pdf import Section
48
49
 
49
- pdf.add_section(Section("# Title\n", toc=False))
50
+ section = Section("# Title\n", toc=False)
51
+ assert section.page_count == 0
52
+ pdf.add_section(section)
53
+ assert section.page_count == 1
50
54
  ```
51
55
 
52
56
  Add a second section with external and internal hyperlinks.
@@ -97,6 +101,12 @@ css = "table, th, td {border: 1px solid black;}"
97
101
  pdf.add_section(Section(text), user_css=css)
98
102
  ```
99
103
 
104
+ The `sections` property of the `MarkdownPdf` class contains a list of added sections in the order in which they were added.
105
+
106
+ ```python
107
+ assert len(pdf.sections) > 1
108
+ ```
109
+
100
110
  Set the properties of the pdf document.
101
111
 
102
112
  ```python
@@ -207,6 +217,8 @@ In the created file `plantuml.pdf`, you will see the following result:
207
217
 
208
218
  ![With plantuml.jpg](img/with_plantuml.jpg)
209
219
 
220
+ You can find a more detailed description of the plugins [here](plugins.md).
221
+
210
222
  ## Example
211
223
 
212
224
  As an example, you can download the [pdf file](examples/markdown_pdf.pdf) created from this md file.
@@ -1,5 +1,4 @@
1
1
  """Markdown to pdf converter based on markdown_it and fitz."""
2
- import os
3
2
  import io
4
3
  import typing
5
4
  import pathlib
@@ -9,18 +8,11 @@ from markdown_it import MarkdownIt
9
8
  from pymupdf import (
10
9
  _as_pdf_document, mupdf, JM_embedded_clean, JM_ensure_identity, JM_new_output_fileptr, ASSERT_PDF, Rect,
11
10
  )
12
- from .pligins import PLUGINS, get_plugin_chunks
11
+ from .pligins import PLUGINS, get_plugin_chunks, TempFiles
13
12
 
14
13
  MM_2_PT = 2.835
15
14
 
16
15
 
17
- def clear_temp_files(files):
18
- """Remove temp files from given list."""
19
- for i in files:
20
- if os.path.exists(i):
21
- os.remove(i)
22
-
23
-
24
16
  class Section:
25
17
  """Markdown section."""
26
18
 
@@ -36,6 +28,7 @@ class Section:
36
28
  self.text = text
37
29
  self.toc = toc
38
30
  self.root = root
31
+ self.page_count = 0
39
32
 
40
33
  self.paper_size = paper_size
41
34
  if isinstance(paper_size, str):
@@ -76,18 +69,18 @@ class MarkdownPdf:
76
69
  self.toc_level = toc_level
77
70
  self.toc = []
78
71
  self.plugins = plugins or {}
79
- self.temp_files = []
72
+ self.temp_files = TempFiles()
80
73
 
81
74
  # zero, commonmark, js-default, gfm-like
82
75
  # https://markdown-it-py.readthedocs.io/en/latest/using.html#quick-start
83
76
  self.m_d = (MarkdownIt(mode).enable('table')) # Enable support for tables
84
77
 
85
78
  self.optimize = optimize
86
-
87
79
  self.out_file = io.BytesIO()
88
80
  self.writer = fitz.DocumentWriter(self.out_file)
89
81
  self.page_num = 0
90
82
  self.hrefs = []
83
+ self.sections = []
91
84
 
92
85
  @staticmethod
93
86
  def _recorder(elpos):
@@ -128,12 +121,15 @@ class MarkdownPdf:
128
121
  more = 1
129
122
  while more: # loop outputting the story
130
123
  self.page_num += 1
124
+ section.page_count += 1
131
125
  device = self.writer.begin_page(section.rect)
132
126
  more, _ = story.place(where) # layout into allowed rectangle
133
127
  story.element_positions(self._recorder, {"toc": section.toc, "pdfile": self})
134
128
  story.draw(device)
135
129
  self.writer.end_page()
136
130
 
131
+ self.sections.append(section)
132
+
137
133
  return html
138
134
 
139
135
  def _make_doc(self):
@@ -155,7 +151,7 @@ class MarkdownPdf:
155
151
  else:
156
152
  doc.save(file_name)
157
153
  doc.close()
158
- clear_temp_files(self.temp_files)
154
+ self.temp_files.clean()
159
155
 
160
156
  def save_bytes(self, bytesio: io.BytesIO) -> int:
161
157
  """Save pdf to file-like object and return byte size of the filled object."""
@@ -191,6 +187,6 @@ class MarkdownPdf:
191
187
  out = JM_new_output_fileptr(bytesio)
192
188
  mupdf.pdf_write_document(pdf, out, opts)
193
189
  out.fz_close_output()
194
- clear_temp_files(self.temp_files)
190
+ self.temp_files.clean()
195
191
 
196
192
  return bytesio.getbuffer().nbytes
@@ -0,0 +1,62 @@
1
+ """Plugins."""
2
+ import os
3
+ import uuid
4
+
5
+ from .plantuml import handler as plantuml_handler
6
+ from .mermaid import handler as mermaid_handler
7
+
8
+ PLUGINS = {}
9
+
10
+
11
+ class Plugin:
12
+ """Available plugins."""
13
+
14
+ Plantuml = "plantuml"
15
+ Mermaid = "mermaid"
16
+
17
+
18
+ class TempFiles:
19
+ """Temp files for plugins."""
20
+
21
+ def __init__(self):
22
+ """Init empty list."""
23
+ self.name_list = []
24
+
25
+ def new_name(self, ext=None):
26
+ """Return file name with given extension."""
27
+ self.name_list.append(str(uuid.uuid4()) + ".{}".format(ext) if ext else '')
28
+ return self.name_list[-1]
29
+
30
+ def clean(self):
31
+ """Remove temp files."""
32
+ for i in self.name_list:
33
+ if os.path.exists(i):
34
+ os.remove(i)
35
+
36
+
37
+ def register(key, handler):
38
+ """Register plugin as available."""
39
+ PLUGINS[key] = handler
40
+
41
+
42
+ def get_plugin_chunks(key, text):
43
+ """Extract key parts from given text."""
44
+ chunk = []
45
+ chunks = []
46
+
47
+ for line in text.splitlines():
48
+
49
+ if line.startswith("```{}".format(key)):
50
+ chunk = [line]
51
+ elif (line.startswith("```")) and chunk:
52
+ chunk.append(line)
53
+ chunks.append('\n'.join(chunk))
54
+ chunk = []
55
+ elif chunk:
56
+ chunk.append(line)
57
+
58
+ return chunks
59
+
60
+
61
+ register(Plugin.Plantuml, plantuml_handler)
62
+ register(Plugin.Mermaid, mermaid_handler)
@@ -0,0 +1,9 @@
1
+ """Plugin helper functions."""
2
+
3
+
4
+ def get_key(params_dict, key, default):
5
+ """Return value for key from given dict."""
6
+ if params_dict and (key in params_dict):
7
+ return params_dict.get(key)
8
+
9
+ return default
@@ -0,0 +1,25 @@
1
+ """Mermaid plugin."""
2
+ import base64
3
+ import requests
4
+
5
+ from .helpers import get_key
6
+
7
+
8
+ def handler(params_dict, text, temp_files):
9
+ """Translate mermaid marked text to png image."""
10
+ url = get_key(params_dict, 'url', 'https://mermaid.ink/img/')
11
+ code = '\n'.join(text.splitlines()[1:-1])
12
+ response = requests.get(
13
+ "{}{}".format(
14
+ url,
15
+ base64.urlsafe_b64encode(code.encode("utf-8")).decode("ascii"),
16
+ ),
17
+ params={"format": "png"},
18
+ timeout=5
19
+ )
20
+
21
+ file_name = temp_files.new_name(ext="png")
22
+ with open(file_name, mode='wb') as out:
23
+ out.write(response.content)
24
+
25
+ return "\n![Mermaid image]({})\n".format(file_name)
@@ -0,0 +1,15 @@
1
+ """Plantunl plugin."""
2
+ from plantuml import PlantUML
3
+ from .helpers import get_key
4
+
5
+
6
+ def handler(params_dict, text, temp_files):
7
+ """Translate plantunl marked text to png image."""
8
+ url = get_key(params_dict, 'url', 'http://www.plantuml.com/plantuml/img/')
9
+ image = PlantUML(url=url).processes('\n'.join(text.splitlines()[1:-1]))
10
+ file_name = temp_files.new_name("png")
11
+
12
+ with open(file_name, mode='wb') as out:
13
+ out.write(image)
14
+
15
+ return "\n![PlantUML image]({})\n".format(file_name)
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: markdown_pdf
3
- Version: 1.11
3
+ Version: 1.13
4
4
  Summary: Markdown to pdf renderer
5
5
  Author-email: Vitaly Bogomolov <mail@vitaly-bogomolov.ru>
6
6
  License-Expression: AGPL-3.0-only
@@ -33,7 +33,7 @@ Dynamic: license-file
33
33
  [![Codacy Badge](https://app.codacy.com/project/badge/Coverage/27b53043bff34f07bfb79ee1672b7ba0)](https://app.codacy.com/gh/vb64/markdown-pdf/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_coverage)
34
34
  [![PyPI - Downloads](https://img.shields.io/pypi/dm/markdown-pdf?label=pypi%20installs)](https://pypistats.org/packages/markdown-pdf)
35
35
 
36
- The free, open source Python module `markdown-pdf` will create a PDF file from your content in `markdown` format.
36
+ The free, open source Python module `markdown-pdf` will create a PDF file from your `markdown` content.
37
37
 
38
38
  When creating a PDF file you can:
39
39
 
@@ -45,7 +45,7 @@ When creating a PDF file you can:
45
45
  - Use different page sizes within single pdf
46
46
  - Create tables in `markdown`
47
47
  - Use clickable hyperlinks. Thanks a lot [@thongtmtrust](https://github.com/thongtmtrust) for ideas and collaboration.
48
- - Use the plantuml content plugin
48
+ - Render plantuml and mermaid code to pdf images with [plugins](plugins.md).
49
49
 
50
50
  The module utilizes the functions of two great libraries.
51
51
 
@@ -69,11 +69,15 @@ pdf = MarkdownPdf(toc_level=2, optimize=True)
69
69
  ```
70
70
 
71
71
  Add the first section to the pdf. The title is not included in the table of contents.
72
+ After adding a section to a pdf, the `page_count` property in the section contains the number of pdf pages created for the added section.
72
73
 
73
74
  ```python
74
75
  from markdown_pdf import Section
75
76
 
76
- pdf.add_section(Section("# Title\n", toc=False))
77
+ section = Section("# Title\n", toc=False)
78
+ assert section.page_count == 0
79
+ pdf.add_section(section)
80
+ assert section.page_count == 1
77
81
  ```
78
82
 
79
83
  Add a second section with external and internal hyperlinks.
@@ -124,6 +128,12 @@ css = "table, th, td {border: 1px solid black;}"
124
128
  pdf.add_section(Section(text), user_css=css)
125
129
  ```
126
130
 
131
+ The `sections` property of the `MarkdownPdf` class contains a list of added sections in the order in which they were added.
132
+
133
+ ```python
134
+ assert len(pdf.sections) > 1
135
+ ```
136
+
127
137
  Set the properties of the pdf document.
128
138
 
129
139
  ```python
@@ -234,6 +244,8 @@ In the created file `plantuml.pdf`, you will see the following result:
234
244
 
235
245
  ![With plantuml.jpg](img/with_plantuml.jpg)
236
246
 
247
+ You can find a more detailed description of the plugins [here](plugins.md).
248
+
237
249
  ## Example
238
250
 
239
251
  As an example, you can download the [pdf file](examples/markdown_pdf.pdf) created from this md file.
@@ -10,4 +10,6 @@ markdown_pdf.egg-info/dependency_links.txt
10
10
  markdown_pdf.egg-info/requires.txt
11
11
  markdown_pdf.egg-info/top_level.txt
12
12
  markdown_pdf/pligins/__init__.py
13
+ markdown_pdf/pligins/helpers.py
14
+ markdown_pdf/pligins/mermaid.py
13
15
  markdown_pdf/pligins/plantuml.py
@@ -7,7 +7,7 @@ build-backend = "setuptools.build_meta"
7
7
 
8
8
  [project]
9
9
  name = "markdown_pdf"
10
- version = "1.11"
10
+ version = "1.13"
11
11
  description = "Markdown to pdf renderer"
12
12
  readme = { file = "README.md", content-type = "text/markdown" }
13
13
  requires-python = ">=3.8"
@@ -54,3 +54,6 @@ filterwarnings = [
54
54
  'ignore:builtin type SwigPyObject has no __module__ attribute:DeprecationWarning',
55
55
  'ignore:builtin type SwigPyPacked has no __module__ attribute:DeprecationWarning',
56
56
  ]
57
+ markers = [
58
+ 'external: marks a test as uses external resources'
59
+ ]
@@ -1,32 +0,0 @@
1
- """Plugins."""
2
- from .plantuml import handler as plantuml_handler
3
-
4
-
5
- class Plugin:
6
- """Available plugins."""
7
-
8
- Plantuml = "plantuml"
9
-
10
-
11
- PLUGINS = {
12
- Plugin.Plantuml: plantuml_handler,
13
- }
14
-
15
-
16
- def get_plugin_chunks(key, text):
17
- """Extract key parts from given text."""
18
- chunk = []
19
- chunks = []
20
-
21
- for line in text.splitlines():
22
-
23
- if line.startswith("```{}".format(key)):
24
- chunk = [line]
25
- elif (line.startswith("```")) and chunk:
26
- chunk.append(line)
27
- chunks.append('\n'.join(chunk))
28
- chunk = []
29
- elif chunk:
30
- chunk.append(line)
31
-
32
- return chunks
@@ -1,26 +0,0 @@
1
- """Plantunl plugin."""
2
- import os
3
- import tempfile
4
- from plantuml import PlantUML
5
-
6
-
7
- def handler(params_dict, text, temp_files):
8
- """Translate plantunl marked text to png image."""
9
- url = params_dict.get("url")
10
- if not url:
11
- return "No value for 'url' key in plantuml plugin parameters: {}".format(params_dict)
12
-
13
- text = '\n'.join(text.splitlines()[1:-1])
14
- server = PlantUML(url=url)
15
- image = server.processes(text)
16
- file_name = ''
17
-
18
- with tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix=".png") as tmp_file:
19
- file_name = os.path.basename(tmp_file.name)
20
- temp_files.append(tmp_file.name)
21
-
22
- with open(file_name, mode='wb') as out:
23
- temp_files.append(file_name)
24
- out.write(image)
25
-
26
- return "\n![PlantUML scheme]({})\n".format(file_name)
File without changes
File without changes
File without changes