Skip to content

Commit

Permalink
Update Readme (#9)
Browse files Browse the repository at this point in the history
  • Loading branch information
vb64 committed Feb 28, 2024
1 parent 00f96fa commit 085fa9b
Show file tree
Hide file tree
Showing 5 changed files with 71 additions and 15 deletions.
41 changes: 34 additions & 7 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,14 +1,24 @@
# markdown-pdf
# Module markdown-pdf

[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/vb64/markdown-pdf/pep257.yml?label=Pep257&style=plastic&branch=main)](https://github.com/vb64/markdown-pdf/actions?query=workflow%3Apep257)
[![GitHub Workflow Status](https://img.shields.io/github/actions/workflow/status/vb64/markdown-pdf/py3.yml?label=Python%203.8-3.12&style=plastic&branch=main)](https://github.com/vb64/markdown-pdf/actions?query=workflow%3Apy3)
[![Codacy Badge](https://app.codacy.com/project/badge/Grade/27b53043bff34f07bfb79ee1672b7ba0)](https://app.codacy.com/gh/vb64/markdown-pdf/dashboard?utm_source=gh&utm_medium=referral&utm_content=&utm_campaign=Badge_grade)
[![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)

This is a small Python class that links two libraries:
[markdown-it-py](https://github.com/executablebooks/markdown-it-py) and
[PyMuPDF](https://github.com/pymupdf/PyMuPDF).
This class will create a PDF file from your set of `markdown` files.
The free, open source Python module `markdown-pdf` will create a PDF file from your content in `markdown` format.

When creating a PDF file you can:

- Use `UTF-8` encoded text in `markdown` in any language
- Embed images used in `markdown`
- Break text into pages in the desired order
- Create a TableOfContents (bookmarks) from markdown headings
- Tune the necessary elements using your CSS code

The module is implemented as wrapper for two wonderful libraries.

- [markdown-it-py](https://github.com/executablebooks/markdown-it-py) to convert `markdown` to `html`.
- [PyMuPDF](https://github.com/pymupdf/PyMuPDF) to convert `html` to `pdf`.

## Installation

Expand All @@ -29,13 +39,17 @@ pdf = MarkdownPdf(toc_level=2)
Add three sections of markdown to the pdf.
Each section starts on a new page.
Headings from the first section are not included in the TOC.
The second section header is centered using CSS.
The second section header is centered using CSS
and the image from the file `img/python.png` is embedded on the PDF page.

```python
from markdown_pdf import Section

pdf.add_section(Section("# Title\n", toc=False))
pdf.add_section(Section("# Head1\n\nbody\n"), user_css="h1 {text-align:center;}")
pdf.add_section(
Section("# Head1\n\n![python](img/python.png)\n\nbody\n"),
user_css="h1 {text-align:center;}"
)
pdf.add_section(Section("## Head2\n\n### Head3\n\n"))
```

Expand All @@ -54,6 +68,8 @@ pdf.save("guide.pdf")

![Pdf](img/with_toc.png)

## Settings and options

The `Section` class defines a portion of `markdown` data,
which is processed according to the same rules.
The next `Section` data starts on a new page.
Expand All @@ -64,3 +80,14 @@ The `Section` class can set the following attributes.
- 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".
- 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.

- `creationDate`: current date
- `modDate`: current date
- `creator`: "PyMuPDF library: https://pypi.org/project/PyMuPDF"
- `producer`: ""
- `title`: ""
- `author`: ""
- `subject`: ""
- `keywords`: ""
40 changes: 33 additions & 7 deletions README_ru.md
Original file line number Diff line number Diff line change
@@ -1,9 +1,19 @@
# markdown-pdf
# Модуль markdown-pdf

Это маленький класс Python, связывающий две библиотеки:
[markdown-it-py](https://github.com/executablebooks/markdown-it-py) и
[PyMuPDF](https://github.com/pymupdf/PyMuPDF).
Он позволит создать PDF файл из вашего набора файлов markdown.
Бесплатный, с открытым исходным кодом Python модуль `markdown-pdf` позволит создать PDF файл из вашего контента в формате `markdown`.

При создании PDF файла вы можете:

- Использовать в `markdown` текст на любом языке в кодировке `UTF-8`
- Встраивать используемые в `markdown` картинки
- Разбивать текст на страницы в нужном порядке
- Создавать оглавление (bookmarks) из заголовков markdown
- Оформлять нужные элементы при помощи вашего CSS кода

Модуль реализован как надстройка над двумя замечательными библиотеками.

- [markdown-it-py](https://github.com/executablebooks/markdown-it-py) для преобразования `markdown` в `html`.
- [PyMuPDF](https://github.com/pymupdf/PyMuPDF) для преобразования `html` в `pdf`.

## Установка

Expand All @@ -24,13 +34,16 @@ pdf = MarkdownPdf(toc_level=2)
Добавляем в pdf три секции markdown.
Каждая секция начинается с новой страницы.
Заголовки из первой секции не включаем в оглавление.
Заголовок второй секции центрируется при помощи CSS.
Заголовок второй секции центрируется при помощи CSS и на страницу встраивается изображение из файла `img/python.png`.

```python
from markdown_pdf import Section

pdf.add_section(Section("# Title\n", toc=False))
pdf.add_section(Section("# Head1\n\nbody\n"), user_css="h1 {text-align:center;}")
pdf.add_section(
Section("# Head1\n\n![python](img/python.png)\n\nbody\n"),
user_css="h1 {text-align:center;}"
)
pdf.add_section(Section("## Head2\n\n### Head3\n\n"))
```

Expand All @@ -49,6 +62,8 @@ pdf.save("guide.pdf")

![Pdf](img/with_toc.png)

## Настройки и опции

Класс `Section` задает порцию данных `markdown`, которые обрабатываются по единым правилам.
Данные следующего `Section` начинаются с новой страницы.

Expand All @@ -58,3 +73,14 @@ pdf.save("guide.pdf")
- root: имя корневого каталога, от которого начинаются пути файлов картинок в markdown. По умолчанию ".".
- paper_size: название размера бумаги, [как описано здесь](https://pymupdf.readthedocs.io/en/latest/functions.html#paper_size). По умолчанию "A4".
- borders: размер полей. По умолчанию (36, 36, -36, -36).

Для присвоения доступны следующие свойства документа (словарь `MarkdownPdf.meta`) с указанными значениями по умолчанию.

- `creationDate`: текущая дата
- `modDate`: текущая дата
- `creator`: "PyMuPDF library: https://pypi.org/project/PyMuPDF"
- `producer`: ""
- `title`: ""
- `author`: ""
- `subject`: ""
- `keywords`: ""
Binary file added img/python.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file modified img/with_toc.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
5 changes: 4 additions & 1 deletion tests/test/test_converter.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ def test_with_toc(self):

pdf = MarkdownPdf(toc_level=2)
pdf.add_section(Section("# Title\n", toc=False))
pdf.add_section(Section("# Head1\n\nbody\n"), user_css="h1 {text-align:center;}")
pdf.add_section(
Section("# Head1\n\n![python](img/python.png)\n\nbody\n"),
user_css="h1 {text-align:center;}"
)
pdf.add_section(Section("## Head2\n\n### Head3\n\n"))
pdf.save(self.build("with_toc.pdf"))

Expand Down

0 comments on commit 085fa9b

Please sign in to comment.