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
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -131,7 +131,7 @@ The `Section` class can set the following attributes.

- toc: whether to include the headers `<h1>` - `<h6>` of this section in the TOC. Default is True.
- root: the name of the root directory from which the image file paths starts in markdown. Default ".".
- paper_size: name of paper size, [as described here](https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size). Default "A4".
- paper_size: either the name of a paper size, [as described here](https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size), or a list/tuple containing the width and height in mm. Default "A4".
- borders: size of borders. Default (36, 36, -36, -36).

The following document properties are available for assignment (dictionary `MarkdownPdf.meta`) with the default values indicated.
Expand Down
2 changes: 1 addition & 1 deletion README_ru.md
Original file line number Diff line number Diff line change
Expand Up @@ -124,7 +124,7 @@ assert out.getbuffer().nbytes > 0

- toc: нужно ли включать заголовки `<h1>` - `<h6>` этой секции в TOC. По умолчанию True.
- root: имя корневого каталога, от которого начинаются пути файлов картинок в markdown. По умолчанию ".".
- paper_size: название размера бумаги, [как описано здесь](https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size). По умолчанию "A4".
- paper_size: название размера бумаги, [как описано здесь](https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size), или list/tuple содержащий ширину и высоту в мм. По умолчанию "A4".
- borders: размер полей. По умолчанию (36, 36, -36, -36).

Для присвоения доступны следующие свойства документа (словарь `MarkdownPdf.meta`) с указанными значениями по умолчанию.
Expand Down
23 changes: 17 additions & 6 deletions markdown_pdf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,9 +6,11 @@
import fitz
from markdown_it import MarkdownIt
from pymupdf import (
_as_pdf_document, mupdf, JM_embedded_clean, JM_ensure_identity, JM_new_output_fileptr, ASSERT_PDF,
_as_pdf_document, mupdf, JM_embedded_clean, JM_ensure_identity, JM_new_output_fileptr, ASSERT_PDF, Rect,
)

MM_2_PT = 2.835


class Section:
"""Markdown section."""
Expand All @@ -18,15 +20,25 @@ def __init__(
text: str,
toc: bool = True,
root: str = ".",
paper_size: str = "A4",
paper_size: str or list or tuple = "A4",
borders: typing.Tuple[int, int, int, int] = (36, 36, -36, -36)
):
"""Create md section with given properties."""
self.text = text
self.toc = toc
self.root = root
# https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size

self.paper_size = paper_size
if isinstance(paper_size, str):
# https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size
self.rect = fitz.paper_rect(paper_size)
elif isinstance(paper_size, (list, tuple)):
# Other paper sizes are in pt, so need to times mm by 2.835.
width, height = paper_size
self.rect = Rect(0.0, 0.0, (width * MM_2_PT), (height * MM_2_PT))
else:
raise TypeError("paper_size must be 'str', 'tuple' or 'list'")

self.borders = borders


Expand Down Expand Up @@ -81,14 +93,13 @@ def _recorder(elpos):

def add_section(self, section: Section, user_css: typing.Optional[str] = None) -> str:
"""Add markdown section to pdf."""
rect = fitz.paper_rect(section.paper_size)
where = rect + section.borders
where = section.rect + section.borders
html = self.m_d.render(section.text)
story = fitz.Story(html=html, archive=section.root, user_css=user_css)
more = 1
while more: # loop outputting the story
self.page_num += 1
device = self.writer.begin_page(rect)
device = self.writer.begin_page(section.rect)
more, _ = story.place(where) # layout into allowed rectangle
story.element_positions(self._recorder, {"toc": section.toc, "pdfile": self})
story.draw(device)
Expand Down
18 changes: 18 additions & 0 deletions tests/test/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@
make test T=test_converter.py
"""
import io
import pytest

from . import TestBase

TABLE_TEXT = """# Section with Table
Expand Down Expand Up @@ -94,3 +96,19 @@ def test_bytes(self):
assert out.getbuffer().nbytes > 0
with open(self.build("as_bytes.pdf"), "wb") as i:
i.write(out.getvalue())

def test_paper_size(self):
"""Check paper_size arg for Section class."""
from markdown_pdf import Section

section = Section("Title") # default paper size 'A4'
assert section.rect.height == 842.0
assert section.rect.width == 595.0

section = Section("Title", paper_size=(5, 10)) # 5x10 mm
assert section.rect.height == 28.35
assert section.rect.width == 14.175

with pytest.raises(TypeError) as err:
Section("Title", paper_size=111)
assert 'paper_size must be' in str(err.value)