Debian Codegraph @

texk/texlive/linked_scripts/epstopdf/epstopdf.pl

raw
1 #!/usr/bin/env perl
2 use warnings;
3 # $Id: epstopdf.pl 71777 2024-07-11 21:24:57Z karl $
4 # (Copyright lines below.)
5 #
6 # Redistribution and use in source and binary forms, with or without
7 # modification, are permitted provided that the following conditions are met:
8 #
9 # 1. Redistributions of source code must retain the above copyright
10 # notice, this list of conditions and the following disclaimer.
11 # 2. Redistributions in binary form must reproduce the above copyright
12 # notice, this list of conditions and the following disclaimer in the
13 # documentation and/or other materials provided with the distribution.
14 # 3. The name of the author may not be used to endorse or promote
15 # products derived from this software without specific prior written
16 # permission.
17 #
18 # THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
19 # IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
20 # WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
21 # DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT,
22 # INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
23 # (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
24 # SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
25 # HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
26 # STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
27 # ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
28 # POSSIBILITY OF SUCH DAMAGE.
29 # ----------------------------------------------------------------
30 # This is a script to transform an EPS file to PDF. Theoretically, any
31 # Level 2 PS interpreter should work, although in practice using
32 # Ghostscript is near-universal. Many more details below.
33 #
34 # One thing not supported is the case of
35 # "%%BoundingBox: (atend)" when input is not seekable (e.g., from a pipe),
36 #
37 # emacs-page
38 #
39 my $ver = "2.36";
40 # 2024/07/11 2.36 (Karl Berry)
41 # * regexp syntax for OS/2 test, found by John Collins.
42 # 2024/06/21 2.35 (Karl Berry)
43 # * path_sep for OS/2 is also ";".
44 # 2024/04/29 2.34 (Karl Berry)
45 # * if --debug is first argument, give more output.
46 # * do not check for kpsewhich in PATH unless restricted.
47 # * minor wording and doc changes.
48 # 2024/04/14 (John Collins)
49 # * use warnings.
50 # * Msys PATH separator is :.
51 # * Do immediate decomposition of path to array on startup, and use array
52 # instead of separate uses of split.
53 # * On Windows, Msys and Cygwin, normalize directory separator to /.
54 # * Detect invocation via Windows TL (and epstopdf.exe wrapper script) by
55 # presence of TL's private gs in PATH: a directory ending in /tlgs/bin.
56 # In this case, change behavior under Cygwin to be like that of Windows
57 # instead of Unix.
58 # * On Cygwin and Msys, put temporary file in current directory instead of
59 # default, which is normally /tmp. That's so that the pathname to the
60 # temporary file remains valid no matter which kind of gs it's passed to:
61 # native Windows, Msys or Cygwin.
62 # * Prettyprint PATH, one directory per line, in error about program
63 # not in PATH.
64 # Original report from Pablo Gonzalez L,
65 # https://tug.org/pipermail/tex-k/2024-April/004036.html
66 # 2023/09/15 2.33 (Karl Berry)
67 # * Cygwin PATH separator is :. Report from Alois Steindl,
68 # https://tug.org/pipermail/tex-live/2023-September/049474.html
69 # 2023/07/08 2.32 (Karl Berry)
70 # * check that kpsewhich and gs are in PATH.
71 # * correct TL path for kpsewhich to bin/windows.
72 # 2023/03/06 v2.31 (Karl Berry)
73 # * disallow --nosafer in restricted mode.
74 # * disallow output to pipes in restricted mode.
75 # Report from nikolay.ermishkin to tlsecurity.
76 # 2022/09/05 v2.30 (Siep Kroonenberg)
77 # * still use gswin32c if gswin64c.exe not on PATH.
78 # 2022/08/29 v2.29 (Karl Berry)
79 # * use gswin64c.exe on 64-bit Windows.
80 # 2018/09/17 v2.28 (Karl Berry)
81 # * -dCompatibilityLevel=1.5 by default, since gs9.25 switched to 1.7.
82 # 2017/09/14 v2.27 (Karl Berry)
83 # * extract value from --gsopt with $3 not $2 (extra regexp group
84 # added previously), and check it with ^(...)$ so anchors apply to all.
85 # (report to Karl from Yannick Berker, 7 Sep 2017 14:07:09.)
86 # 2017/01/07 v2.26 (Norbert Preining, Karl Berry)
87 # * allow cmdline of infile outfile.pdf.
88 # * explicitly allow -o as abbreviation for --outfile,
89 # to guard against future --options. (Also --output.)
90 # 2016/06/30 v2.25 (Norbert Preining, Karl Berry)
91 # * don't set (default) device until after restricted check.
92 # * a few more debugging lines.
93 # 2016/05/29 v2.24 (Karl Berry)
94 # * new option --gray; patch from William Bader,
95 # tex-k mail 9 Feb 2016 19:37:08.
96 # * disallow --device completely in restricted mode,
97 # to avoid maintenance of device list.
98 # tex-live mail 10 Feb 2016 10:36:26.
99 # 2015/01/22 v2.23 (Karl Berry)
100 # * use # instead of = to placate msys; report from KUROKI Yusuke,
101 # tex-k mail 20 Jan 2015 12:40:16.
102 # 2014/06/18 v2.22 (Karl Berry)
103 # * escape % in $outputfilename; report from William Fischer,
104 # tex-k mail 16 Jun 2014 18:45:12.
105 # 2014/01/17 v2.21 (Karl Berry)
106 # * tweaks to help message, per reports from Knuth.
107 # 2013/09/28 v2.20 (Heiko Oberdiek, and (a little) Karl Berry)
108 # * New command line argument --(no)safer which allows setting
109 # -dNOSAFER instead of -dSAFER (only for non-restricted).
110 # * New command line argument --pdfsettings for
111 # Ghostscript's -dPDFSETTINGS.
112 # * New command line argument --(no)quiet.
113 # * New command line argument --device for specifying a differnt
114 # Ghostscript device (limited set of devices for restricted mode).
115 # * New command line arguments --gsopts and --gsopt for adding
116 # Ghostscript options.
117 # * Full support of ghostscript's option -r, DPIxDPI added.
118 # * Support for DOS EPS binary files (TN 5002) added.
119 # * Removes PJL commands at start of file.
120 # 2013/05/12 v2.19 (Karl Berry)
121 # * explain option naming conventions (= defaults for Getopt::Long).
122 # 2012/05/22 v2.18 (Karl Berry)
123 # * use /usr/bin/env, since Ruby has apparently required #! for years,
124 # and we rely on it for our other scripts, so why not.
125 # (tex-k mail from Jean Krohn, 2 Aug 2010 15:57:54,
126 # per http://osdir.com/ml/lang.ruby.general/2002-06/msg01388.html
127 # and ruby-bugs:PR#315).
128 # 2012/05/12 v2.17 (Karl Berry)
129 # * uselessly placate -w. Debian bug 672281.
130 # 2010/05/09 v2.16 (Karl Berry)
131 # * make --nogs dump edited PostScript to stdout by default
132 # (report from Reinhard Kotucha).
133 # 2010/03/19 v2.15 (Karl Berry)
134 # * let --outfile override --filter again.
135 # * recognize MSWin64 as well as MSWin32, just in case.
136 # 2010/03/08 v2.14 (Manuel P\'egouri\'e-Gonnard)
137 # * In restricted mode, forbid --gscmd (all platforms) and call GS with full
138 # path relative to self location (Windows).
139 # 2010/02/26 v2.13 (Karl Berry)
140 # * New release.
141 # 2010/02/23 (Manuel P\'egouri\'e-Gonnard)
142 # * Use kpsewhich for filename validation in restricted mode, both input and
143 # output. Requires kpathsea 5.1.0 (TL2010), rejects the name with earlier
144 # versions of kpsewhich.
145 # * Call external programs with full path on win32 in order to avoid obvious
146 # attacks with rogue versions of these programs in the current directory.
147 # 2009/11/27 v2.12 (Karl Berry)
148 # * Make --filter work again
149 # 2009/11/25 (Manuel P\'egouri\'e-Gonnard)
150 # * Better extension detection, suggested by A. Cherepanov.
151 # 2009/10/18 (Manuel P\'egouri\'e-Gonnard)
152 # * Better argument validation (Alexander Cherepanov).
153 # * Use list form of pipe open() (resp. system()) to prevent injection.
154 # Since Perl's fork() emulation doesn't work on Windows with Perl 5.8.8 from
155 # TeX Live 2009, use a temporary file instead of a pipe on Windows.
156 # 2009/10/14 (Manuel P\'egouri\'e-Gonnard)
157 # * Added restricted mode.
158 # 2009/09/27 v2.11 (Karl Berry)
159 # * Fixed two bugs in the (atend) handling code (Martin von Gagern)
160 # * Improved handling of CR line ending (Martin von Gagern)
161 # * More error checking
162 # * --version option
163 # * Create source repository in TeX Live
164 # 2009/07/17 v2.9.11gw
165 # * Added -dSAFER to default gs options
166 # TL2009 wants to use a restricted variant of -shell-escape,
167 # allowing epstopdf to run. However without -dSAFER Ghostscript
168 # allows writing to files (other than given in -sOutputFile)
169 # and running commands (through Ghostscript pipe's language feature).
170 # 2009/05/09 v2.9.10gw
171 # * Changed cygwin name for ghostscript to gs
172 # 2008/08/26 v2.9.9gw
173 # * Switch to embed fonts (default=yes) (J.P. Chretien)
174 # * turned no AutoRotatePages into an option (D. Kreil) (default = None)
175 # * Added resolution switch (D. Kreil)
176 # * Added BSD-style license
177 # 2007/07/18 v2.9.8gw
178 # 2007/05/18 v.2.9.7gw (Gerben Wierda)
179 # * Merged both supplied 2.9.6 versions
180 # 2007/05/15 v2.9.6tp (Theo Papadopoulo)
181 # * Simplified the (atend) support
182 # 2007/01/24 v2.9.6sw (Staszek Wawrykiewicz)
183 # * patched to work also on Windows
184 # 2005/10/06 v2.9.5gw (Gerben Wierda)
185 # * Fixed a horrendous bug in the (atend) handling code
186 # 2005/10/06 v2.9.4gw (Gerben Wierda)
187 # * This has become the official version for now
188 # 2005/10/01 v2.9.3draft (Gerben Wierda)
189 # * Quote OutFilename
190 # 2005/09/29 v2.9.2draft (Gerben Wierda)
191 # * Quote OutFilename
192 # 2004/03/17 v2.9.1draft (Gerben Wierda)
193 # * No autorotate page
194 # 2003/04/22 v2.9draft (Gerben Wierda)
195 # * Fixed bug where with cr-eol files everything up to the first %!
196 # * in the first 2048 bytes was gobbled (double ugh!)
197 # 2002/02/21 v2.8draft (Gerben Wierda)
198 # * Fixed bug where last line of buffer was not copied out (ugh!)
199 # 2002/02/18 v2.8draft (Gerben Wierda)
200 # * Handle different eol styles transparantly
201 # * Applied fix from Peder Axensten for Freehand bug
202 # 2001/03/05 v2.7 (Heiko Oberdiek)
203 # * Newline before grestore for the case that there is no
204 # whitespace at the end of the eps file.
205 # 2000/11/05 v2.6 (Heiko Oberdiek)
206 # * %%HiresBoundingBox corrected to %%HiResBoundingBox
207 # 1999/05/06 v2.5 (Heiko Oberdiek)
208 # * New options: --hires, --exact, --filter, --help.
209 # * Many cosmetics: title, usage, ...
210 # * New code for debug, warning, error
211 # * Detecting of cygwin perl
212 # * Scanning for %%{Hires,Exact,}BoundingBox.
213 # * Scanning only the header in order not to get a wrong
214 # BoundingBox of an included file.
215 # * (atend) supported.
216 # * uses strict; (earlier error detecting).
217 # * changed first comment from '%!PS' to '%!';
218 # * corrected (atend) pattern: '\s*\(atend\)'
219 # * using of $bbxpat in all BoundingBox cases,
220 # correct the first white space to '...Box:\s*$bb...'
221 # * corrected first line (one line instead of two before 'if 0;';
222 #
223 # Thomas Esser, Sept. 1998: change initial lines to find
224 # perl along $PATH rather than guessing a fixed location. The above
225 # construction should work with most shells.
226 #
227 # Originally by Sebastian Rahtz, for Elsevier Science
228 # with extra tricks from Hans Hagen's texutil and many more.
229
230 ### emacs-page
231 ### program identification
232 my $program = "epstopdf";
233 my $ident = '($Id: epstopdf.pl 71777 2024-07-11 21:24:57Z karl $)' . " $ver";
234 my $copyright = <<END_COPYRIGHT ;
235 Copyright 2009-2024 Karl Berry et al.
236 Copyright 2002-2009 Gerben Wierda et al.
237 Copyright 1998-2001 Sebastian Rahtz et al.
238 License RBSD: Revised BSD <http://www.xfree86.org/3.3.6/COPYRIGHT2.html#5>
239 This is free software: you are free to change and redistribute it.
240 There is NO WARRANTY, to the extent permitted by law.
241 END_COPYRIGHT
242 my $title = "$program $ident\n";
243
244 ### message functions.
245 sub debug { print STDERR "* @_\n" if $::opt_debug; }
246 sub warning { print STDERR "==> Warning: @_\n"; }
247 sub error { die "$title!!! Error: @_\n"; }
248 sub errorUsage { die "$program: Error: @_ (try --help for more information)\n"; }
249 sub warnerr { $restricted ? error(@_) : warning(@_); }
250
251 # Check specially for --debug or -d (exactly) as first argument, so we can
252 # generate debugging output during initialization.
253 $::opt_debug = 1 if @ARGV && ($ARGV[0] eq "--debug" || $ARGV[0] eq "-d");
254
255 # Different Windows cases.
256 my $on_cygwin = ($^O eq 'cygwin');
257 my $on_msys = ($^O eq 'msys');
258 my $on_windows = ($^O =~ /^MSWin/) || $on_msys;
259 my $on_windows_or_cygwin = $on_windows || $on_cygwin;
260 debug "on_windows=$on_windows, on_windows_or_cygwin=$on_windows_or_cygwin";
261 debug " on_cygwin=$on_cygwin, on_msys=$on_msys";
262
263 # Split PATH and use / as directory separator.
264 #
265 my $path_sep = ($^O =~ /^(OS2|MSWin)/i) ? ';' : ':'; # not msys
266 my @pdirs = split($path_sep, $ENV{"PATH"});
267 # Normalize directory separators to /. Always valid on Windows.
268 if ($on_windows_or_cygwin) {
269 foreach (@pdirs) { s !\\!/!g; }
270 }
271 debug "Normalized PATH to: @pdirs";
272
273 # Default values for commands.
274 # Ghostscript, which is always needed.
275 my $GS = 'gs';
276 # Kpsewhich, only used in restricted mode.
277 my $kpsewhich = 'kpsewhich';
278
279 # Determine if we were invoked from a standard Windows TL installation via the
280 # wrapper script epstopdf.exe:
281 my $TL_Windows_bin = undef;
282 my $TL_tlgs = undef;
283 if ($on_windows_or_cygwin) {
284 debug "Looking for symptoms of Windows TL gs and wrapper .exe:";
285 for (@pdirs) {
286 if (m!^(.+)/tlpkg/tlgs/bin$!) {
287 debug "Found Windows tlgs item '$_' in PATH";
288 # We were probably invoked via runscript by .exe file in native TL
289 # Windows, since then a tlgs/bin item is inserted in PATH,
290 # so that Windows TL's private installation of gs, with its executables
291 # gswin64c.exe and/or gswin32c.exe gets used.
292 # Anything else giving the same symptom is surely a deliberate
293 # configuration to imitate that the TL Windows behavior.
294 my $TL_root = $1;
295 $TL_tlgs = $_;
296 $TL_Windows_bin = "$TL_root/bin/windows";
297 last;
298 }
299 }
300 if ($TL_tlgs) {
301 # Confirm by existence of expected directories and files.
302 # If those do not exist, we don't have a standard native
303 # Windows TL installation.
304 if (-x "$TL_Windows_bin/kpsewhich.exe"
305 && (-x "$TL_tlgs/gswin64c.exe" || -x "$TL_tlgs/gswin32c.exe")
306 ) {
307 # The needed files exist.
308 # The runscript wrapper ensures that the tlgs and the binary directory
309 # of its own installation are in PATH ahead of any directories that
310 # may contain other versions.
311 }
312 else {
313 warning(<<END_STRANGE_WINDOWS);
314 It seems epstopdf has been called from native TeX Live Windows,
315 with these Windows bin and tlgs dirs:
316 $TL_Windows_bin
317 $TL_tlgs
318 But the needed files don't exist, namely kpsewhich and gswin64c or gswin32c
319 So we don't have a correct standard TeX Live Windows installation.
320 Unsetting the Windows bin and tlgs directories and hoping for the best.
321 END_STRANGE_WINDOWS
322 $TL_Windows_bin = undef;
323 $TL_tlgs = undef;
324 }
325 } else {
326 debug "No tlpkg/tlgs/bin item found in PATH: @pdirs";
327 } # not TL_tlgs
328 } # on_windows_or_cygwin
329
330 if ($on_windows || defined $TL_tlgs) {
331 $GS = "gswin32c";
332 if ($ENV{"PROCESSOR_ARCHITECTURE"} eq "AMD64"
333 || $ENV{"PROCESSOR_ARCHITEW6432"} eq "AMD64") {
334 # prefer gswin64c.exe if on search path.
335 foreach my $d (@pdirs) {
336 $d = substr ($d, 1, -1) if (substr ($d,1,1) eq '"');
337 if (-f $d . "/gswin64c.exe") {
338 $GS = "gswin64c";
339 last;
340 }
341 }
342 }
343 debug "on_windows and have tlgs, GS set to: $GS";
344 }
345
346
347 ### restricted mode, implicit if called as repstopdf.
348 $restricted = 0;
349 $restricted = 1 if $0 =~ /repstopdf/;
350
351 ### default values
352 my $default_device = 'pdfwrite';
353
354 ### options
355 $::opt_autorotate = "None";
356 $::opt_compress = 1;
357 $::opt_debug = 0;
358 $::opt_device = "";
359 $::opt_embed = 1;
360 $::opt_exact = 0;
361 $::opt_filter = 0;
362 $::opt_gray = 0;
363 $::opt_gs = 1;
364 $::opt_gscmd = "";
365 @::opt_gsopt = ();
366 $::opt_help = 0;
367 $::opt_hires = 0;
368 $::opt_outfile = "";
369 $::opt_pdfsettings = "";
370 $::opt_res = '';
371 $::opt_restricted = 0;
372 $::opt_safer = 1;
373 $::opt_quiet = 1;
374 $::opt_version = 0;
375
376 sub gsopts { push (@::opt_gsopt, split (' ', $_[1])); }
377
378 # known-safe Ghostscript options and values.
379 my %optcheck = qw<
380 AlignToPixels 0|1
381 AntiAliasColorImages true|false
382 AntiAliasGrayImages true|false
383 AntiAliasMonoImages true|false
384 ASCII85EncodePages true|false
385 AutoFilterColorImages true|false
386 AutoFilterGrayImages true|false
387 AutoPositionEPSFiles true|false
388 AutoRotatePages /(None|All|PageByPage)
389 BATCH true
390 Binding /(Left|Right)
391 CannotEmbedFontPolicy /(OK|Warning|Error)
392 ColorConversionStrategy /(LeaveColorUnchanged|UseDeviceIndependentColor|UseDeviceIndependendColorForImages|sRGB|CMYK)
393 ColorImageDepth -1|1|2|4|8
394 ColorImageDownsampleThreshold 10(.0*)?|\d(.\d*)|\.\d+
395 ColorImageDownsampleType /(Average|Bicubic|Subsample|None)
396 ColorImageFilter /(DCTEncode|FlateEncode|JPXEncode)
397 ColorImageResolution \d+
398 COLORSCREEN true|0|false
399 CompatibilityLevel 1\.[0-7]
400 CompressFonts true|false
401 CompressPages true|false
402 ConvertCMYKImagesToRGB true|false
403 ConvertImagesToIndexed true|false
404 DefaultRenderingIntent /(Default|Perceptual|Saturation|AbsoluteColorimetric|RelativeColorimetric)
405 DetectBlends true|false
406 DetectDuplicateImages true|false
407 DITHERPPI \d+
408 DOINTERPOLATE true
409 DoThumbnails true|false
410 DownsampleColorImages true|false
411 DownsampleGrayImages true|false
412 DownsampleMonoImages true|false
413 EmbedAllFonts true|false
414 EmitDSCWarnings true|false
415 EncodeColorImages true|false
416 EncodeGrayImages true|false
417 EncodeMonoImages true|false
418 EndPage -?\d+
419 FIXEDRESOLUTION true
420 GraphicsAlphaBits 1|2|4
421 GrayImageDepth -1|1|2|4|8
422 GrayImageDownsampleThreshold \d+\.?\d*|\.\d+
423 GrayImageDownsampleType /(Average|Bicubic)
424 GrayImageFilter /(DCTEncode|FlateEncode|JPXEncode)
425 GrayImageResolution \d+
426 GridFitTT 0|1|2|3
427 HaveTransparency true|false
428 HaveTrueTypes true|false
429 ImageMemory \d+
430 LockDistillerParams true|false
431 LZWEncodePages true|false
432 MaxSubsetPct 100|[1-9][0-9]?
433 MaxClipPathSize \d+
434 MaxInlineImageSize \d+
435 MaxShadingBitmapSize \d+
436 MonoImageDepth -1|1|2|4|8
437 MonoImageDownsampleThreshold \d+\.?\d*|\.\d+
438 MonoImageDownsampleType /(Average|Bicubic|Subsample|None)
439 MonoImageFilter /(CCITTFaxEncode|FlateEncode|RunLengthEncode)
440 MonoImageResolution \d+
441 NOCIE true
442 NODISPLAY true
443 NOEPS true
444 NOINTERPOLATE true
445 NOPSICC true
446 NOSUBSTDEVICECOLORS true|false
447 NOTRANSPARENCY true
448 OPM 0|1
449 Optimize true|false
450 ParseDSCComments true|false
451 ParseDSCCommentsForDocInfo true|false
452 PreserveCopyPage true|false
453 PreserveEPSInfo true|false
454 PreserveHalftoneInfo true|false
455 PreserveOPIComments true|false
456 PreserveOverprintSettings true|false
457 StartPage -?\d+
458 PatternImagemask true|false
459 PDFSETTINGS /(screen|ebook|printer|prepress|default)
460 PDFX true|false
461 PreserveDeviceN true|false
462 PreserveSeparation true|false
463 QUIET true
464 SHORTERRORS true
465 SubsetFonts true|false
466 TextAlphaBits 1|2|4
467 TransferFunctionInfo /(Preserve|Remove|Apply)
468 UCRandBGInfo /(Preserve|Remove)
469 UseCIEColor true|false
470 UseFlateCompression true|false
471 UsePrologue true|false
472 >;
473 # In any case not suitable for restricted:
474 # -dDOPS
475
476 ### usage
477 my @bool = ("false", "true");
478 my $resmsg = $::opt_res ? $::opt_res : "[use gs default]";
479 my $rotmsg = $::opt_autorotate ? $::opt_autorotate : "[use gs default]";
480
481 my $usage = <<"END_OF_USAGE";
482 ${title}Usage: $program [OPTION]... [EPSFILE [PDFFILE.pdf]]
483
484 Convert an EPS file to PDF (or other formats), by default using Ghostscript.
485
486 By default, the output name is the input name with any extension
487 replaced by ".pdf". An output name ending with .pdf can also be given
488 as a second argument on the command line, or the --outfile (-o) option
489 can be used with any name.
490
491 The output is PDF 1.5 by default; use --gsopt=-dCompatibilityLevel=1.7
492 (for example) to change this.
493
494 The resulting output is guaranteed to start at the 0,0 coordinate, and
495 sets a page size exactly corresponding to the BoundingBox. Thus, the
496 result does not need any cropping, and the PDF MediaBox is correct.
497
498 If the bounding box in the input is incorrect, inevitably there will
499 be resulting problems.
500
501 Options:
502 --help display this help and exit
503 --version display version information and exit
504
505 -o, --outfile=FILE write result to FILE (default based on input name)
506 --restricted use restricted mode (default: $bool[$restricted])
507
508 --(no)debug output debugging info (default: $bool[$::opt_debug])
509 --(no)exact scan ExactBoundingBox (default: $bool[$::opt_exact])
510 --(no)filter read standard input (default: $bool[$::opt_filter])
511 --(no)gs run ghostscript (default: $bool[$::opt_gs])
512 --(no)hires scan HiResBoundingBox (default: $bool[$::opt_hires])
513
514 Options for Ghostscript:
515 --gscmd=VAL pipe output to VAL (default: $GS
516 [gs on Unix, gswin64c.exe or gswin32c.exe on Windows])
517 --gsopt=VAL single option for gs (see below)
518 --gsopts=VAL options for gs (see below)
519 --autorotate=VAL set AutoRotatePages (default: $rotmsg)
520 recognized VAL choices: None, All, PageByPage;
521 for EPS files, PageByPage is equivalent to All.
522 --(no)compress use compression (default: $bool[$::opt_compress])
523 --device=DEV use -sDEVICE=DEV (default: $default_device)
524 --(no)embed embed fonts (default: $bool[$::opt_embed])
525 --(no)gray grayscale output (default: $bool[$::opt_gray])
526 --pdfsettings=VAL use -dPDFSETTINGS=/VAL (default is prepress if --embed,
527 else empty); recognized VAL choices:
528 screen, ebook, printer, prepress, default.
529 --(no)quiet use -q (-dQUIET) (default: $bool[$::opt_quiet])
530 --res=DPI|DPIxDPI set image resolution (default: $resmsg)
531 --(no)safer use -d(NO)SAFER (default: $bool[$::opt_safer])
532
533 These examples all equivalently convert test.eps to test.pdf:
534 \$ $program test.eps
535 \$ $program test.eps test.pdf
536 \$ cat test.eps | $program --filter >test.pdf
537 \$ cat test.eps | $program -f -o=test.pdf
538
539 Example for using HiResBoundingBox instead of BoundingBox:
540 \$ $program --hires test.eps
541
542 Example for producing epstopdf's attempt at corrected PostScript:
543 \$ $program --nogs test.ps >testcorr.ps
544
545 In all cases, you can use --debug to see more about what epstopdf
546 is doing. For maximum output, use --debug as the first option.
547
548 More about the options for Ghostscript:
549 Additional options to be used with gs can be specified
550 with either or both of the two cumulative options --gsopts and --gsopt.
551 --gsopts takes a single string of options, which is split at whitespace
552 and each resulting word then added to the gs command line individually.
553 --gsopt adds its argument as a single option to the gs command line.
554 It can be used multiple times to specify options separately,
555 and is necessary if an option or its value contains whitespace.
556 In restricted mode, options are limited to those with names and values
557 known to be safe. Some options taking booleans, integers or fixed
558 names are allowed, those taking general strings are not.
559
560 All options to epstopdf may start with either - or --, and may be
561 unambiguously abbreviated. It is best to use the full option name in
562 scripts to avoid possible collisions with new options in the future.
563
564 When reporting bugs, please include an input file and all command line
565 options so the problem can be reproduced.
566
567 Report bugs to: tex-k\@tug.org
568 epstopdf home page: <https://tug.org/epstopdf/>
569 END_OF_USAGE
570
571 ### process options
572 use Getopt::Long;
573 GetOptions (
574 "autorotate=s", # \ref{val_autorotate}
575 "compress!",
576 "debug!",
577 "device=s",
578 "embed!",
579 "exact!",
580 "gray!",
581 "filter!",
582 "gs!",
583 "gscmd=s", # \ref{val_gscmd}
584 "gsopt=s@", # \ref{val_gsopt}
585 "gsopts=s" => \&gsopts, # \ref{val_gsopts}
586 "help|h",
587 "hires!",
588 "outfile|output|o=s", # \ref{openout_any}
589 "pdfsettings=s",
590 "quiet",
591 "res=s",
592 "restricted",
593 "safer!",
594 "version",
595 ) or die "Try $0 --help for more information\n";
596
597 ### disable --quiet if option --debug is given
598 $::opt_quiet = 0 if $::opt_debug;
599
600 ### restricted option
601 $restricted = 1 if $::opt_restricted;
602
603 ### debug messages
604 debug "Restricted mode activated" if $restricted;
605
606 ### check that PROG is in PATH and executable, abort if not. It'd be
607 # better to actually try running the program, but then we'd have to
608 # either replicate Perl's logic for finding the command interpreter
609 # (trivial on Unix, complicated on Windows), or do a fork/exec and close
610 # the file descriptors ourselves, which seems too painful. Nor do we
611 # want to load/assume File::Which. Instead we'll look along PATH
612 # ourselves, which is good enough in practice for us, since the only
613 # goal here is to give a better error message if the program isn't
614 # available.
615 sub check_prog_exists {
616 my ($prog) = @_;
617 my @w_ext = ("exe", "com", "bat");
618 debug " Checking if $prog is in PATH";
619 # absolute unix
620 if (! $on_windows_or_cygwin && $prog =~ m,^((\.(\.)?)?/),) {
621 return 1 if -x $prog; # absolute or explicitly relative
622 error "Required program $prog not found, given with explicit directory";
623
624 # absolute windows: optional drive letter, then . or .., then \ or /.
625 } elsif ($on_windows_or_cygwin
626 && $prog =~ m,^(([a-zA-Z]:)?(\.(\.)?)?[/\\]),) {
627 return 1 if -x $prog;
628 for my $ext (@w_ext) {
629 return 1 if (-x "$prog.$ext");
630 }
631 error "Required program $prog not found, given explicit Windows directory";
632 }
633
634 # not absolute, check path
635 for my $dir (@pdirs) {
636 $dir = "." if $dir eq ""; # empty path element
637 debug " Checking dir $dir";
638 if (-x "$dir/$prog") {
639 return 1;
640 } elsif ($on_windows_or_cygwin) {
641 for my $ext (@w_ext) {
642 return 1 if (-x "$dir/$prog.$ext");
643 }
644 }
645 }
646
647 # if made it through the whole loop, not found, so quit.
648 my @path_pretty = ();
649 for (@pdirs) { push @path_pretty, " '$_'\n"; }
650 error "Required program $prog not found in PATH, which contains:\n",
651 @path_pretty;
652 }
653 check_prog_exists ($kpsewhich) if $restricted; # only needed if restricted
654
655 ### check if a name is "safe" according to kpse's open(in|out)_any
656 # return true if name is ok, false if not.
657 sub safe_name {
658 my ($mode, $name) = @_;
659 my $option = "";
660 $option = '-safe-in-name' if $mode eq 'in';
661 $option = '-safe-out-name' if $mode eq 'out';
662 error "Unknown check mode in safe_name(): $mode" unless $option;
663 my @args = ($kpsewhich, '-progname', 'repstopdf', $option, $name);
664 debug "Checking safe_name with: @args";
665 my $bad = system { $args[0] } @args;
666 return ! $bad;
667 }
668
669 ### help, version options.
670 if ($::opt_help) {
671 print $usage;
672 exit 0;
673 }
674
675 if ($::opt_version) {
676 print $title;
677 print $copyright;
678 exit 0;
679 }
680
681 ### get input filename (\ref{openin_any} for validation)
682 my $InputFilename = "";
683 if ($::opt_filter) {
684 @ARGV == 0 or
685 errorUsage "Input file cannot be used with filter option";
686 debug "Filtering: will read standard input";
687 } else {
688 # not filtering.
689 @ARGV > 0 or errorUsage "Input filename missing";
690 # allow infile outfile.pdf.
691 if (@ARGV == 2) {
692 if ($::opt_outfile) {
693 errorUsage ("Multiple output specifications: second arg=$ARGV[1],"
694 . " --outfile=$::opt_outfile");
695 }
696 if ($ARGV[1] !~ m/\.pdf$/i) {
697 errorUsage "Output file argument requires .pdf extension: $ARGV[1]";
698 }
699 # seems we can use it.
700 $::opt_outfile = $ARGV[1];
701 debug "Output filename from argv:", $::opt_outfile;
702 }
703 @ARGV > 2 and errorUsage "Too many arguments: @ARGV";
704
705 $InputFilename = $ARGV[0];
706 debug "Input filename:", $InputFilename;
707 }
708
709 ### emacs-page
710 ### building the gs invocation.
711
712 ### option gscmd
713 if ($::opt_gscmd) {
714 if ($restricted) { # \label{val_gscmd}
715 error "Option forbidden in restricted mode: --gscmd";
716 } else {
717 debug "Switching from $GS to $::opt_gscmd";
718 $GS = $::opt_gscmd;
719 }
720 }
721 debug "GS command: $GS";
722 check_prog_exists ($GS);
723
724 ### option (no)safer
725 my $gs_opt_safer = "-dSAFER";
726 if (! $::opt_safer) {
727 if ($restricted) {
728 error "Option forbidden in restricted mode: --nosafer";
729 } else {
730 debug "Switching from $gs_opt_safer to -dNOSAFER";
731 $gs_opt_safer = "--nosafer";
732 }
733 }
734
735 ### start building GS command line for the pipe
736 my @GS = ($GS);
737 push @GS, '-q' if $::opt_quiet;
738 push @GS, $gs_opt_safer;
739 push @GS, '-dNOPAUSE';
740 push @GS, '-dBATCH';
741 push @GS, '-dCompatibilityLevel=1.5';
742
743 ### option device
744 if ($::opt_device) {
745 if ($restricted) {
746 error "Option forbidden in restricted mode: --device";
747 } else {
748 debug "Switching from $default_device to $::opt_device";
749 }
750 } else {
751 $::opt_device = $default_device;
752 }
753
754 push @GS, "-sDEVICE=$::opt_device";
755
756 ### option outfile
757 my $OutputFilename = $::opt_outfile;
758 if (! $OutputFilename) {
759 if ($::opt_gs) {
760 if ($::opt_filter) {
761 debug "Filtering: will write standard output";
762 $OutputFilename = "-";
763 } else {
764 # Ghostscript, no filter: replace input extension with .pdf.
765 $OutputFilename = $InputFilename;
766 my $ds = $on_windows_or_cygwin ? '\\/' : '/';
767 $OutputFilename =~ s/\.[^\.$ds]*$//;
768 $OutputFilename .= ".pdf";
769 }
770 } else {
771 debug "No Ghostscript: will write standard output";
772 $OutputFilename = "-";
773 }
774 }
775 #
776 # gs -sOutputFilename opens pipes itself if the string starts with
777 # %pipe or |. Disallow this in restricted mode.
778 if ($restricted && $OutputFilename =~ /^(%pipe|\|)/) {
779 error "Output to pipe forbidden in restricted mode: $OutputFilename";
780 }
781 $OutputFilename =~ s/%/%%/g; # stop gs interpretation of % characters
782 debug "Output filename:", $OutputFilename;
783 push @GS, "-sOutputFile=$OutputFilename";
784
785 ### options compress, embed, res, autorotate
786 $::opt_pdfsettings = 'prepress' if $::opt_embed and not $::opt_pdfsettings;
787 if ($::opt_pdfsettings
788 && $::opt_pdfsettings
789 !~ s/^\/?(screen|ebook|printer|prepress|default)$/$1/) {
790 warnerr "Invalid value for --pdfsettings: $::opt_pdfsettings";
791 $::opt_pdfsettings = '';
792 }
793 # use # instead of = to avoid mingw path munging.
794 push (@GS, "-dPDFSETTINGS#/$::opt_pdfsettings") if $::opt_pdfsettings;
795
796 push @GS, qw[
797 -dMaxSubsetPct=100
798 -dSubsetFonts=true
799 -dEmbedAllFonts=true
800 ] if $::opt_embed;
801
802 push @GS, '-dUseFlateCompression=false' unless $::opt_compress;
803
804 push @GS, qw(-sColorConversionStrategy=Gray -dProcessColorModel=/DeviceGray)
805 if $::opt_gray;
806
807 if ($::opt_res and
808 not $::opt_res =~ /^(\d+(x\d+)?)$/) {
809 warnerr "Invalid resolution: $opt_res";
810 $::opt_res = '';
811 }
812 push @GS, "-r$::opt_res" if $::opt_res;
813 $resmsg = $::opt_res ? $::opt_res : "[use gs default]";
814
815 # \label{val_autorotate}
816 if ($::opt_autorotate and
817 not $::opt_autorotate =~ /^(None|All|PageByPage)$/) {
818 warnerr "Invalid value for --autorotate: $::opt_autorotate' "
819 . "(use 'All', 'None' or 'PageByPage'";
820 $::opt_autorotate = '';
821 }
822 # use # instead of = to avoid mingw path munging.
823 push (@GS, "-dAutoRotatePages#/$::opt_autorotate") if $::opt_autorotate;
824 $rotmsg = $::opt_autorotate ? $::opt_autorotate : "[use gs default]";
825
826 foreach my $gsopt (@::opt_gsopt) {
827 if ($restricted) {
828 my $ok = 0;
829 if ($gsopt =~ /^-[dD]([A-Za-z0-9]+)(=(.*))?$/) {
830 my $name = $1;
831 my $value = $3;
832 $value = 'true' if not defined $value;
833 if ($optcheck{$name} and $value =~ /^($optcheck{$name})$/) {
834 $ok = 1;
835 }
836 else {
837 warnerr "Option forbidden in restricted mode: --gsopt $gsopt";
838 $gsopt = '';
839 }
840 }
841 if (not $ok) {
842 warnerr "Option forbidden in restricted mode: --gsopt $gsopt";
843 $gsopt = '';
844 }
845 }
846 push @GS, $gsopt if $gsopt;
847 }
848
849 ### option BoundingBox types
850 my $BBName = "%%BoundingBox:";
851 !($::opt_hires and $::opt_exact) or
852 error "Options --hires and --exact cannot be used together";
853 $BBName = "%%HiResBoundingBox:" if $::opt_hires;
854 $BBName = "%%ExactBoundingBox:" if $::opt_exact;
855 debug "BoundingBox comment:", $BBName;
856
857 ### validate input file name in restricted mode \label{openin_any}
858 if ($restricted and not $::opt_filter
859 and not safe_name('in', $InputFilename)) {
860 error "Input filename '$InputFilename' not allowed in restricted mode.";
861 }
862
863 ### validate output file name in restricted mode \label{openout_any}
864 if ($restricted and not safe_name('out', $OutputFilename)) {
865 error "Output filename '$OutputFilename' not allowed in restricted mode.";
866 }
867
868 ### option gs
869 if ($::opt_gs) {
870 debug "Ghostscript command:", $GS;
871 debug "Compression:", ($::opt_compress) ? "on" : "off";
872 debug "Embedding:", ($::opt_embed) ? "on" : "off";
873 debug "Grayscale:", ($::opt_gray) ? "on" : "off";
874 debug "PDFSettings:", $::opt_pdfsettings;
875 debug "Resolution:", $resmsg;
876 debug "Rotation:", $rotmsg;
877 }
878
879 ### emacs-page
880 ### open input file
881 if ($::opt_filter) {
882 open(IN, '<-') || error("Cannot open stdin: $!");
883 } else {
884 open(IN, '<', $InputFilename) || error("Cannot open $InputFilename: $!");
885 }
886 binmode IN;
887
888 ### open output file
889 my $outname; # used in error message at end
890 my $tmp_filename; # temporary file for windows
891 my $OUT; # filehandle for output (GS pipe or temporary file)
892 use File::Temp 'tempfile';
893 if ($::opt_gs) {
894 if (! $on_windows_or_cygwin) { # list piped open works
895 push @GS, qw(- -c quit);
896 debug "Ghostscript pipe: @GS";
897 open($OUT, '|-', @GS)
898 or error "Cannot open Ghostscript for piped input: @GS";
899 } else {
900 # use a temporary file on Windows/msys/Cygwin.
901 if ($on_cygwin || $on_msys) {
902 # Use current directory for temporary file, to avoid problems of
903 # translation of directory name if native Windows gs gets invoked.
904 ($OUT, $tmp_filename) = tempfile(UNLINK => 1, DIR => '.');
905 } else {
906 ($OUT, $tmp_filename) = tempfile(UNLINK => 1);
907 }
908 debug "Using temporary file '$tmp_filename'";
909 }
910 $outname = $GS;
911 }
912 else {
913 debug "No Ghostscript: opening $OutputFilename";
914 if ($OutputFilename eq "-") {
915 $OUT = *STDOUT;
916 $outname = "-";
917 } else {
918 open($OUT, '>', $OutputFilename)
919 || error ("Cannot write \"$OutputFilename\": $!");
920 $outname = $OutputFilename;
921 }
922 }
923 binmode $OUT;
924
925 # reading a cr-eol file on a lf-eol system makes it impossible to parse
926 # the header and besides it will read the intire file into yor line by line
927 # scalar. this is also true the other way around.
928
929 ### emacs-page
930 ### scan a block, try to determine eol style
931
932 my $buf;
933 my $buflen;
934 my @bufarray;
935 my $inputpos;
936 my $maxpos = -1;
937
938 # We assume 2048 is big enough.
939 my $EOLSCANBUFSIZE = 2048;
940
941 # PJL
942 my $UEL = "\x1B%-12345X";
943 my $PJL = '@PJL[^\r\n]*\r?\n';
944
945 $buflen = read(IN, $buf, $EOLSCANBUFSIZE);
946 if ($buflen > 0) {
947 my $crlfpos;
948 my $lfpos;
949 my $crpos;
950
951 $inputpos = 0;
952
953 # TN 5002 "Encapsulated PostScript File Format Specification"
954 # specifies a DOS EPS binary file format for including a
955 # device-specific screen preview.
956 #
957 # DOS EPS Binary File Header (30 Bytes):
958 # * Bytes 0-3: 0xC5D0D3C6
959 # * Bytes 4-7: Offset of PostScript section
960 # * Bytes 8-11: Length of PostScript section
961 # * ...
962 # * Bytes 28-29: XOR checksum of bytes 0-27 or 0xFFFF
963 if ($buflen > 30 and $buf =~ /^\xC5\xD0\xD3\xC6/) {
964 debug "DOS EPS binary file header found";
965 my $header = substr($buf, 0, 30);
966 my ($offset_ps, $length_ps, $checksum) = unpack("x[V]VVx[V4]n", $header);
967 debug " PS offset: $offset_ps";
968 debug " PS length: $length_ps";
969 $maxpos = $offset_ps + $length_ps;
970 # validate checksum
971 if ($checksum == 0xFFFF) {
972 debug " No checksum";
973 }
974 else {
975 debug " Checksum: $checksum";
976 my $cs = 0;
977 map { $cs ^= $_ } unpack('n14', $header);
978 if ($cs != $checksum) {
979 warning "Wrong checksum of DOS EPS binary header";
980 }
981 }
982 # go to the start of the PostScript section and refill buffer
983 if ($::opt_filter) {
984 if ($offset_ps <= $buflen) {
985 $buf = substr($buf, $offset_ps);
986 $buflen = $buflen - $offset_ps;
987 $inputpos = $offset_ps;
988 my $len = read(IN, $buf, $offset_ps, $buflen);
989 $buflen += $len;
990 }
991 else {
992 $inputpos = $buflen;
993 $buflen = 0;
994 my $skip = $offset_ps - $inputpos;
995 while ($skip > 0) {
996 $buflen = read(IN, $buf,
997 $skip > $EOLSCANBUFSIZE ? $EOLSCANBUFSIZE : $skip);
998 $buflen > 0 or error "Unexpected end of input stream";
999 $inputpos += $buflen;
1000 $skip = $offset_ps - $inputpos;
1001 }
1002 $buflen = read(IN, $buf, $EOLSCANBUFSIZE);
1003 $buflen > 0 or error "Unexpected end of input stream";
1004 }
1005 }
1006 else {
1007 seek(IN, $offset_ps, 0) || error "Cannot seek to PostScript section";
1008 $inputpos = $offset_ps;
1009 $buflen = read(IN, $buf, $EOLSCANBUFSIZE);
1010 $buflen > 0 or error "Reading PostScript section failed";
1011 }
1012 }
1013 elsif ($buf =~ s/^($UEL($PJL)+)//) {
1014 $inputpos = length($1);
1015 debug "PJL commands removed at start of file: $inputpos bytes";
1016 }
1017 else {
1018 # remove binary junk before header
1019 # if there is no header, we assume the file starts with ascii style and
1020 # we look for a eol style anyway, to prevent possible loading of the
1021 # entire file
1022 if ($buf =~ /%!/) {
1023 # throw away binary junk before %!
1024 $buf =~ s/(.*?)%!/%!/o;
1025 $inputpos = length($1);
1026 debug "Binary junk at start of file: $inputpos byte(s)";
1027 }
1028 }
1029
1030 $lfpos = index($buf, "\n");
1031 $crpos = index($buf, "\r");
1032 $crlfpos = index($buf, "\r\n");
1033
1034 if ($crpos > 0 and ($lfpos == -1 or $lfpos > $crpos+1)) {
1035 # The first eol was a cr and it was not immediately followed by a lf
1036 $/ = "\r";
1037 debug "The first eol character was a CR ($crpos) and not immediately followed by a LF ($lfpos)";
1038 }
1039
1040 # Now we have set the correct eol-character. Get one more line and add
1041 # it to our buffer. This will make the buffer contain an entire line
1042 # at the end. Then split the buffer in an array. We will draw lines from
1043 # that array until it is empty, then move again back to <IN>
1044 $buf .= <IN> unless eof(IN);
1045 $buflen = length($buf);
1046
1047 # In case of DOS EPS binary files respect end of PostScript section.
1048 if ($maxpos> 0 and $inputpos + $buflen > $maxpos) {
1049 $buflen = $maxpos - $inputpos;
1050 $buflen > 0 or error "Internal error";
1051 $buf = substr($buf, 0, $buflen);
1052 }
1053
1054 # Some extra magic is needed here: if we set $/ to \r, Perl's re engine
1055 # still thinks eol is \n in regular expressions (not very nice) so we
1056 # cannot split on ^, but have to split on a look-behind for \r.
1057 if ($/ eq "\r") {
1058 @bufarray = split(/(?<=\r)/ms, $buf); # split after \r
1059 }
1060 else {
1061 @bufarray = split(/^/ms, $buf);
1062 }
1063 }
1064
1065 ### getline
1066 sub getline
1067 {
1068 if ($#bufarray >= 0) {
1069 $_ = shift(@bufarray);
1070 }
1071 elsif ($maxpos > 0 and $inputpos >= $maxpos) {
1072 $_ = undef;
1073 }
1074 else {
1075 $_ = <IN>;
1076 if ($maxpos > 0) {
1077 my $skip = $maxpos - $inputpos - length($_);
1078 if ($skip < 0) {
1079 $_ = substr($_, 0, $skip);
1080 }
1081 }
1082 }
1083 $inputpos += length($_) if defined $_;
1084 return defined($_);
1085 }
1086
1087 ### scan first line
1088 my $header = 0;
1089 getline();
1090 if (/%!/) {
1091 # throw away binary junk before %!
1092 s/(.*)%!/%!/o;
1093 }
1094 $header = 1 if /^%/;
1095 debug "Scanning header for BoundingBox";
1096 print $OUT $_;
1097
1098 ### variables and pattern for BoundingBox search
1099 my $bbxpatt = '[0-9eE\.\-]';
1100 # protect backslashes: "\\" gets '\'
1101 my $BBValues = "\\s*($bbxpatt+)\\s+($bbxpatt+)\\s+($bbxpatt+)\\s+($bbxpatt+)";
1102 my $BBCorrected = 0;
1103
1104 sub CorrectBoundingBox
1105 {
1106 my ($llx, $lly, $urx, $ury) = @_;
1107 debug "Old BoundingBox:", $llx, $lly, $urx, $ury;
1108 my ($width, $height) = ($urx - $llx, $ury - $lly);
1109 my ($xoffset, $yoffset) = (-$llx, -$lly);
1110 debug "New BoundingBox: 0 0", $width, $height;
1111 debug "Offset:", $xoffset, $yoffset;
1112
1113 print $OUT "%%BoundingBox: 0 0 $width $height$/";
1114 print $OUT "<< /PageSize [$width $height] >> setpagedevice$/";
1115 print $OUT "gsave $xoffset $yoffset translate$/";
1116 }
1117
1118 ### emacs-page
1119 ### scan header
1120 if ($header) {
1121 HEADER: while (getline()) {
1122 ### Fix for freehand bug ### by Peder Axensten
1123 next HEADER if(!/\S/);
1124
1125 ### end of header
1126 if (!/^%/ or /^%%EndComments/) {
1127 print $OUT $_;
1128 last;
1129 }
1130
1131 ### BoundingBox with values
1132 if (/^$BBName$BBValues/o) {
1133 CorrectBoundingBox $1, $2, $3, $4;
1134 $BBCorrected = 1;
1135 last;
1136 }
1137
1138 ### BoundingBox with (atend)
1139 if (/^$BBName\s*\(atend\)/) {
1140 debug $BBName, "(atend)";
1141 if ($::opt_filter) {
1142 warning "Cannot look for BoundingBox in the trailer",
1143 "with option --filter";
1144 last;
1145 }
1146 my $pos = $inputpos;
1147 debug "Current file position:", $pos;
1148
1149 # looking for %%BoundingBox
1150 while (getline()) {
1151 # skip over included documents
1152 my $nestDepth = 0;
1153 $nestDepth++ if /^%%BeginDocument/;
1154 $nestDepth-- if /^%%EndDocument/;
1155 if ($nestDepth == 0 && /^$BBName$BBValues/o) {
1156 CorrectBoundingBox $1, $2, $3, $4;
1157 $BBCorrected = 1;
1158 last;
1159 }
1160 }
1161
1162 # go back
1163 seek(IN, $pos, 0) or error "Cannot go back to line \"$BBName (atend)\"";
1164 $inputpos = $pos;
1165 @bufarray = ();
1166 last;
1167 }
1168
1169 # print header line
1170 print $OUT $_;
1171 }
1172 }
1173
1174 ### print rest of file
1175 while (getline()) {
1176 print $OUT $_;
1177 }
1178
1179 ### emacs-page
1180 ### close files
1181 close(IN);
1182 print $OUT "$/grestore$/" if $BBCorrected;
1183 close($OUT);
1184
1185 ### actually run GS if we were writing to a temporary file
1186 if (defined $tmp_filename) {
1187 push @GS, $tmp_filename;
1188 push @GS, qw(-c quit);
1189 debug "Ghostscript command: @GS";
1190 system @GS;
1191 }
1192
1193 # if ghostscript exited badly, we should too.
1194 if ($? & 127) {
1195 error(sprintf "Writing to $outname failed, signal %d\n", $? & 127);
1196 } elsif ($? != 0) {
1197 error(sprintf "Writing to $outname failed, error code %d\n", $? >> 8);
1198 }
1199
1200 warning "BoundingBox not found" unless $BBCorrected;
1201 debug "Done.";
1202
1203 # vim: ts=8 sw=2 expandtab: