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
17 changes: 17 additions & 0 deletions src/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -5767,6 +5767,23 @@ def layout(self, rect=None, width=0, height=0, fontsize=11):
self._reset_page_refs()
self.init_doc()

def apply_css(self, css: str, append: bool = True):
"""Apply CSS to a reflowable document.

If 'append' evaluates to True, the CSS will be appended to
the default CSS of this document type.
Otherwise the default CSS will be ignored.
"""
if self.is_closed or self.is_encrypted:
raise ValueError("document closed or encrypted")
doc = self.this
if not mupdf.fz_is_document_reflowable(doc):
return
if not isinstance(css, str) or not css:
return
append = int(bool(append)) # ensure integer
mupdf.fz_style_document(doc, append, css)

def load_page(self, page_id):
"""Load a page.

Expand Down
31 changes: 31 additions & 0 deletions tests/test_markdown_support.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,3 +40,34 @@ def test_archive_links():
assert links[0]["uri"] == "http://www.google.com"
assert links[0]["kind"] == pymupdf.LINK_URI
assert links[1]["kind"] == pymupdf.LINK_GOTO


def test_markdown_style():
print()
if pymupdf.mupdf_version_tuple < (1, 28):
print('test_markdown_style(): not running because mupdf<1.28.')
return

font = pymupdf.Font("tiro")
arch = pymupdf.Archive(font.buffer, "tiro")

css = """@font-face {font-family: sans-serif; src: url(tiro);}"""
md = "Overriding sans-serif with Times-Roman."
for use_css in 0, 1:
md_doc = pymupdf.open(stream=md.encode(), filetype="md", archive=arch)
if use_css:
md_doc.apply_css(css) # apply the CSS to the document

md_pdf_stream = md_doc.convert_to_pdf()
with pymupdf.open(stream=md_pdf_stream) as pdf_doc:
page = pdf_doc[0]
spans = [
s for b in page.get_text("dict")["blocks"] for l in b["lines"] for s in l["spans"]
]

assert len(spans) == 1
print(f'test_markdown_style(): {use_css=} {spans[0]["font"]=}.')
if use_css:
assert "Roman" in spans[0]["font"]
else:
assert "Roman" not in spans[0]["font"]
Loading