Last active
February 18, 2025 01:42
-
-
Save adosib/641cd120d4e5f1d584c146f01f1a2b41 to your computer and use it in GitHub Desktop.
Super simple snippet that replaces white background in a pdf with a grey one using pymupdf
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# To make those white background PDFs a little easier on the eyes | |
import pymupdf | |
doc = pymupdf.open('path/to/pdf-in.pdf') | |
background_color = (211/255, 211/255, 211/255) | |
for page in doc: | |
page.draw_rect(page.rect, color=None, fill=background_color, overlay=False) | |
doc.ez_save('path/to/pdf-out.pdf') | |
doc.close() | |
# The below is a crude attempt at a true dark theme without affecting images. | |
# It doesn't work very well, but maybe could with some effort. | |
# There are some solutions to dark-theme for PDFs, | |
# but they tend to invert colors for everything instead of just text. | |
# I've also seen file sizes balloon. | |
# import pymupdf | |
# from pymupdf import Font | |
# from collections import defaultdict | |
# doc = pymupdf.open('path/to/pdf-in.pdf') | |
# background_color = (0/255, 0/255, 0/255) # black | |
# text_color = (255/255, 255/255, 255/255) # white | |
# fonts = defaultdict(lambda: 0) | |
# default_font = Font('helv') | |
# for page in doc: | |
# page.draw_rect(page.rect, color=None, fill=background_color, overlay=False) | |
# spans = [] | |
# for block in page.get_text("dict")['blocks']: | |
# for line in block.get('lines', []): | |
# for span in line['spans']: | |
# if span.get('color', 0) != 0: | |
# continue | |
# spans.append(span) | |
# page.add_redact_annot(span['bbox']) | |
# page.apply_redactions() | |
# tw = pymupdf.TextWriter(page.rect, color=text_color) | |
# for span in spans: | |
# font = span['font'] | |
# fonts[font] += 1 | |
# tw.append(span["origin"], span["text"], font=default_font, fontsize=span["size"]) | |
# tw.write_text(page) | |
# doc.ez_save('path/to/pdf-out.pdf') | |
# doc.close() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment