From d043cba32a6824e35a92d481dbc3d499ae0c6164 Mon Sep 17 00:00:00 2001 From: "Jorj X. McKie" Date: Wed, 27 May 2026 15:45:31 -0400 Subject: [PATCH 1/2] Add method `apply_css` to reflowable documents. --- src/__init__.py | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/src/__init__.py b/src/__init__.py index ba6f35eff..ca029b7d1 100644 --- a/src/__init__.py +++ b/src/__init__.py @@ -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. From d806ef2176ed5d3894f78cababa6d13df322eb68 Mon Sep 17 00:00:00 2001 From: Julian Smith Date: Tue, 9 Jun 2026 17:27:12 +0100 Subject: [PATCH 2/2] tests/test_markdown_support.py: add test_markdown_style(): Checks pymupdf.Document.apply_css() works as expected. --- tests/test_markdown_support.py | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/test_markdown_support.py b/tests/test_markdown_support.py index 184577dfc..76b8863ff 100644 --- a/tests/test_markdown_support.py +++ b/tests/test_markdown_support.py @@ -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"]