Micah Jamison's Dev Blog.
# Automatically change a background in ubuntu with pages from a pdf
I have a big library of comic books and no time to read them. I like the artwork though and it's a shame to never even passivly see them. My solution: automatically swap out my desktop background in ubuntu with pages from a random pdf.
The script:
```python
import glob
import random
import subprocess
from PIL import Image
import pypdfium2 as pdfium
def get_random_pil(num):
pdf_path = random.choice(glob.glob("/home/micah/data/books/adv*.pdf"))
pdf = pdfium.PdfDocument(pdf_path)
n_pages = len(pdf) # get the number of pages in the document
# get a random start page, but back far enough to get the number of pages
# needed in a row
r_page = random.randint(1, n_pages-(num+1))
for page in range(r_page, r_page + num):
page = pdf.get_page(page)
bitmap = page.render(
scale=4, # 72dpi resolution
rotation=0, # no additional rotation
)
yield bitmap.to_pil()
def combine_images(*args):
"""Combines images side by side and saves the result.
Args:
*images: PIL images
output_path: Path to save the combined image.
"""
combined_width = 0
combined_height = 0
for img in args[:-1]:
combined_width += img.size[0]
combined_height = max(combined_height, img.size[1])
combined_image = Image.new('RGB', (combined_width, combined_height))
cur_x = 0
for img in args[:-1]:
# Paste the two images side by side
combined_image.paste(img, (cur_x, 0))
cur_x += img.size[0]
combined_image.save(args[-1])
combine_images(*get_random_pil(3), "/home/micah/wallpaper.jpg")
command = f"gsettings set org.gnome.desktop.background picture-uri-dark 'file:///home/micah/wallpaper.jpg'"
subprocess.run(command, shell=True)
```
Next I updated my user's crontab to run it on an interval.
```
$ crontab -e
# using a pyenv virtual env
@hourly /home/micah/.pyenv/versions/3.13.2/envs/media_organize/bin/python /home/micah/projects/media_organize/random_wallpaper.py
```
@blog