1 # -*- coding: utf-8 -*-
4 # This file is part of LyX, the document processor.
5 # Licence details can be found in the file COPYING.
7 # \author Angus Leeming
10 # Full author contact details are available in file CREDITS
13 # This script converts an XFIG image to something that pdflatex can process
14 # into high quality PDF.
17 # python fig2pdftex.py ${base}.fig ${base}.pdft
18 # This command generates
19 # ${base}.pdf the converted pdf file
20 # ${base}.pdft a tex file that can be included in your latex document
21 # using '\input{${base}.pdft}'
24 # Do not use this command as
25 # python fig2pdftex.py file.fig file.pdf
26 # the real pdf file will be overwritten by a tex file named file.pdf.
29 from __future__ import print_function
35 run a command, quit if fails
37 if os.system(cmd) != 0:
38 print("Command '%s' fails." % cmd)
42 # We expect two args, the names of the input and output files.
43 if len(sys.argv) != 3:
46 input, output = sys.argv[1:]
48 # Fail silently if the file doesn't exist
49 if not os.path.isfile(input):
52 # Strip the extension from ${output}
53 outbase = os.path.splitext(output)[0]
55 # Ascertain whether fig2dev is "modern enough".
56 # If it is, then the help info will mention "pdftex_t" as one of the
58 fout = os.popen('fig2dev -h')
59 help_msg = fout.read()
63 if 'pdftex_t' in help_msg:
64 # Modern versions of xfig can output the image without "special" text as
65 # a PDF file ${base}.pdf and place the text in a LaTeX file
66 # ${base}.pdftex_t for typesetting by pdflatex itself.
67 runCommand('fig2dev -Lpdftex -p1 %s %s.pdf' % (input, outbase))
68 runCommand('fig2dev -Lpdftex_t -p%s %s %s' % (outbase, input, output))
70 # Older versions of xfig cannot do this, so we emulate the behaviour using
71 # pstex and pstex_t output.
72 runCommand('fig2dev -Lpstex %s %s.pstex' % (input, outbase))
73 runCommand('fig2dev -Lpstex_t -p %s %s %s' % (outbase, input, output))
75 # manipulates the Bounding Box info to enable gs to produce
76 # the appropriate PDF file from an EPS one.
77 # The generated PostScript commands are extracted from epstopdf, distributed
79 epsfile = outbase + '.pstex'
81 boundingboxline = re.compile(b'%%BoundingBox:\s+(\d*)\s+(\d*)\s+(\d*)\s+(\d*)')
82 for line in open(epsfile, 'rb'):
83 if line[:13] == b'%%BoundingBox':
84 (llx, lly, urx, ury) = list(map(int, boundingboxline.search(line).groups()))
89 tmp.write(b'''%%%%BoundingBox: 0 0 %d %d
90 << /PageSize [%d %d] >> setpagedevice
92 ''' % (width, height, width, height, xoffset, yoffset))
96 # direct move(rename) may fail under windows
98 os.rename(epsfile + '.??', epsfile)
100 # Convert the ${pstex} EPS file (free of "special" text) to PDF format
102 runCommand('gs -q -dNOPAUSE -dBATCH -dSAFER -sDEVICE=pdfwrite -sOutputFile=%s.pdf %s.pstex'\
103 % (outbase, outbase))