-
Notifications
You must be signed in to change notification settings - Fork 1
/
latex-trim
executable file
·75 lines (62 loc) · 2.3 KB
/
latex-trim
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Small script to get the trim parameters for Latex
# Usage:
# latex-trim [filename]
#
# Needs imagemagick for pdf inputs
# License WTFPL
import sys
import io
import subprocess
import numpy as np
import matplotlib as mpl
import matplotlib.pyplot as plt
import matplotlib.widgets as widgets
import matplotlib.patches as patches
from PIL import Image
mpl.rcParams['toolbar'] = 'None'
filename = sys.argv[1]
def pixel2cm(px):
return px * 2.54 / dpi
def onselect(eclick, erelease):
rightPx = min(max(eclick.xdata, erelease.xdata), width)
leftPx = max(min(eclick.xdata, erelease.xdata), 0)
topPx = max(min(eclick.ydata, erelease.ydata), 0)
bottomPx = min(max(eclick.ydata, erelease.ydata), height)
print("trim={{{:.2f}cm {:.2f}cm {:.2f}cm {:.2f}cm}}, clip, ".format(pixel2cm(leftPx),
pixel2cm(height-bottomPx),
pixel2cm(width - rightPx),
pixel2cm(topPx)))
plt.close()
# If pdf file, converting it with imagemagick to png
if filename.endswith(".pdf"):
cmd = ["convert", filename, "png:-"]
fconvert = subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = fconvert.communicate()
assert fconvert.returncode == 0, stderr
inputImage = io.BytesIO(stdout)
else:
inputImage = filename
im = Image.open(inputImage).convert('RGB')
arr = np.asarray(im)
width, height = im.size
if 'dpi' in im.info:
dpi = im.info['dpi'][0]
else:
# dpi not stored in image, revert to latex default: 72
dpi = 72
fig, ax = plt.subplots()
plt_image = plt.imshow(arr)
border = (width+height)*0.05
ax.set_xlim(-border, width + border)
ax.set_ylim(height + border, -border)
rect = patches.Rectangle((0, 0), width, height, linewidth=1, edgecolor='black', facecolor='none', alpha=0.2)
ax.add_patch(rect)
rs = widgets.RectangleSelector(ax,
onselect,
drawtype='box',
rectprops = dict(facecolor='red', edgecolor = 'black', alpha=0.5, linestyle='dashed', fill=True))
fig.canvas.set_window_title('latex-trim')
plt.tight_layout()
plt.show()