dn
Markdown parsing and generation
To install: pip install dn
Optional Dependencies
This package supports converting various file formats to Markdown, with each format requiring specific dependencies:
Format Required Package(s)
----------- -----------------
PDF pypdf
Word mammoth
Excel pandas, openpyxl, tabulate
PowerPoint python-pptx
HTML markdownify
Notebooks nbconvert, nbformat
Ebooks calibre and/or pandoc (system tools) -- see below
Scanned PDF tesseract (system tool) + pytesseract, PyMuPDF
Installation Options
You can install these dependencies after the fact, if and when package complains it needs some specific resource.
You can also install these when installing dn, like so:
# Install with minimal dependencies
pip install dn
# Install with support for specific formats
pip install dn[pdf] # PDF conversion support
pip install dn[word] # Word document support
pip install dn[excel] # Excel support
pip install dn[powerpoint] # PowerPoint support
pip install dn[html] # HTML conversion
pip install dn[notebook] # Jupyter Notebook support
pip install dn[ebook] # EPUB (pure-python backend)
pip install dn[ocr] # OCR for scanned PDFs
# Install multiple format support
pip install dn[pdf,word,excel] # Multiple formats
# Install all optional dependencies
pip install dn[all]
Examples
To and from jupyter notebooks
from dn import markdown_to_notebook
sample_markdown = """# Sample Notebook
This is a markdown cell with some explanation.
```python
# This is a code cell
print("Hello, World!")
x = 42
print(f"The answer is {x}")
```
## Another Section
More markdown content here.
```python
# Another code cell
def greet(name):
return f"Hello, {name}!"
print(greet("Jupyter"))
```
Final markdown cell."""
Test basic functionality
notebook = markdown_to_notebook(sample_markdown)
print(f"Created notebook with {len(notebook['cells'])} cells")
Test with file output
output_path = markdown_to_notebook(sample_markdown, egress="./sample_notebook.ipynb")
print(f"Saved notebook to: {output_path}")
Created notebook with 5 cells
Saved notebook to: /Users/thorwhalen/Dropbox/py/proj/t/dn/misc/sample_notebook.ipynb
from dn import notebook_to_markdown
md_string = notebook_to_markdown(notebook)
print(md_string)
# Sample Notebook
This is a markdown cell with some explanation.
```python
# This is a code cell
print("Hello, World!")
x = 42
print(f"The answer
...
nt(greet("Jupyter"))
```
Final markdown cell.
... and other formats
from dn import pdf_to_markdown # requires pypdf
from dn import docx_to_markdown # requires mammoth
from dn import excel_to_markdown # requires pandas
from dn import pptx_to_markdown # requires python-pptx
from dn import html_to_markdown # requires markdownify
Ebooks (EPUB, MOBI, AZW3, ...)
dn converts ebooks to markdown through a registry of interchangeable backends,
tried best-first:
Backend Needs Notes
---------------- ---------------------- ------------------------------------
calibre_pandoc calibre + pandoc Best fidelity; all ebook formats
pandoc pandoc EPUB/FB2/ODT/RTF; loses CSS emphasis
calibre_txt calibre All formats; noisier output
ebooklib pip install dn[ebook] EPUB only; no external binary
Calibre and pandoc are system tools, not pip packages. Ask what you have, and how to get the rest:
from dn import check_ebook_requirements
check_ebook_requirements()
Then convert a path, a URL, or bytes:
from dn import ebook_to_markdown
md = ebook_to_markdown("book.mobi")
Ebook formats also route through the generic entry point, detected from the filename or from the file's own leading bytes:
from dn import bytes_to_markdown
md = bytes_to_markdown(epub_bytes, key="book.epub")
md = bytes_to_markdown(epub_bytes) # format sniffed from the bytes
Add your own strategy — or a whole new format — with register_ebook_backend.
Note that only unambiguous ebook extensions are auto-detected. Several formats
calibre reads are usually something else entirely (.rb is Ruby far more often
than Rocket eBook, .pdb is usually a Protein Data Bank file), so those never
get claimed from a filename; convert them by asking:
ebook_to_markdown(src, input_format='rb').
What cannot be converted. DRM-protected ebooks (Amazon KFX/AZW, Adobe-DRM
EPUB) are encrypted: no backend can read them, and you must remove the DRM
yourself — where you are legally entitled to — before converting. Image-only
containers (CBZ, CBR, DJVU) hold no text layer and are deliberately excluded from
EBOOK_FORMATS. Scanned PDFs are handled -- see the OCR section below.
Sections: a long document as addressable pieces
A book or a report is easier to search, cite and read as a list of sections than as one string. pdf_sections cuts a PDF's text at its outline (its bookmarks); markdown_sections cuts markdown at its headings. Both return the same Section records, in reading order, and a section's own text stops where its first sub-section starts, so the sections together hold the whole text.
from dn import pdf_sections, markdown_sections, pdf_outline
sections = pdf_sections("book.pdf") # needs dn[pdf]
s = sections[40]
(
s.key,
s.path,
s.page_start,
s.label_start,
) # ('0040-the-repository-pattern', ('Part I', 'The Repository Pattern'), 61, '33')
s.text # that section only, with <!-- page 34 --> markers inside
pdf_outline("book.pdf", max_level=1) # the chapters: (level, title, page, label)
markdown_sections(open("report.md").read()) # line_start / line_end instead of pages
max_level (default 3) sets how deep the cut goes; deeper headings stay inside their parent. Keys are stable for the same input and max_level: outline entry number k is always seq k, and seq 0 is reserved for the text before the first entry. For an ebook, compose: markdown_sections(ebook_to_markdown('book.epub')). A PDF with no bookmarks raises and says what to pass: outline=[OutlineEntry(level, title, page), ...] for the headings you know. page_text= swaps the text extractor (an OCR result, another library).
Scanned PDFs (OCR)
A scanned book is a PDF full of pictures of pages, so ordinary text extraction
returns nothing. dn notices and runs OCR on exactly those pages:
from dn import pdf_to_markdown
md = pdf_to_markdown(scanned_pdf_bytes) # OCRs the pages that have no text
md = pdf_to_markdown(pdf_bytes, ocr=False) # opt out (OCR costs ~1s/page)
'auto' engages only when the document has no text layer anywhere — the
scanned-book case, where the alternative is an empty result. A text PDF never
pays the OCR cost, not even one with blank or figure-only pages. For a PDF
that's mostly text with a few scanned inserts, ask explicitly:
md = pdf_to_markdown(pdf_bytes, ocr=True) # OCR every text-less page
'auto' is also opportunistic: if OCR is unavailable or fails, you still get
the plain-extraction result. ocr=True raises instead.
This needs the Tesseract binary plus pip install dn[ocr]:
from dn import check_ocr_requirements
check_ocr_requirements()
Markdown stores
User story: I have a directory with multiple files in different formats.
I want to batch convert all supported files to markdown and store them in memory.
from dn import Files, bytes_store_to_markdown_store
from dn.tests.utils_for_testing_dn import test_data_dir
# Setup source files from test directory
src_files = Files(test_data_dir)
# Setup target store as an in-memory dictionary
target_store = {}
# Convert all files in directory to markdown
result = bytes_store_to_markdown_store(src_files, target_store, verbose=False)
# Check that the result is the target_store
assert result is target_store
# Verify that the supported file types were converted correctly
supported_files = [
"test.docx",
"test.pptx",
"test.pdf",
"test.html",
"test.xlsx",
"test.txt",
"test.md",
"test.ipynb",
]
print(
f"\nSupported files (given what packages are installed here): {supported_files}\n"
)
for filename in supported_files:
assert f"{filename}.md" in target_store, f"{filename} not found in target_store"
assert len(target_store[f"{filename}.md"]) > 0, f"{filename} conversion failed"
invalid pdf header: b'PK\x03\x04\n'
EOF marker not found
EOF marker not found
invalid pdf header: b'PK\x03\x04\x14'
EOF marker not found
invalid pdf h
...
df header: b'PK\x03\x04\x14'
EOF marker not found
Supported files (given what packages are installed here): ['test.docx', 'test.pptx', 'test.pdf', 'test.html', 'test.xlsx', 'test.txt', 'test.md', 'test.ipynb']
Convert this notebook into a markdown for the README.md
from dn import notebook_to_markdown
notebook_to_markdown(
"~/Dropbox/py/proj/t/dn/misc/dn_readme.ipynb", target_file="../README.md"
)
HTML output truncated. (Data removed)
Metadata
Release files for dn 0.0.17
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| dn-0.0.17.tar.gz | 191.4 kB | Without provenance | Details for dn-0.0.17.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| dn-0.0.17-py3-none-any.whl | Python 3 | none | any | Details for dn-0.0.17-py3-none-any.whl |
Total release size: 385.0 kB
Release files / dn-0.0.17.tar.gz
| Download URL | dn-0.0.17.tar.gz |
|---|---|
| Size | 191.4 kB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
b8d9ba726361fb224f472702c0cd3c40e1082bd3a484c1856349ff35f2a18d20
|
|
BLAKE2b-256 checksum How to use checksums |
9ec13ba084c2ba27f0e2df8850e3b83b12a5dc959d059e2055f888520e02d4e9
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Release files / dn-0.0.17-py3-none-any.whl
| Download URL | dn-0.0.17-py3-none-any.whl |
|---|---|
| Size | 193.6 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
c8d70a84a16337022e79f4de33b65859349cbac3c8d7aac6b3c3dbacbac6fa50
|
|
BLAKE2b-256 checksum How to use checksums |
2dc586a9c1acedacbdcbc13ee96d604d0fb15499f05d829086805db0ab481c63
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
uv/0.13.7 {"installer":{"name":"uv","version":"0.13.7","subcommand":["publish"]},"python":null,"implementation":{"name":null,"version":null},"distro":{"name":"Ubuntu","version":"26.04","id":"resolute","libc":null},"system":{"name":null,"release":null},"cpu":null,"openssl_version":null,"setuptools_version":null,"rustc_version":null,"ci":true}
|
Security for dn 0.0.17
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.