Created
June 28, 2015 04:43
-
-
Save ubnt-intrepid/93cea45aba8de67fde78 to your computer and use it in GitHub Desktop.
This file contains hidden or 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
#!/usr/bin/env python | |
# -*- coding: utf-8 -*- | |
r'''TeX系コマンドのPythonインタフェース | |
Functions: | |
- make_pdf : TeX文書を PDF に変換 | |
- read_bounding_box : 画像の Bounding Box を取得 | |
Memo: | |
* portability を重視(TeXLiveと標準パッケージのみで出来るだけ対応する) | |
* ディレクトリの監視 | |
* 画像ファイルの自動生成(TikZをPDFに変換するなど) | |
''' | |
import sys, os | |
import re | |
from subprocess import check_output, CalledProcessError | |
def make_pdf(file_path): | |
r'''TeX文書ファイルからPDFを生成する | |
Keyword arguments: | |
file_path -- target file path | |
''' | |
# %! compiler: xxxx <- (u)pLaTeX, pdfLaTeX, xelatex, lualatex を指定 | |
pass | |
def read_bounding_box(file_path, hi_res=False): | |
'''BoundingBoxの値を取得する | |
Keyword arguments: | |
eps_path -- 取得したいファイルのパス | |
hi_res -- HiResBoundingBox から値を取得 (if True, default) | |
BoundingBox から値を取得 (if False) | |
Returns: tuple(lb_x, lb_y, rt_x, rt_y) | |
''' | |
if hi_res: | |
regex = re.compile(r'^\%\%HiResBoundingBox\: ([\d\.]+) ([\d\.]+) ([\d\.]+) ([\d\.]+)$') | |
else: | |
regex = re.compile(r'^\%\%BoundingBox\: (\d+) (\d+) (\d+) (\d+)$') | |
def bbox(m): | |
return tuple(float(g) for g in m.groups()) | |
ext = os.path.splitext(file_path)[-1][1:].lower() | |
if ext == 'eps': | |
# ファイルから直接読み込む | |
with open(file_path, 'r') as f: | |
for line in f: | |
m = regex.match(line) | |
if m: | |
return bbox(m) | |
return None | |
elif ext in ('jpg', 'png', 'pdf'): | |
# extractbb を介して読み込む | |
try: | |
stdout = check_output(["extractbb", "-O", file_path], universal_newlines=True) | |
for line in stdout.split('\n'): | |
m = regex.match(line) | |
if m: | |
return bbox(m) | |
return None | |
except CalledProcessError as e: | |
return None | |
else: | |
return None | |
if __name__ == '__main__': | |
print(read_bounding_box(sys.argv[1])) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment