Skip to content

Instantly share code, notes, and snippets.

@zhaofeng-shu33
Last active September 11, 2020 06:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zhaofeng-shu33/d1d7ac9a32afa735653086d00d9fddd0 to your computer and use it in GitHub Desktop.
Save zhaofeng-shu33/d1d7ac9a32afa735653086d00d9fddd0 to your computer and use it in GitHub Desktop.
import time
import subprocess
from subprocess import PIPE, STDOUT
import sys
from PIL import Image
resolution = 144
pdf_file_name = sys.argv[1]
r = subprocess.run(['gs', '-q', '-dBATCH', '-dNOPAUSE', '-sDEVICE=bbox', pdf_file_name], stdout=PIPE, stderr=STDOUT)
# grab the coordinate value
r_t = r.stdout.decode('utf-8')
val_str = r_t[r_t.find('HiResBoundingBox:'):].rstrip()
Ls = val_str.split(' ')
left, lower, right, upper = float(Ls[1]), float(Ls[2]), float(Ls[3]), float(Ls[4])
# output the png
png_file_name = pdf_file_name.replace('pdf', 'png')
r = subprocess.run(['gs', '-q', '-dBATCH', '-dNOPAUSE', '-sDEVICE=pngalpha', '-r' + str(resolution), '-sOutputFile=' + png_file_name, pdf_file_name])
# read the image from disk
ratio = resolution / 72
im = Image.open(png_file_name)
height = im.size[1]
left *= ratio
upper_new = height - lower * 2
right *= ratio
lower_new = height - upper * 2
im_new = im.crop((left, lower_new, right, upper_new))
im_new.save(png_file_name)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment