Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 4 additions & 12 deletions markdown_pdf/__init__.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
"""Markdown to pdf converter based on markdown_it and fitz."""
import os
import io
import typing
import pathlib
Expand All @@ -9,18 +8,11 @@
from pymupdf import (
_as_pdf_document, mupdf, JM_embedded_clean, JM_ensure_identity, JM_new_output_fileptr, ASSERT_PDF, Rect,
)
from .pligins import PLUGINS, get_plugin_chunks
from .pligins import PLUGINS, get_plugin_chunks, TempFiles

MM_2_PT = 2.835


def clear_temp_files(files):
"""Remove temp files from given list."""
for i in files:
if os.path.exists(i):
os.remove(i)


class Section:
"""Markdown section."""

Expand Down Expand Up @@ -76,7 +68,7 @@ def __init__(
self.toc_level = toc_level
self.toc = []
self.plugins = plugins or {}
self.temp_files = []
self.temp_files = TempFiles()

# zero, commonmark, js-default, gfm-like
# https://markdown-it-py.readthedocs.io/en/latest/using.html#quick-start
Expand Down Expand Up @@ -155,7 +147,7 @@ def save(self, file_name: typing.Union[str, pathlib.Path]) -> None:
else:
doc.save(file_name)
doc.close()
clear_temp_files(self.temp_files)
self.temp_files.clean()

def save_bytes(self, bytesio: io.BytesIO) -> int:
"""Save pdf to file-like object and return byte size of the filled object."""
Expand Down Expand Up @@ -191,6 +183,6 @@ def save_bytes(self, bytesio: io.BytesIO) -> int:
out = JM_new_output_fileptr(bytesio)
mupdf.pdf_write_document(pdf, out, opts)
out.fz_close_output()
clear_temp_files(self.temp_files)
self.temp_files.clean()

return bytesio.getbuffer().nbytes
21 changes: 21 additions & 0 deletions markdown_pdf/pligins/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
"""Plugins."""
import os
import uuid
from .plantuml import handler as plantuml_handler


Expand All @@ -8,6 +10,25 @@ class Plugin:
Plantuml = "plantuml"


class TempFiles:
"""Temp files for plugins."""

def __init__(self):
"""Init empty list."""
self.name_list = []

def new_name(self, ext=None):
"""Return file name with given extension."""
self.name_list.append(str(uuid.uuid4()) + ".{}".format(ext) if ext else '')
return self.name_list[-1]

def clean(self):
"""Remove temp files."""
for i in self.name_list:
if os.path.exists(i):
os.remove(i)


PLUGINS = {
Plugin.Plantuml: plantuml_handler,
}
Expand Down
13 changes: 2 additions & 11 deletions markdown_pdf/pligins/plantuml.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
"""Plantunl plugin."""
import os
import tempfile
from plantuml import PlantUML


Expand All @@ -10,17 +8,10 @@ def handler(params_dict, text, temp_files):
if not url:
return "No value for 'url' key in plantuml plugin parameters: {}".format(params_dict)

text = '\n'.join(text.splitlines()[1:-1])
server = PlantUML(url=url)
image = server.processes(text)
file_name = ''

with tempfile.NamedTemporaryFile(mode='wb', delete=False, suffix=".png") as tmp_file:
file_name = os.path.basename(tmp_file.name)
temp_files.append(tmp_file.name)
image = PlantUML(url=url).processes('\n'.join(text.splitlines()[1:-1]))
file_name = temp_files.new_name("png")

with open(file_name, mode='wb') as out:
temp_files.append(file_name)
out.write(image)

return "\n![PlantUML scheme]({})\n".format(file_name)
13 changes: 0 additions & 13 deletions tests/test/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,16 +112,3 @@ def test_paper_size(self):
with pytest.raises(TypeError) as err:
Section("Title", paper_size=111)
assert 'paper_size must be' in str(err.value)

def test_clear_temp_files(self):
"""Check clear_temp_files function."""
from markdown_pdf import clear_temp_files

files = [
self.build('tmp1.png'),
self.build('tmp2.png'),
]
with open(files[0], 'wb') as out:
out.write(b'0')

assert clear_temp_files(files) is None
18 changes: 16 additions & 2 deletions tests/test/test_plugins/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ class TestInit(TestPlugin):

def test_md(self):
"""Process md with plantuml content."""
from markdown_pdf import Section, MarkdownPdf, clear_temp_files
from markdown_pdf import Section, MarkdownPdf
from markdown_pdf.pligins import Plugin
from markdown_pdf.pligins import plantuml

Expand All @@ -32,7 +32,7 @@ def test_md(self):
text = open(self.fixture("plantuml.md"), "rt", encoding='utf-8').read()
html = pdf.add_section(Section(text))
assert "@startuml" not in html
clear_temp_files(pdf.temp_files)
pdf.temp_files.clean()

plantuml.PlantUML = saved

Expand All @@ -42,3 +42,17 @@ def test_get_plugin_chunks(self):

text = open(self.fixture("plantuml.md"), "rt", encoding='utf-8').read()
assert len(get_plugin_chunks(Plugin.Plantuml, text)) == 2

def test_temp_files(self):
"""Check temp_files class."""
from markdown_pdf.pligins import TempFiles

files = TempFiles()
files.name_list = [
self.build('tmp1.png'),
self.build('tmp2.png'),
]
with open(files.name_list[0], 'wb') as out:
out.write(b'0')

assert files.clean() is None
6 changes: 3 additions & 3 deletions tests/test/test_plugins/test_plantuml.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,7 @@ def test_www(self):

def test_handler(self):
"""Check handler function."""
from markdown_pdf import clear_temp_files
from markdown_pdf import TempFiles
from markdown_pdf.pligins import get_plugin_chunks, Plugin
from markdown_pdf.pligins import plantuml

Expand All @@ -37,7 +37,7 @@ def test_handler(self):

text = open(self.fixture("plantuml.md"), "rt", encoding='utf-8').read()
text = get_plugin_chunks(Plugin.Plantuml, text)[0]
temp_files = []
temp_files = TempFiles()
params = {}
chunk = plantuml.handler(params, text, temp_files)
assert "No value for 'url'" in chunk
Expand All @@ -50,6 +50,6 @@ def test_handler(self):
params['url'] = 'http://www.plantuml.com/plantuml/img/'
chunk = plantuml.handler(params, text, temp_files)
assert ".png" in chunk
clear_temp_files(temp_files)
temp_files.clean()

plantuml.PlantUML = saved