From anonymous, 9 Months ago, written in Python.
Embed
  1. import tempfile
  2. import pathlib
  3. import subprocess
  4. import datetime
  5.  
  6. import requests
  7. import pylatex
  8.  
  9.  
  10. def get_comic():
  11.     print("Downloading metadata...")
  12.     r = requests.get("https://xkcd.com/info.0.json")
  13.     r.raise_for_status()
  14.     data = r.json()
  15.  
  16.     print("Downloading comic...")
  17.     r = requests.get(data['img'])
  18.     r.raise_for_status()
  19.  
  20.     return r.content, data
  21.  
  22.  
  23. def write_pdf(title, alt, num, date, tmpdir, imgfile):
  24.     print("Writing PDF...")
  25.  
  26.     geometry_options = {
  27.         "head": "40pt",
  28.         "margin": "0.5in",
  29.         "bottom": "0.6in",
  30.         "includeheadfoot": True
  31.     }
  32.  
  33.     doc = pylatex.Document(default_filepath=str(tmpdir / 'xkcd'),
  34.                            geometry_options=geometry_options)
  35.  
  36.     for pkg in ['cmbright', 'caption']:
  37.         doc.packages.append(pylatex.Package(pkg))
  38.  
  39.     doc.preamble.append(pylatex.Command('captionsetup', 'labelformat=empty'))
  40.     doc.preamble.append(pylatex.Command('title', title))
  41.     doc.preamble.append(pylatex.Command('author', f"https://xkcd.com/{num}/"))
  42.     doc.preamble.append(pylatex.Command('date', date.strftime('%Y-%m-%d')))
  43.     doc.append(pylatex.NoEscape(r'\maketitle'))
  44.  
  45.     doc.append(pylatex.Command('thispagestyle', 'empty'))
  46.     with doc.create(pylatex.Figure(position='h!')) as img:
  47.         img.add_image(str(imgfile))
  48.         img.add_caption(alt)
  49.  
  50.     doc.generate_pdf()
  51.  
  52.  
  53. def print_pdf(filename):
  54.     print("Printing PDF...")
  55.     subprocess.run(['lpr', '-P', 'HSR_HP_Color_LaserJet_M651', str(filename)])
  56.  
  57.  
  58. def main():
  59.     img, data = get_comic()
  60.     with tempfile.TemporaryDirectory() as tmpdir:
  61.         tmpdir = pathlib.Path(tmpdir)
  62.         imgfile = tmpdir / 'xkcd.png'
  63.         imgfile.write_bytes(img)
  64.  
  65.         date = datetime.date(year=int(data['year']),
  66.                              month=int(data['month']),
  67.                              day=int(data['day']))
  68.  
  69.         write_pdf(title=data['title'], alt=data['alt'], num=data['num'],
  70.                   date=date, tmpdir=tmpdir, imgfile=imgfile)
  71.  
  72.         print_pdf(tmpdir / 'xkcd.pdf')
  73.  
  74.  
  75. if __name__ == '__main__':
  76.     main()
  77.