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