Debian Codegraph @

texk/texlive/linked_scripts/epspdf/epspdf.tlu

raw
1 #!/usr/bin/env texlua
2
3 kpse.set_program_name('texlua')
4
5 --[[
6 epspdf conversion utility
7
8 0.6.0: first texlua version
9 0.6.1: allow TeX installation on path with spaces
10 0.6.2: compatibility fix for luatex 0.81
11 0.6.3: compatibility fixes for luatex 0.9x
12 0.6.4: adaptations for newer versions of LuaTeX and ghostscript;
13 some refactoring; better handling of some corner cases
14 0.6.5: eliminate .setpdfwrite from ghostscript commandlines,
15 since this is now considered obsolete
16 0.6.5.1: eliminate faulty check for writability system_tmpdir;
17 just error out when no tempdir for epspdf can be created.
18 Avoid spawn for MiKTeX.
19
20 Copyright (C) 2006-2023 Siep Kroonenberg
21
22 siepo at bitmuis nl
23
24 This program is free software, licensed under the GNU GPL, >=2.0.
25 This software comes with absolutely NO WARRANTY. Use at your own risk!
26
27 Note.
28 TeX code for cropping pdfs adapted from Heiko Oberdiek's pdfcrop utility
29
30 Program structure
31
32 - early initialization
33 - functions for:
34 - error handling
35 - file- and path utilities
36 - other general utilities
37 - infrastructure: logging and temporary files
38 - reading and writing settings
39 - gui function for communicating with frontend
40 - boundingboxes
41 - manipulating [e]ps- and pdf files
42 - the PsPdf object:
43 - creator functions
44 - boundingbox handling
45 - one-step conversion methods
46 - any_to_any function.
47 this function checks options, the one-step converters check for success.
48 - main initialization section:
49 - collecting system information
50 - infrastructure: setting up logging and temp directory
51 - settings:
52 - defining settings-, descriptions-, options- and auxiliary tables
53 - read settings
54 - defining commandline options and help function
55 - parsing commandline and performing non-conversion options
56 - calling any_to_any
57 - finishing up
58
59 all calls to external programs work on temporary files with a simple
60 generated filename. The current directory is a newly-created
61 temporary directory. So no need to quote names of input- and output
62 filenames.
63
64 POSSIBLE EXTENSIONS
65
66 - duplicating epstopdf options
67 - custom options for gs and pdftops
68
69 --]]
70
71 -- some general utilities and globals ---------------------------
72
73 -- early initializations
74
75 eol = false
76 path_sep = false
77 if os.type=='unix' then
78 eol='\n'
79 path_sep = ':'
80 else
81 eol='\r\n'
82 path_sep = ';'
83 end
84
85 infile = false
86 outfile = false
87
88 bufsize=16000 -- for reading and writing files
89
90 -- these `declarations' are not really needed;
91 -- they are here mainly for my own peace of mind
92
93 from_gui = false -- whether epspdf is run from the epspsdtk gui
94
95 cwd = ''
96
97 -- Windows: miktex, TL or neither.
98 -- Actual values determined during system-dependent initialization
99 is_miktex = false
100 is_tl_w32 = false
101
102 -- Luatex 1.09 and later replace epdf with pdfe
103
104 -- some global file- and directory names
105 gs_prog = false
106 pdftops = false
107 epsdir = false
108 rcfile = false
109 logfile = false
110 tempdir = false
111 tempfiles = {}
112 -- childpath = false
113 -- os.getenv('path') returns the parents path,
114 -- so we need to keep track ourselves of the child path
115
116 options = false -- actual conversion options
117 settings = false -- persistent settings; may be stored in config file
118 descriptions = false -- help strings for settings
119 gs_options = false
120 pdf_options = false
121 pdf_tail_options = false
122 ps_options = false
123 gray_options = false
124
125 -- logging ------------------------
126
127 -- we open and close the logfile anew for each write.
128 -- failure to open does not constitute an error.
129
130 function print_log(s)
131 local f = io.open(logfile, 'a')
132 if f then
133 f:write(s,eol)
134 f:close()
135 end
136 if from_gui then
137 print(s) -- intercepted by the gui
138 end
139 end
140
141 function write_log(s)
142 print_log(string.format('%s %s',
143 os.date('%Y/%m/%d %H:%M:%S', os.time()), s))
144 end
145
146 function log_cmd(cmd)
147 write_log('[' .. table.concat(cmd, '] [') .. ']')
148 end
149
150 -- error- and debug -------------------------
151
152 -- Simple-minded error handling. At most, we call a function which
153 -- tries to write the error message to log before re-raising the error.
154
155 -- When run from the Tcl/Tk gui, this gui will capture error messages.
156
157 function errror(mess)
158 if infile and outfile then
159 mess = 'Failure to convert '..infile..' to '..outfile..':\n'..mess
160 end
161 if logfile then pcall(write_log, mess) end
162 -- ignore result of pcall: we can do nothing about failure
163 error(mess, 2)
164 end
165
166 function warn(mess)
167 if logfile then write_log(mess) end
168 print(mess)
169 end
170
171 -- function dbg(mess)
172 -- if options.debug then
173 -- warn(mess)
174 -- end
175 -- end
176
177 -- file- and path utilities ----------------
178
179 -- function ep_shortname(path)
180 -- if os.type=='unix' then
181 -- return path
182 -- else
183 -- -- shortname appears not to work under miktex
184 -- -- so return original path as a fallback
185 -- local sp = lfs.shortname(path)
186 -- return sp or path
187 -- end
188 -- end
189
190 -- prepend or append dir to path if necessary
191 function maybe_add_path(dir, append)
192 local dircmp = path_sep .. dir .. path_sep
193 local pathcmp = path_sep .. kpse.var_value('PATH') .. path_sep
194 -- case folding
195 if os.name=='windows' or os.name=='cygwin' or os.name=='macosx' then
196 dircmp = string.lower(dir)
197 pathcmp = string.lower(pathcmp)
198 end
199 -- slash flipping
200 if os.type=='windows' then
201 pathcmp = (string.gsub(pathcmp, '/', '\\'))
202 dircmp = (string.gsub(dircmp, '/', '\\'))
203 end
204 if not string.find(pathcmp, dircmp, 1, true) then
205 if not append then -- prepend
206 os.setenv('PATH', dir..path_sep..kpse.var_value('PATH'))
207 else -- append
208 os.setenv('PATH', kpse.var_value('PATH')..path_sep..dir)
209 end
210 end
211 end
212
213 function fw(path)
214 if os.type=='windows' then
215 return string.gsub(path, '\\', '/')
216 else
217 return path
218 end
219 end
220
221 function absolute_path(path)
222
223 --[[ Return absolute normalized version of path, interpreted
224 from the directory from where the program was called.
225
226 We use the fact that lfs.currentdir() always returns an absolute and
227 normalized path. So we go to the parent directory of path, ask for
228 the current directory and then combine the current directory with
229 the base filename.
230
231 On windows, texlua has no trouble cd-ing into a UNC path.
232
233 The function returns nil if there is no valid parent path.
234 This might be an issue if path is a directory,
235 but we shall apply this function only on files.
236 It is ok if path itself does not exist. --]]
237
238 path = fw(path)
239
240 local present_dir = fw(lfs.currentdir())
241
242 lfs.chdir(cwd)
243
244 local parentdir
245 local filename
246
247 if string.match(path, '/') then
248 parentdir, filename = string.match(path,'^(.*)/([^/]*)$')
249 if parentdir=='' then
250 parentdir = '/'
251 -- on unix, this is an absolute path. on windows, it is not
252 if os.type=='windows' then
253 lfs.chdir('/')
254 parentdir = fw(lfs.currentdir())
255 end
256 elseif os.type=='windows' and string.match(parentdir,'^[a-zA-Z]:$') then
257 parentdir = string.sub(parentdir,1,2)..'/'
258 else
259 if not lfs.chdir(parentdir) then
260 parentdir = nil
261 else
262 parentdir = fw(lfs.currentdir())
263 end
264 end
265 elseif os.type=='windows' and string.match(path,'^[a-zA-Z]:') then
266 -- windows: d:file
267 parentdir = string.sub(path,1,2)
268 if not lfs.chdir(parentdir) then
269 parentdir = nil
270 else
271 parentdir = fw(lfs.currentdir())
272 filename = string.sub(path,3)
273 end
274 else
275 parentdir = fw(lfs.currentdir())
276 filename = path
277 end
278 lfs.chdir(present_dir)
279 if not parentdir then
280 return nil
281 elseif string.sub(parentdir,-1)=='/' then
282 return parentdir..filename, parentdir
283 else
284 return parentdir..'/'..filename, parentdir
285 end
286 end -- absolute_path
287
288 -- check whether prog is on the searchpath.
289 -- we need it only under unix,
290 -- so we save ourselves the trouble of accommodating windows.
291 -- we return the original string, although we only need a yes or no answer
292
293 function find_on_path (prog)
294 if os.type == 'unix' then
295 for d in string.gmatch(os.getenv('PATH'), '[^:]+') do
296 if lfs.isfile(d..'/'..prog) then
297 return prog
298 end
299 end
300 else
301 for d in string.gmatch(os.getenv('PATH'), '[^;]+') do
302 if lfs.isfile(d..'\\'..prog) then
303 return prog
304 end
305 end
306 end
307 return false
308 end -- find_on_path
309
310 function system_tempdir ()
311 local d = false
312 if os.type=='windows' then
313 d = os.getenv('TEMP')
314 if not d then
315 d = os.getenv('TMP')
316 end
317 else
318 d = os.getenv('TMPDIR')
319 if not d then
320 d = '/tmp'
321 end
322 end
323 -- cygwin: $TEMP=/tmp, root '/' being root of cygwin installation
324 return d
325 end
326
327 -- other general utilities ---------------------------
328
329 -- check whether el occurs in array lst
330 function in_list (el, lst)
331 if not lst then return false end
332 for _,p in ipairs(lst) do
333 if el == p then
334 return true
335 end
336 end
337 return false
338 end -- in_list
339
340 -- remove leading and trailing, but not embedded spaces
341 function strip_outer_spaces(s)
342 s = string.gsub(s, '%s*$', '')
343 s = string.gsub(s, '^%s*', '')
344 return s
345 end -- strip_outer_spaces
346
347 function join(t, sep, lastsep)
348 -- there is a table function concat which does this,
349 -- but without optional different lastsep
350 if t==nil or #t<1 then return '' end -- or should we return nil?
351 local s = t[1]
352 for i=2,#t do -- ok if #t<2
353 if i==#t and lastsep then
354 s = s .. lastsep .. t[i]
355 else
356 s = s .. sep .. t[i]
357 end
358 end
359 return s
360 end -- join
361
362 -- combine several tables into one.
363 -- the parameter is a table of tables.
364 function tab_combine (t)
365 local res = {}
366 for _,tt in ipairs(t) do
367 for __, ttt in ipairs(tt) do
368 table.insert(res, ttt)
369 end
370 end
371 return res
372 end -- tab_combine
373
374 -- workaround for miktex spawn problem
375 function spawnexec(cmd)
376 if is_miktex then
377 if type(cmd)=='table' then
378 return os.execute(table.concat(cmd, ' '))
379 -- there is no need for quoting in the cases used
380 else
381 return os.execute(cmd)
382 end
383 else
384 return os.spawn(cmd)
385 end
386 end
387
388 -- files ----------------------------------------------------
389 -- Copy a file in chunks, with optional length and offset.
390 -- Since files may be very large, we copy them piecemeal.
391 -- An initial chunk of size bufsize should be plenty to include
392 -- any interesting header information.
393
394 function slice_file(source, dest, len, offset, mode)
395 -- The final three parameters can be independently left out by
396 -- specifying false as value
397 -- Assume caller ensured parameters of correct type.
398 -- We do not allow negative offsets.
399
400 local copy2self = false
401 if source==dest then copy2self = true end
402 if os.type=='unix' and
403 lfs.attributes(source,'ino')==lfs.attributes(dest,'ino') then
404 copy2self = true
405 end
406 if copy2self and not len and not offset and mode~='ab' then
407 return -- nothing to do
408 elseif copy2self then
409 errror('slice_file invoked with identical source and destination '..
410 source..' and non-simple copy')
411 end
412 -- in practice any_to_any already checks for this.
413 -- in addition, the main program makes a backup if infile==outfile
414
415 local sz = lfs.attributes(source, 'size')
416 if not offset then
417 offset = 0
418 elseif offset>sz then
419 offset = sz
420 end
421 if not len or len>sz-offset then
422 len = sz - offset
423 end
424 if not mode then mode = 'wb' end
425 local buffer=''
426 local s=io.open(source, 'rb')
427 s:seek('set', offset)
428 local copied = 0
429 local d=io.open(dest, mode)
430 if not d then errror('slice_file: failed to copy to '..dest) end
431 local slen = len
432 while slen>0 do
433 if slen>=bufsize then
434 buffer = s:read(bufsize)
435 slen = slen - bufsize
436 else
437 buffer = s:read(slen)
438 slen = 0
439 end
440 if not d:write(buffer) then
441 errror('slice_file: failed to copy to '..dest)
442 end
443 end
444 s:close()
445 d:close()
446 end -- slice_file
447
448 function move_or_copy(source, dest)
449 if lfs.isfile(dest) and lfs.attributes(dest, 'size')>0 then
450 warn('Removing old '..dest)
451 os.remove(dest) -- in case of failure, go ahead anyway
452 end
453 -- Windows: try first renaming in-place before moving to the right directory
454 if os.type == 'windows' then
455 if os.rename(source, source..'.renamed') then
456 source = source..'.renamed'
457 end
458 end
459 if not os.rename(source, dest) then
460 slice_file(source, dest) -- bails out on failure
461 local ok, err_mess = os.remove(source)
462 if not ok then
463 warn('Failed to remove old ' .. source .. ': ' .. err_mess)
464 end
465 end
466 end
467
468 -- temporary files ----------------------------------------
469
470 -- tempdir = false -- will be created later and chdir-ed into
471 -- tempfiles initialized early to empty table
472
473 -- We just name our temporary files nn.<ext> with successive nn.
474 -- We cannot exclude that another process uses our tempdir
475 -- so we have to first check for each new file whether it already exists.
476 -- Epspdf does all the real work from the temp directory.
477
478 function mktemp(ext)
479 local froot, fname, f, g
480 for i=0,99 do
481 froot = string.format('%02d.', i)
482 fname = froot..ext
483 if ext~='tex' then
484 if not lfs.isfile(fname) then
485 f = io.open(fname, 'wb')
486 if not f then
487 errror('Cannot create temporary file '..fname)
488 end
489 f:close()
490 table.insert(tempfiles, fname)
491 return froot..ext -- no need to record pdf name
492 end
493 else
494 -- tex; we also need a pdf
495 if not lfs.isfile(fname) and not lfs.isfile(froot..'pdf') then
496 local f = io.open(fname, 'wb')
497 if not f then
498 errror('Cannot create temporary file '..fname)
499 end
500 f:close()
501 table.insert(tempfiles, fname)
502 fname = froot..'pdf'
503 g = io.open(fname, 'wb')
504 if not g then
505 errror('Cannot create temporary file '..fname)
506 end
507 g:close()
508 table.insert(tempfiles, fname)
509 table.insert(tempfiles, froot..'log')
510 return froot..ext -- no need to record pdf name
511 end
512 end -- if
513 end -- for
514 errror('Cannot create temporary file in '..tempdir)
515 end
516
517 function waitasec()
518 -- stupid windows file locking; assume vista or later
519 if os.type=='windows' then
520 os.execute('timeout /t 1 /nobreak >nul')
521 -- else do nothing
522 end
523 -- error checking pointless
524 end
525
526 function cleantemp()
527 lfs.chdir(tempdir)
528 if os.type=='windows' then waitasec() end
529 for _,f in ipairs(tempfiles) do
530 if lfs.isfile(f) then
531 local success, mess = os.remove(f)
532 if not success then write_log(mess) end
533 end
534 end
535 local empty = true
536 for f in lfs.dir('.') do
537 if f ~= '.' and f ~= '..' then
538 empty = false
539 write_log('Temp dir '..tempdir..' contains '..f..' therefore not removed')
540 break
541 end
542 end
543 if os.type=='windows' then waitasec() end
544 lfs.chdir('..')
545 if empty then
546 local res, mess
547 res, mess = lfs.rmdir(tempdir)
548 if not res then
549 write_log('Failed to remove empty '..tempdir..'\n'..mess)
550 end
551 end
552 end
553
554 -- gs_epsdevice -----------------------
555
556 function gs_epsdevice()
557 local gh = io.popen(gs_prog..' -help')
558 local s = gh:read("*a")
559 gh:close()
560 if string.find(s,'eps2write') then
561 return 'eps2write'
562 elseif string.find(s,'epswrite') then
563 return 'epswrite'
564 else
565 return false
566 end
567 end
568
569 -- settings -----------------------
570
571 function write_settings (file)
572 local f
573 if file then
574 f = io.open(file, 'wb')
575 if not f then
576 return
577 end
578 else -- stdout to be captured by epspdftk
579 f = io.output()
580 end
581 for k, v in pairs(settings) do
582 if descriptions[k] and file then
583 f:write(eol, '# ', descriptions[k], eol)
584 end
585 f:write(k, ' = ', tostring(v), eol)
586 end
587 if file then
588 f:close()
589 end
590 end
591
592 function read_settings(file)
593 -- read and interpret rcfile
594 -- we shall ignore illegal entries.
595 local contents
596 local f
597 if file then
598 f = io.open(rcfile, 'rb')
599 if not f then
600 return
601 end
602 else
603 f = io.input()
604 end
605 contents = f:read(10000)
606 if file then
607 f:close()
608 end
609 if not contents or contents=='' then
610 return
611 end
612 -- remove initial \r and \n characters
613 contents = string.gsub(contents, '^[\r\n]*', '');
614 -- gmatch chops contents into series of non-line-ending characters
615 -- possibly followed by line-ending characters i.e. in lines
616 local k, v, vl, vnum
617 for l in string.gmatch(contents, '[^\r\n]+[\r\n]*') do
618 l = string.match(l,'[^\r\n]*')
619 if not string.match(l, '^#') then
620 k, v = string.match(l, '^%s*([^%s]+)%s*=%s*(.*)$')
621 if v then v = string.gsub(v,'%s*$', '') end
622 -- now handle k and v
623 if k == 'pdf_target' then
624 -- ignore unless valid option
625 if in_list(v, pdf_targets) then
626 settings[k] = v
627 end
628 elseif k == 'pdf_version' then
629 -- ignore unless valid option
630 if in_list(v, pdf_versions) then
631 settings[k] = v
632 end
633 elseif k == 'ignore_pdftops' then
634 vl = string.lower(string.sub(v,1,1))
635 if v == 0 or vl == 'n' or vl == 'f' then
636 settings.use_pdftops = true
637 elseif v == 1 or vl == 'y' or vl == 't' then
638 settings.use_pdftops = false
639 end
640 elseif k == 'use_pdftops' then
641 vl = string.lower(string.sub(v,1,1))
642 if v == '0' or vl == 'n' or vl == 'f' then
643 settings.use_pdftops = false
644 elseif v == '1' or vl == 'y' or vl == 't' then
645 settings.use_pdftops = true
646 end
647 -- final three settings not used by epspdf itself but
648 -- passed along to epspdftk
649 elseif k == 'ps_viewer' then
650 settings.ps_viewer = v
651 elseif k == 'pdf_viewer' then
652 settings.pdf_viewer = v
653 elseif k == 'default_dir' then
654 settings.default_dir = v
655 end -- test for k
656 end -- not matching ^#
657 end -- for
658 end -- read settings
659
660 function version_added()
661 for _, v in pairs(pdf_options) do
662 if string.find(v, '-dCompatibilityLevel') then
663 return true
664 end
665 end
666 return false
667 end
668
669 function maybe_add_version_parameter()
670 if options.type=='pdf' and not options.bbox and settings.pdf_version and
671 settings.pdf_version~='default' and not version_added() then
672 table.insert(pdf_options, '-dCompatibilityLevel#'..settings.pdf_version)
673 end
674 end
675
676 -- gui: reading and writing settings -----------
677
678 function gui(action)
679 -- use stdin for reading settings from gui, and stdout for writing
680 if action=='config_w' then
681 -- called at start of epspdftk
682 write_settings() -- to pipe epspdf => epspdftk
683 os.exit()
684 elseif action=='config_r' then
685 read_settings() -- from 'pipe' epspdftk => epspdf
686 write_settings(rcfile)
687 os.exit()
688 else
689 from_gui = true
690 end
691 end
692
693 -- boundingboxes ---------------------------------------------------
694
695 -- [HR]Bb.coords names same as those of epdf PDFRectangle
696 -- but the new pdfe simply uses an array
697
698 Bb = {}
699 Bb.coords = {'x1', 'y1', 'x2', 'y2'}
700
701 function Bb:from_rect(r)
702 -- also handle the case that r is a 4-element array:
703 if not r.x1 then r.x1 = r[1] end
704 if not r.y1 then r.y1 = r[2] end
705 if not r.x2 then r.x2 = r[3] end
706 if not r.y2 then r.y2 = r[4] end
707
708 for _,k in ipairs(self.coords) do
709 if not r[k] or type(r[k])~='number' then
710 errror('from_rect called with illegal parameters')
711 end
712 -- sanity check on size
713 -- FIXME: this limit is far too high
714 if r[k]+.5==r[k] or r[k]-.5==r[k] then
715 errror('Bb:from_rect: ' .. r[k] ..' greater than maxint')
716 end
717 local b = {}
718 local eps = 0.000001
719 b.x1, b.x2 = math.floor(math.min(r.x1, r.x2) + eps),
720 math.ceil(math.max(r.x1, r.x2) - eps)
721 b.y1, b.y2 = math.floor(math.min(r.y1, r.y2) + eps),
722 math.ceil(math.max(r.y1, r.y2) - eps)
723 if b.x1==b.x2 or b.y1==b.y2 then
724 errror('from_rect: width or height is zero')
725 end
726 setmetatable(b, {__index=self})
727 return b
728 end
729 end
730
731 Bb.bb_pat = '^%s*%%%%BoundingBox:'
732 Bb.bb_end = '^%s*%%%%BoundingBox:%s*%(%s*atend%s*%)'
733
734 function Bb:from_comment(s)
735 local p = self.bb_pat..'%s*([-+%d]+)'..string.rep('%s+([-+%d]+)',3)
736 local b = {}
737 b.x1, b.y1, b.x2, b.y2 = string.match(s, p)
738 if not b.y2 then
739 errror('Bb.from_comment: illegal boundingbox string ' .. s)
740 end
741 for _,k in ipairs(self.coords) do
742 b[k] = tonumber(b[k])
743 end
744 return Bb:from_rect(b)
745 end
746
747 function Bb:nonnegative ()
748 return self.x1>=0 and self.y1>=0
749 end
750
751 function Bb:comment()
752 -- if options.debug then print(debug.traceback()) end
753 return string.format('%%%%BoundingBox: %d %d %d %d',
754 self.x1, self.y1, self.x2, self.y2)
755 end
756
757 -- hires boundingboxes ---------------------------------------------
758
759 HRBb = {}
760
761 setmetatable(HRBb, {__index=Bb})
762
763 function HRBb:from_rect(r)
764 -- also handle the case that r is a 4-element array:
765 if not r.x1 then r.x1 = r[1] end
766 if not r.y1 then r.y1 = r[2] end
767 if not r.x2 then r.x2 = r[3] end
768 if not r.y2 then r.y2 = r[4] end
769
770 for _,k in ipairs(self.coords) do
771 if not r[k] or type(r[k])~='number' then
772 errror('from_rect called with illegal parameters')
773 end
774 -- sanity check on size
775 if r[k]+.5==r[k] or r[k]-.5==r[k] then
776 errror('HRBb:from_rect: ' .. b[k] ..' greater than maxint')
777 end
778 local b = {}
779 b.x1, b.x2 = math.min(r.x1, r.x2), math.max(r.x1, r.x2)
780 b.y1, b.y2 = math.min(r.y1, r.y2), math.max(r.y1, r.y2)
781 if b.x1==b.x2 or b.y1==b.y2 then
782 errror('from_rect: width or height is zero')
783 end
784 setmetatable(b, {__index=self})
785 return b
786 end
787 end
788
789 HRBb.bb_pat = '^%s*%%%%HiResBoundingBox:'
790 HRBb.bb_end = '^%s*%%%%HiResBoundingBox:%s*%(%s*atend%s*%)%s*$'
791
792 function HRBb:from_comment(s)
793 local p = self.bb_pat..'%s*([-+.%deE]+)'..string.rep('%s+([-+.%deE]+)',3)
794 local b = {}
795 b.x1, b.y1, b.x2, b.y2 = string.match(s, p)
796 if not b.y2 then
797 errror('HRBb.from_comment: illegal boundingbox string ' .. s)
798 end
799 for _,k in ipairs(self.coords) do
800 b[k] = tonumber(b[k])
801 end
802 return HRBb:from_rect(b)
803 end
804
805 function HRBb:nonnegative ()
806 return self.x1>=0 and self.y1>=0
807 end
808
809 function HRBb:comment()
810 return string.format('%%%%HiResBoundingBox: %f %f %f %f',
811 self.x1, self.y1, self.x2, self.y2)
812 end
813
814 --[[
815
816 -- no longer used: gs handles this
817 -- call this one also via pcall
818 function HRBb:wrapper()
819
820 -- local fn = mktemp('ps')
821 -- local f = io.open(fn, 'wb')
822 -- f.write(string.format('<< /PageSize [%f %f] >> setpagedevice\n',
823 -- self.x2 - self.x1, self.y2 - self.y1))
824 -- f.write(string.format('gsave\n%f %f translate\n', -self.x1, -self.y1))
825 -- f:close()
826 -- return fn
827
828 return string.format(
829 '<< /PageSize [%f %f] >> setpagedevice gsave %f %f translate',
830 self.x2 - self.x1, self.y2 - self.y1, -self.x1, -self.y1)
831 end
832
833 --]]
834
835 -- manipulating eps/ps/pdf files -----------------------------------
836
837 function identify()
838 local f = io.open(infile, 'rb')
839 if not f then
840 errror('Failure to open '..infile..' for identification')
841 end
842 local filestart= f:read(23)
843 f:close()
844 if not filestart or filestart=='' then
845 return false
846 elseif string.match(filestart,'^\197\208\211\198') then -- c5 d0 d3 c6
847 return 'epsPreview'
848 elseif string.match(filestart,'^%%!PS%-Adobe%-%d%.%d EPSF%-%d%.%d') then
849 return 'eps'
850 elseif string.match(filestart,'^%%!PS%-Adobe%-%d%.%d') then
851 for _, p in ipairs({'.eps', '.epi', '.epsi', '.epsf'}) do
852 if string.sub(string.lower(infile), -1-string.len(p),-1) == p then
853 return 'eps'
854 else
855 return 'ps'
856 end
857 end
858 return 'ps'
859 elseif string.match(filestart, '^%%PDF') then
860 return 'pdf'
861 else
862 return false
863 end
864 end -- identify
865
866 function pdf_props(path)
867 local pdfdoc, pgs, maver, miver
868 if pdfe then
869 pdfdoc = pdfe.open(path)
870 if pdfdoc then
871 pgs = pdfe.getnofpages(pdfdoc)
872 maver, miver = pdfe.getversion(pdfdoc)
873 end
874 if not (pdfdoc and pgs and maver and miver) then
875 errror('pdfe failed to get information about '..path)
876 end
877 pdfe.close(pdfdoc)
878 else
879 local cat
880 pdfdoc = epdf.open(path)
881 if pdfdoc then
882 cat = pdfdoc:getCatalog()
883 if cat then
884 pgs = cat:getNumPages()
885 end
886 maver = pdfdoc:getPDFMajorVersion()
887 miver = pdfdoc:getPDFMinorVersion()
888 end
889 if not (pdfdoc and pgs and maver and miver) then
890 errror('epdf failed to get information about '..path)
891 end
892 -- epdf.close(pdfdoc)
893 end
894 -- if os.type=='windows' then waitasec() end
895 if maver > 1 then
896 print(path..' has pdf major version \n'..tostring(maver)..
897 ' which is unsupported;\n'..
898 'Continuing with fingers crossed...')
899 end
900 return pgs, miver, maver
901 end -- pdf_props
902
903 function info()
904 local intype = identify()
905 if not intype then
906 print(infile..' has an unsupported filetype.')
907 elseif intype~='pdf' then
908 print(infile..' has type '..intype..'.')
909 else
910 local pgs, miver, maver = pdf_props(infile)
911 print(infile..' has type pdf, version '..tostring(maver)..
912 '.'..tostring(miver)..' and has '..tostring(pgs)..' pages.')
913 end
914 os.exit()
915 end
916
917 -- PsPdf object -------------------------------------------------
918
919 PsPdf = {}
920
921 -- creators
922
923 function PsPdf:new(ext)
924 local psp = {}
925 setmetatable(psp, {__index = self})
926 -- assign temp file
927 psp.path = mktemp(string.lower(ext))
928 if string.lower(ext)=='pdf' then
929 psp.type = 'pdf'
930 elseif string.lower(ext)=='eps' then
931 psp.type = 'eps'
932 elseif string.lower(ext)=='ps' then
933 psp.type = 'ps'
934 else
935 psp.type = false
936 end
937 if psp.type=='eps' then
938 psp.pages = 1
939 end
940 psp.bb = false
941 psp.hrbb = false
942 return psp
943 end -- PsPdf:new
944
945 function PsPdf:from_path(path)
946 local psp = {}
947 setmetatable(psp, {__index = self})
948 psp.path = path
949 if lfs.isfile(path) then
950 -- turn existing file into PsPdf object.
951 psp.type = identify(psp.path)
952 if psp.type=='pdf' then
953 psp.pages, psp.miver, psp.maver = pdf_props(psp.path)
954 end
955 else
956 errror('PsPdf:from_path called with non-existant file '..path)
957 end
958 if psp.type=='eps' then
959 psp.pages = 1
960 end
961 psp.bb = false
962 psp.hrbb = false
963 -- only calculate when needed
964 return psp
965 end -- PsPdf:from_path
966
967 -- do we need to downgrade the pdf to a lower version?
968 -- consider [e]ps lower than any pdf version
969 function PsPdf:to_downgrade()
970 if self.type~='pdf' then
971 return false
972 elseif options.type~='pdf' then
973 return true
974 elseif settings.pdf_version=='default' then
975 return false
976 elseif settings.pdf_version~='default' and
977 self.maver+0.1*self.miver-0.001 > tonumber(settings.pdf_version) then
978 -- -0.001: exact binary representation of pdf_version not guaranteed
979 return true
980 else
981 return false
982 end
983 end
984
985 --[[ getting boundingbox property from file itself --------------
986
987 get_bb_simple: use only for eps PsPdf objects we generated
988 ourselves, so we can assume that the bbox comments are in the header
989 and the hires bb lies within the lores bb.
990 Of course the file itself is not rewritten.
991
992 --]]
993
994 function PsPdf:get_bb_simple()
995 if self.type~='eps' then
996 errror('get_bb_simple called with non-eps file '..self.path)
997 end
998 self.bb = false
999 self.hrbb = false
1000 local slurp = false
1001 local f = io.open(self.path, 'rb')
1002 if f then
1003 slurp = f:read(bufsize)
1004 f:close()
1005 end
1006 lines = {}
1007 for l in string.gmatch(slurp, '[^\n\r]+') do
1008 if string.match(l, Bb.bb_pat) then
1009 self.bb = Bb:from_comment(l)
1010 elseif string.match(l, HRBb.bb_pat) then
1011 self.hrbb = HRBb:from_comment(l)
1012 elseif self.bb then
1013 break -- stop looking; we expect hrbb next to bb
1014 end
1015 if self.bb and self.hrbb then break end
1016 end
1017 if not self.bb then
1018 errror('No valid boundingbox for generated file' .. self.path)
1019 end
1020 return self -- no real need for a return value
1021 end
1022
1023 function PsPdf:bb_from_gs()
1024
1025 if self.type=='ps' then
1026 errror('bb_from_gs called with ps file '..self.path)
1027 -- not needed for generic PostScript,
1028 -- page selection only works with pdf files, so we save ourselves
1029 -- the trouble of picking the right bbox from a list
1030 end
1031 if self.type=='eps' and not self.bb:nonnegative() then
1032 errror('bb_from_gs called on ' .. self.path ..
1033 ' which has some negative boundingbox coordinates')
1034 -- any_to_any should guard against such an invocation
1035 end
1036
1037 -- Since Ghostscript writes the boundingbox comments to stderr,
1038 -- we need a shell to intercept this output:
1039
1040 local bb_file = mktemp('dsc')
1041 -- a somewhat low resolution parameter may help gs
1042 -- deal with eps files with large coordinates
1043 -- but this may impact the accuracy of the HRBb
1044 local cmdline
1045 if self.type=='eps' and (self.bb.x2 > 850 or self.bb.y2 > 850) then
1046 cmdline = gs_prog .. ' -r300 ' .. table.concat(gs_options,' ')
1047 else
1048 cmdline = gs_prog .. ' ' .. table.concat(gs_options,' ')
1049 end
1050 if self.type=='pdf' then
1051 pg = options.page or 1
1052 cmdline = cmdline .. ' -dFirstPage#' .. tostring(pg) ..
1053 ' -dLastPage#' .. tostring(pg)
1054 end
1055 cmdline = cmdline .. ' -sDEVICE#bbox ' .. self.path .. ' 2>'..bb_file
1056
1057 -- execute shell command
1058
1059 local r, cmd
1060 write_log('os.execute: '..cmdline)
1061 r = os.execute(cmdline)
1062 if not r then
1063 errror('Cannot get fixed boundingbox for '..self.path)
1064 end
1065
1066 -- read new bbox from ghostscript output
1067 -- can we really count on the plain bb coming first?
1068 -- OTOH, I would rather not introduce unnecessary complexity
1069 -- still, it may be better to match each line with [HR]Bb_pat
1070
1071 local bb = false
1072 local hrbb = false
1073 local fin = io.open(bb_file, 'r')
1074 if fin then
1075 for i=1,10 do -- actually, 2 should suffice
1076 local l = fin:read("*line")
1077 if not l then break end
1078 if string.match(l, Bb.bb_pat) then
1079 bb = Bb:from_comment(l)
1080 end
1081 if string.match(l, HRBb.bb_pat) then
1082 hrbb = HRBb:from_comment(l)
1083 end
1084 end
1085 fin:close()
1086 end
1087 if not bb or not hrbb then
1088 errror('Cannot get fixed boundingbox for '..self.path)
1089 end
1090 return bb, hrbb
1091 end
1092
1093 -- eps_clean: remove some problem features from eps (new file & object)
1094
1095 function PsPdf:eps_clean()
1096
1097 -- return a PsPdf object referring to a new file
1098 -- without a preview header and with boundingbox(es) in the header.
1099 -- return a new file even if no changes were needed.
1100
1101 local function bytes2num (s, i)
1102 -- convert substring s[i..i+3] to a number.
1103 -- by working byte for byte we avoid endian issues
1104 local n = string.byte(s, i+3)
1105 for j=2,0,-1 do n = 256*n + string.byte(s, i+j) end
1106 return n
1107 -- somehow the explicit expression below didn't work
1108 -- return ((256 * (256 * (256 * string.byte(s,i+3)) + string.byte(s,i+2))
1109 -- + string.byte(s,i+1)) + string.byte(s,i))
1110 end
1111
1112 if self.type~='eps' and self.type~='epsPreview' then
1113 errror('epsclean called with non-eps file ' .. self.path)
1114 end
1115 local offset, ps_length = false, false
1116 local fin, fout
1117 if self.type=='eps' then
1118 offset = 0
1119 ps_length = lfs.attributes(self.path, 'size')
1120 else
1121 -- read TOC; see Adobe EPS specification
1122 -- interpret byte for byte, in case the platform is not little-endian
1123 fin = io.open(self.path, 'rb')
1124 if fin then
1125 local toc = fin:read(12)
1126 fin:close()
1127 if toc and string.len(toc)==12 then
1128 offset = bytes2num(toc, 5)
1129 ps_length = bytes2num(toc, 9)
1130 end
1131 end
1132 if not offset then
1133 errror('Could not read preview header of ' .. self.path)
1134 end
1135 end
1136
1137 -- create the PsPdf object which is to be returned
1138
1139 local psp
1140 psp = PsPdf:new('eps')
1141
1142 -- read an initial and if necessary a final chunk of the file
1143 -- to find boundingbox comments.
1144
1145 local atend = false
1146 local hr_atend = false
1147 local slurp -- the read buffer
1148 local l -- contains current scanned line; split off from slurp
1149 -- pre_lines: scanned header lines; alternately lines and eols
1150 local pre_lines = {}
1151 -- new_offset: offset plus combined length of scanned header lines
1152 local new_offset = offset
1153 -- post_lines: scanned trailer lines
1154 local post_lines = {}
1155 -- middle_length: ps_length minus scanned header- and and maybe trailer parts
1156 -- this is the length of file that will be copied wholesale.
1157 local middle_length
1158 local i, i_bb, i_hrbb
1159 local j, j_bb, j_hrbb, j_end
1160 -- j_end: index of final scanned trailer line
1161 -- no i_end necessary: for header lines we can use #pre_lines.
1162
1163 fin = io.open(self.path, 'rb')
1164 if not fin then errror('Cannot read '..self.path) end
1165 fin:seek('set', offset)
1166
1167 -- remaining, unscanned length of input buffer slurp
1168 local unscanned = math.min(ps_length,bufsize)
1169 slurp = fin:read(unscanned)
1170
1171 -- unnecessary:
1172 psp.bb = nil
1173 psp.hrbb = nil
1174
1175 i, i_bb, i_hrbb = 0, false, false
1176 while unscanned>0 do
1177 i = i+1
1178 if string.find(slurp,'[\n\r]')==1 then
1179 l,slurp = string.match(slurp, '^([\n\r]+)(.*)$')
1180 else
1181 l,slurp = string.match(slurp, '^([^\n\r]+)(.*)$')
1182 if string.match(l, Bb.bb_end) then
1183 atend = true
1184 i_bb = i
1185 elseif string.match(l, Bb.bb_pat) then
1186 psp.bb = Bb:from_comment(l)
1187 -- from_comment errors out on failure; no need to check return value
1188 i_bb = i
1189 elseif string.match(l, HRBb.bb_end) then
1190 hr_atend = true
1191 i_hrbb = i
1192 elseif string.match(l, HRBb.bb_pat) then
1193 psp.hrbb = HRBb:from_comment(l)
1194 i_hrbb = i
1195 end -- bbox line
1196 end -- eol/non-eol
1197 pre_lines[i] = l
1198 unscanned = unscanned - string.len(l)
1199 if (i_bb and (i_hrbb or (i_bb<(i-1)))) or unscanned<=0 then
1200 -- condition i_bb<i-1:
1201 -- We do not want to find the hrbb of an included eps.
1202 -- Therefore we stop looking for hrbb if it is not next to bb
1203 -- (with an intervening eol)
1204 -- Note that the header comments are not necessarily terminated
1205 -- with a %%EndComments line; see Adobe DSC spec 5001
1206 break
1207 end -- deciding whether to stop
1208 end -- while
1209 new_offset = offset + string.len(table.concat(pre_lines))
1210 middle_length = ps_length - string.len(table.concat(pre_lines))
1211
1212 if atend or hr_atend then
1213 -- find boundingbox comments, starting from end of postscript
1214 if ps_length>bufsize then
1215 fin:seek('set',offset+ps_length-bufsize)
1216 unscanned = bufsize
1217 slurp = fin:read(unscanned)
1218 else
1219 -- use what is left from old slurp
1220 unscanned = string.len(slurp)
1221 end
1222 j = 1 -- count down from 0
1223 j_bb, j_hrbb, j_end = false, false, false
1224 while unscanned>0 do
1225 j = j - 1
1226 if string.find(slurp,'[\n\r]', string.len(slurp)) then
1227 slurp,l = string.match(slurp, '^(.-)([\n\r]+)$')
1228 -- '-': non-greedy matching
1229 else
1230 slurp,l = string.match(slurp, '^(.-)([^\n\r]+)$')
1231 if string.match(l, Bb.bb_pat) then
1232 psp.bb = Bb:from_comment(l)
1233 j_bb = j
1234 elseif string.match(l, HRBb.bb_pat) then
1235 psp.hrbb = HRBb:from_comment(l)
1236 j_hrbb = j
1237 end -- bbox line
1238 end -- eol/non-eol
1239 post_lines[j] = l
1240 unscanned = unscanned - string.len(l)
1241 if (psp.bb and
1242 (psp.hrbb or not hr_atend or j_bb>(j+1))) or unscanned<=0 then
1243 -- stop looking
1244 j_end = j
1245 break
1246 end -- deciding whether to stop
1247 end -- while
1248 middle_length = middle_length -
1249 string.len(table.concat(post_lines, '', j_end, 0))
1250 end --if atend
1251 fin:close()
1252 -- fix boundingbox lines
1253 if atend and j_bb then
1254 -- pre_lines[i_bb] = post_lines[j_bb]
1255 pre_lines[i_bb] = psp.bb:comment() -- WHY DOESNT THIS WORK ????
1256 post_lines[j_bb] = ''
1257 post_lines[j_bb+1] = ''
1258 end
1259 if hr_atend and j_hrbb then
1260 -- pre_lines[i_hrbb] = post_lines[j_hrbb]
1261 pre_lines[i_hrbb] = psp.hrbb:comment()
1262 post_lines[j_hrbb] = ''
1263 post_lines[j_hrbb+1] = ''
1264 end
1265 -- create cleaned eps file
1266 fout = io.open(psp.path, 'wb')
1267 if not fout then errror('Cannot create new file '..psp.path) end
1268 fout:write(table.concat(pre_lines))
1269 fout:close()
1270 slice_file(self.path, psp.path, middle_length, new_offset, 'ab')
1271 fout = io.open(psp.path, 'ab')
1272 fout:write(table.concat(post_lines, '', j_end, 0))
1273 fout:close()
1274 return psp
1275 end -- eps_clean
1276
1277 -- tight boundingbox (new file & object)
1278
1279 function PsPdf:eps_crop()
1280
1281 -- conversion is not done by an external program, although
1282 -- we invoke Ghostscript with a bbox device for a tight boundingbox.
1283 -- We use both the regular and the hires boundingbox from gs.
1284 -- The eps should already have been cleaned up by eps_clean,
1285 -- and the current boundingbox should not contain negative coordinates,
1286 -- otherwise the bbox output device may give incorrect results.
1287 -- Only the boundingbox in the eps is rewritten.
1288
1289 -- create the PsPdf object which is to be returned
1290
1291 local psp = PsPdf:new('eps')
1292
1293 -- read new bbox from ghostscript output
1294
1295 psp.bb, psp.hrbb = self:bb_from_gs()
1296
1297 -- rewrite header with new boundingboxes
1298
1299 local slurp -- the read buffer
1300 local l -- contains current scanned line; split off from slurp
1301 -- pre_lines: scanned header lines; alternately lines and eols
1302 local pre_lines = {}
1303 -- offset: combined length of scanned header lines
1304 local offset = 0
1305 local ps_length = lfs.attributes(self.path, 'size')
1306 local i, i_bb, i_hrbb
1307
1308 fin = io.open(self.path, 'rb')
1309 if not fin then errror('Cannot read '..self.path) end
1310
1311 -- remaining, unscanned length of input buffer slurp
1312 local unscanned = math.min(ps_length,bufsize)
1313 slurp = fin:read(unscanned)
1314 i, i_bb, i_hrbb = 0, false, false
1315 while unscanned>0 do
1316 i = i+1
1317 if string.find(slurp,'[\n\r]')==1 then
1318 l,slurp = string.match(slurp, '^([\n\r]+)(.*)$')
1319 else
1320 l,slurp = string.match(slurp, '^([^\n\r]+)(.*)$')
1321 if string.match(l, Bb.bb_pat) then
1322 i_bb = i
1323 elseif string.match(l, HRBb.bb_pat) then
1324 i_hrbb = i
1325 end -- bbox line
1326 end -- eol/non-eol
1327 pre_lines[i] = l
1328 unscanned = unscanned - string.len(l)
1329 if (i_bb and (i_hrbb or (i_bb<(i-1)))) or unscanned<=0 then
1330 break
1331 end
1332 end -- while
1333 fin:close()
1334 offset = string.len(table.concat(pre_lines))
1335
1336 if i_hrbb then
1337 pre_lines[i_bb] = psp.bb:comment()
1338 pre_lines[i_hrbb] = psp.hrbb:comment()
1339 else
1340 -- jam both bbox comments into one slot, with an intervening eol.
1341 -- for the sake of conformity, we copy an existing eol.
1342 pre_lines[i_bb] = psp.bb:comment() .. pre_lines[i_bb-1] ..
1343 psp.hrbb:comment()
1344 end
1345
1346 -- write a new eps file
1347
1348 fout = io.open(psp.path, 'wb')
1349 if not fout then errror('Cannot write new file '.. psp.path) end
1350 fout:write(table.concat(pre_lines))
1351 fout:close()
1352 slice_file(self.path, psp.path,
1353 lfs.attributes(self.path,'size') - offset, offset, 'ab')
1354 options.bbox = false
1355 return psp
1356 end -- eps_crop
1357
1358 --[[
1359
1360 most of these conversions involve a single invocation of gs, pdftops or texlua
1361
1362 Each conversion fullfills all options that it can: gray, bbox and
1363 page. gray when converting to pdf, bbox when converting from eps or
1364 from pdf to pdf and page when converting from pdf. It then sets the
1365 fullfilled option(s) to false.
1366
1367 We make sure to do the tight boundingbox before a file format downgrade:
1368 rasterization of the page or graphic frustrates boundingbox calculation.
1369
1370 We like to preserve fonts as fonts. gs does this when generating
1371 pdf, but may fail for fonts such as cid and large truetype when
1372 generating PostScript. In such cases, pdftops may succeed. However,
1373 it seems that if the page contains an element that does not cleanly
1374 convert, pdftops simply rasterizes the entire page, and that this
1375 choice is made per page.
1376
1377 --]]
1378
1379 -- Converting from pdf to pdf using luatex; no grayscaling here
1380
1381 function PsPdf:getpgbox()
1382 if options.page and options.page > self.pages then
1383 errror('PsPdf:getpgbox called with non-existent page '.. options.page)
1384 end
1385 local pg = options.page or 1
1386 local bb, hrbb, pgbox, pdfdoc, ppage
1387 if pdfe then
1388 pdfdoc = pdfe.open(self.path)
1389 if pdfdoc then
1390 ppage = pdfe.getpage(pdfdoc, pg)
1391 if not ppage then errror('did not get page') end
1392 if ppage then
1393 pgbox = pdfe.getbox(ppage, 'MediaBox')
1394 if not pgbox then
1395 pgbox = pdfe.getbox(ppage, 'CropBox')
1396 if not pgbox then
1397 pgbox = pdfe.getbox(ppage, 'TrimBox')
1398 if not pgbox then
1399 errror('No box acquired')
1400 end
1401 end
1402 end
1403 end
1404 end
1405 pdfe.close(pdfdoc)
1406 else
1407 local cat
1408 pdfdoc = epdf.open(self.path)
1409 if pdfdoc then
1410 cat = pdfdoc:getCatalog()
1411 if cat then
1412 ppage = cat:getPage(pg)
1413 if ppage then
1414 pgbox = ppage:getMediaBox()
1415 if not pgbox then
1416 pgbox = ppage:getCropBox()
1417 if not pgbox then
1418 pgbox = ppage:getTrimBox()
1419 end
1420 end
1421 end
1422 end
1423 end
1424 end
1425 -- normalization and further checks, including for non-nil,
1426 -- by HRBb:from_rect, which errors out on failures
1427 if pgbox then
1428 pgbox = HRBb:from_rect(pgbox)
1429 -- this also converts numeric array indices to x1 ... y2 if necessary
1430 else
1431 errror('Cannot get page box from '..self.path..' page '..pg)
1432 end
1433 return pgbox
1434 end -- PsPdf:getpgbox
1435
1436 function PsPdf:pdf_crop()
1437
1438 -- options to be fulfilled: page, boundingbox if possible
1439 -- embeds the pdf with boundingbox parameters into a new (lua)tex document
1440 if options.page and options.page > self.pages then
1441 errror('PsPdf:pdf_crop called with non-existent page '.. options.page)
1442 end
1443 local bb, hrbb, pgbox
1444 pgbox = self:getpgbox()
1445 if options.bbox and pgbox:nonnegative() then
1446 bb, hrbb = self:bb_from_gs()
1447 options.bbox = false
1448 else
1449 hrbb = pgbox
1450 end
1451
1452 -- luatex is on searchpath
1453 local luatex_prog = 'luatex'
1454
1455 -- write TeX file which includes cropped pdf page
1456 -- adapted from Heiko Oberdiek's pdfcrop utility.
1457 -- the table `pieces' will contain the component strings for the tex source
1458 -- first, for texlua <= 0.81
1459 local pieces = {}
1460 if status.luatex_version <= 80 then
1461 pieces[1] = '\\pdfoutput=1\n'
1462 else
1463 pieces[1] = [[
1464 \edef\pdfminorversion {\pdfvariable minorversion}
1465 \edef\pdfcompresslevel {\pdfvariable compresslevel}
1466 \edef\pdfobjcompresslevel {\pdfvariable objcompresslevel}
1467 \edef\pdfdecimaldigits {\pdfvariable decimaldigits}
1468 \edef\pdfhorigin {\pdfvariable horigin}
1469 \edef\pdfvorigin {\pdfvariable vorigin}
1470 \let\pdfpagewidth\pagewidth
1471 \let\pdfpageheight\pageheight
1472 \let\pdfximage\saveimageresource
1473 \let\pdfrefximage\useimageresource
1474 \let\pdflastximage\lastsavedimageresourceindex
1475
1476 \outputmode=1
1477 ]]
1478 end
1479 if self.maver > 1 then
1480 pieces[2] = '\\pdfminorversion=9\n'
1481 else
1482 pieces[2] = '\\pdfminorversion=' .. self.miver .. '\n'
1483 end
1484 if self.maver > 1 or self.miver > 4 then
1485 pieces[3] = [[
1486 \pdfcompresslevel=9
1487 \pdfobjcompresslevel=2
1488 \pdfdecimaldigits=4
1489 ]]
1490 else
1491 pieces[3] = [[
1492 \pdfcompresslevel=9
1493 \pdfobjcompresslevel=0
1494 \pdfdecimaldigits=4
1495 ]]
1496 end
1497 pieces[4] = [[
1498 \def\page #1 [#2 #3 #4 #5]{%
1499 \count0=#1\relax
1500 \setbox0=\hbox{%
1501 \pdfximage page #1 mediabox{]]
1502 pieces[5] = self.path
1503 pieces[6] = [[}%
1504 \pdfrefximage\pdflastximage
1505 }%
1506 \pdfhorigin=#2bp\relax
1507 \pdfvorigin=#3bp\relax
1508 \pagewidth=#4bp\relax
1509 \pageheight=#5bp\relax
1510 \ht0=\pageheight
1511 \shipout\box0\relax
1512 }
1513 ]]
1514 pieces[7] = string.format([[
1515 \page %d [%f %f %f %f]
1516 \csname @@end\endcsname
1517 \end
1518 ]],
1519 options.page or 1, -hrbb.x1, hrbb.y1, hrbb.x2-hrbb.x1, hrbb.y2-hrbb.y1)
1520
1521 local textemp = mktemp('tex') -- this also took care of pdf:
1522 local pdftemp = string.gsub(textemp, 'tex$', 'pdf')
1523 -- if os.type=='windows' then waitasec() end
1524 local f = io.open(textemp, 'w')
1525 -- if os.type=='windows' then waitasec() end
1526 f:write(table.concat(pieces, ''))
1527 f:close()
1528 local cmd, res, psp
1529 -- if os.type=='unix' then
1530 cmd = {luatex_prog, '--safer', '--no-shell-escape', textemp}
1531 log_cmd(cmd)
1532 res = spawnexec(cmd)
1533 if res and res==0 and lfs.attributes(pdftemp, 'size')>0 then
1534 psp = PsPdf:from_path(pdftemp)
1535 options.bbox = false
1536 options.page = false
1537 return psp
1538 else
1539 errror('pdf_crop failed on '..self.path)
1540 end
1541 end
1542
1543 function PsPdf:eps_to_pdf()
1544
1545 -- option to be fulfilled: gray
1546 -- set target and maybe pdf version if applicable
1547 if self.type~='eps' then
1548 errror('PsPdf:eps_to_pdf called for non-eps file '.. self.path)
1549 end
1550 local cmd
1551 maybe_add_version_parameter()
1552 cmd = tab_combine({{gs_prog}, gs_options, pdf_options})
1553 if options.gray then
1554 cmd = tab_combine({cmd, gray_options})
1555 end
1556 table.insert(cmd, '-dEPSCrop') -- uses existing hires bb
1557 local psp = PsPdf:new('pdf')
1558 table.insert(cmd, '-sOutputFile#'..psp.path)
1559 cmd = tab_combine({cmd, pdf_tail_options})
1560 table.insert(cmd, self.path)
1561 log_cmd(cmd)
1562 local res = spawnexec(cmd)
1563 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1564 psp.pages, psp.miver, psp.maver = pdf_props(psp.path)
1565 options.gray = false
1566 return psp
1567 else
1568 errror('eps_to_pdf failed on '..self.path)
1569 end
1570 end -- eps_to_pdf
1571
1572 -- Converting from pdf to pdf with grayscaling and/or page selection
1573 -- or just eliminating negative boundingbox
1574
1575 function PsPdf:pdf_to_pdf()
1576
1577 -- option to be fulfilled: gray, optionally page
1578 -- side effect: makes bbox non-negative.
1579 -- do not call this just for page selection because
1580 -- pdf_crop can do this in a less invasive manner
1581 if self.type~='pdf' then
1582 errror('PsPdf:pdf_to_pdf called for non-pdf file '.. self.path)
1583 end
1584 local cmd
1585 if options.page and options.page > self.pages then
1586 errror('PsPdf:pdf_to_pdf called with non-existent page '.. options.page)
1587 end
1588 cmd = tab_combine({{gs_prog}, gs_options, pdf_options})
1589 if options.gray then
1590 cmd = tab_combine({cmd, gray_options})
1591 end
1592 if options.page then
1593 table.insert(cmd, '-dFirstPage#'..tostring(options.page))
1594 table.insert(cmd, '-dLastPage#'..tostring(options.page))
1595 end
1596 maybe_add_version_parameter()
1597 local psp = PsPdf:new('pdf')
1598 table.insert(cmd, '-sOutputFile#'..psp.path)
1599 cmd = tab_combine({cmd, pdf_tail_options})
1600 table.insert(cmd, self.path)
1601 log_cmd(cmd)
1602 local res = spawnexec(cmd)
1603 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1604 psp.pages, psp.miver, psp.maver = pdf_props(psp.path)
1605 options.gray = false
1606 options.page = false
1607 return psp
1608 else
1609 errror('pdf_to_pdf failed on '..self.path)
1610 end
1611 end -- pdf_to_pdf
1612
1613 function PsPdf:pdf_to_eps()
1614
1615 -- options to be fulfilled: page
1616 local psp = PsPdf:new('eps')
1617 local cmd, res
1618 -- any_to_any already checked the validity and relevance of options.page
1619 if pdftops then
1620 if options.page then
1621 cmd = tab_combine({{pdftops}, ps_options,
1622 {'-f', options.page, '-l', options.page,
1623 '-eps', self.path, psp.path}})
1624 else
1625 cmd = tab_combine({{pdftops}, ps_options,
1626 {'-eps', self.path, psp.path}})
1627 end
1628 log_cmd(cmd)
1629 if os.type=='windows' then
1630 -- suppress console output of 'No display font for...' messages,
1631 -- which are usually harmless and for which I know no easy fix
1632 -- pdftops -q does not do the trick on Windows,
1633 -- and redirection to logfile gives access denied under miktex
1634 res = os.execute(table.concat(cmd, ' ')..' 2>nul')
1635 else
1636 res = spawnexec(cmd)
1637 end
1638 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1639 psp.pages = 1
1640 options.page = false
1641 else
1642 errror('pdf_to_eps failed on '..self.path)
1643 end
1644 -- fix for incorrect DSC header produced by some versions of pdftops:
1645 -- if necessary, change line `% Produced by ...' into `%%Produced by ...'
1646 -- this is usually the second line.
1647 -- otherwise the DSC header would be terminated before the bbox comment.
1648 -- this problem exists with pdftops from TL2011/w32.
1649 local slurp -- input buffer
1650 local fin = io.open(psp.path, 'rb')
1651 if not fin then errror('Cannot read '..psp.path) end
1652
1653 -- remaining, unscanned length of input buffer slurp
1654 local unscanned = math.min(lfs.attributes(psp.path, 'size'),bufsize)
1655 slurp = fin:read(unscanned)
1656 local i, i_bb = 0, false
1657 local needs_fixing = false
1658 local pre_lines = {}
1659 local offset = 0
1660 while unscanned>0 do
1661 i = i+1
1662 if string.find(slurp,'[\n\r]')==1 then
1663 l,slurp = string.match(slurp, '^([\n\r]+)(.*)$')
1664 else
1665 l,slurp = string.match(slurp, '^([^\n\r]+)(.*)$')
1666 if string.match(l, Bb.bb_pat) then
1667 -- bbox line
1668 i_bb = i
1669 elseif string.match(l, '^%%%s') then -- `%' is escape char: doubled
1670 -- %X with X printable would be ok
1671 needs_fixing = true
1672 -- fix rightaway
1673 l = string.gsub(l, '^%%%s', '%%%%') -- same length
1674 end
1675 end -- eol/non-eol
1676 pre_lines[i] = l
1677 unscanned = unscanned - string.len(l)
1678 offset = offset + string.len(l)
1679 if i_bb then break end
1680 end -- while
1681 fin:close()
1682 if needs_fixing then
1683 -- write a new eps file
1684 local newfile = mktemp('eps')
1685 fout = io.open(newfile, 'wb')
1686 if not fout then errror('Cannot write new file '.. newfile) end
1687 fout:write(table.concat(pre_lines))
1688 fout:close()
1689 slice_file(psp.path, newfile,
1690 lfs.attributes(psp.path,'size') - offset, offset, 'ab')
1691 psp.path = newfile
1692 end -- needs_fixing
1693 else -- use ghostscript
1694 local epsdev = gs_epsdevice()
1695 if not epsdev then
1696 errror('Conversion to eps not supported by this ghostscript')
1697 end
1698 cmd = tab_combine({{gs_prog}, gs_options,
1699 {'-sDEVICE#'..epsdev, '-dHaveTrueTypes=true', '-dLanguageLevel#3'}})
1700 if options.gray then
1701 cmd = tab_combine({cmd, gray_options})
1702 end
1703 if options.page then
1704 table.insert(cmd, '-dFirstPage='..options.page)
1705 table.insert(cmd, '-dLastPage='..options.page)
1706 end
1707 table.insert(cmd, '-sOutputFile='..psp.path)
1708 table.insert(cmd, self.path)
1709 log_cmd(cmd)
1710 res = spawnexec(cmd)
1711 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1712 psp.pages = 1
1713 options.page = false
1714 options.gray = false
1715 else
1716 errror('pdf_to_eps failed on '..self.path)
1717 end
1718 end -- use ghostscript
1719 psp:get_bb_simple()
1720 return psp
1721
1722 end -- pdf_to_eps
1723
1724 function PsPdf:ps_to_pdf()
1725
1726 -- options to be fulfilled: gray
1727 if self.type~='ps' then
1728 errror('PsPdf:ps_to_pdf called for non-ps file '.. self.path)
1729 end
1730 local cmd
1731 cmd = tab_combine({{gs_prog}, gs_options, pdf_options})
1732 if options.gray then
1733 cmd = tab_combine({cmd, gray_options})
1734 end
1735 local psp = PsPdf:new('pdf')
1736 table.insert(cmd, '-sOutputFile#'..psp.path)
1737 cmd = tab_combine({cmd, pdf_tail_options})
1738 table.insert(cmd, self.path)
1739 log_cmd(cmd)
1740 local res = spawnexec(cmd)
1741 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1742 psp.pages, psp.miver, psp.maver = pdf_props(psp.path)
1743 options.gray = false
1744 return psp
1745 else
1746 errror('ps_to_pdf failed on '..self.path)
1747 end
1748
1749 end -- PsPdf:ps_to_pdf
1750
1751 function PsPdf:pdf_to_ps()
1752
1753 -- options to be fulfilled: page and, if not using pdftops, also gray
1754 local psp = PsPdf:new('ps')
1755 -- options.page checked by any_to_any
1756 psp.pages = self.pages
1757 local cmd, res
1758 if pdftops then
1759 cmd = tab_combine({{pdftops}, ps_options})
1760 if options.page then
1761 cmd = tab_combine({cmd, {'-f', options.page, '-l', options.page}})
1762 end
1763 cmd = tab_combine({cmd, {'-paper', 'match', self.path, psp.path}})
1764 else -- use ghostscript
1765 cmd = tab_combine({{gs_prog}, gs_options,
1766 {'-sDEVICE#ps2write', '-dHaveTrueTypes=true', '-dLanguageLevel#3'}})
1767 if options.gray then
1768 cmd = tab_combine({cmd, gray_options})
1769 end
1770 if options.page then
1771 cmd = tab_combine({cmd,
1772 {'-dFirstPage#'..options.page, '-dLastPage#'..options.page}})
1773 end
1774 table.insert(cmd, '-sOutputFile#'..psp.path)
1775 table.insert(cmd, self.path)
1776 end
1777 log_cmd(cmd)
1778 if os.type=='windows' and pdftops then
1779 -- suppress console output of 'No display font for...' messages,
1780 -- which are usually harmless and for which I know no easy fix
1781 -- pdftops -q does not do the trick on Windows,
1782 -- and redirection to logfile gives access denied under miktex
1783 res = os.execute(table.concat(cmd, ' ')..' 2>nul')
1784 else
1785 res = spawnexec(cmd)
1786 end
1787 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1788 options.page = false
1789 -- gs will have grayscaled if requested but pdftops will not
1790 if not pdftops then options.gray = false end
1791 return psp
1792 else
1793 errror('pdf_to_ps failed on '..self.path)
1794 end
1795 end -- PsPdf:pdf_to_ps
1796
1797 function PsPdf:ps_to_ps()
1798 -- we do not accept a page option since we do not know
1799 -- which pages are available.
1800 -- if no gray option then there is no point in invoking this function.
1801 local psp = PsPdf:new('ps')
1802 local cmd = tab_combine({{gs_prog}, gs_options,
1803 {'-sDEVICE#ps2write', '-dHaveTrueTypes=true', '-dLanguageLevel#3'}})
1804 if options.gray then
1805 cmd = tab_combine({cmd, gray_options})
1806 end
1807 table.insert(cmd, '-sOutputFile#'..psp.path)
1808 table.insert(cmd, self.path)
1809 log_cmd(cmd)
1810 local res = spawnexec(cmd)
1811 if res and res==0 and lfs.attributes(psp.path, 'size')>0 then
1812 options.gray = false
1813 return psp
1814 else
1815 errror('ps_to_ps failed on '..self.path)
1816 end
1817 end -- PsPdf:ps_to_ps
1818
1819 function any_to_any()
1820
1821 local psp = PsPdf:from_path(infile)
1822
1823 -- sanitize some options
1824
1825 if options.type=='ps' then
1826 options.bbox = false
1827 end
1828
1829 if (options.bbox or options.type=='eps') and not options.page then
1830 options.page = 1
1831 end
1832
1833 if psp.type=='pdf' then
1834 if options.page then
1835 local pgs = pdf_props(infile)
1836 if pgs<options.page then
1837 errror(infile..' has only '..pgs..' page(s).')
1838 elseif pgs==1 then
1839 options.page = false
1840 end
1841 end
1842 elseif psp.type=='eps' then
1843 options.page = false
1844 end
1845 -- psp.type=='ps': pages not yet known but maybe not needed
1846
1847 local do_something = false
1848 if psp.type=='eps' then
1849 do_something = true -- do at least cleanup
1850 elseif psp.type~=options.type then
1851 do_something = true
1852 elseif options.page then
1853 do_something = true
1854 elseif options.bbox then
1855 do_something = true
1856 elseif options.gray then
1857 do_something = true
1858 elseif options.type=='pdf' then
1859 if psp:to_downgrade() then
1860 do_something = true
1861 elseif settings.pdf_target and settings.pdf_target~=default then
1862 do_something = true
1863 end
1864 end
1865 if not do_something then
1866 if infile~=outfile then
1867 slice_file(infile, outfile)
1868 end
1869 return true
1870 end
1871
1872 -- `distiller' settings
1873 -- these depend on whether final output is pdf
1874 if options.type=='pdf' then
1875 if settings.pdf_target and (settings.pdf_target~='default') then
1876 table.insert(pdf_options, '-dPDFSETTINGS#/'..settings.pdf_target)
1877 end
1878 if not is_miktex then
1879 -- options below cause trouble with unpacked cmd table
1880 if settings.pdf_target~='screen' and settings.pdf_target~='ebook' then
1881 pdf_tail_options = {
1882 '-c', '<</NeverEmbed [ ] >> setdistillerparams', '-f'}
1883 end
1884 end
1885 end
1886
1887 --[[ Actual conversions
1888 each single-step conversion takes care of options it can handle
1889 and sets those options to false.
1890 Cropping a pdf is best be done before converting to postscript or
1891 a low (<1.4) pdf version.
1892
1893 all invocations of external programs work on temporary files
1894 in the then-current temporary directory, with a simple generated
1895 filename. So no need to quote names of input- or output filenames.
1896 --]]
1897
1898 local newfile
1899
1900 if psp.type=='eps' or psp.type=='epsPreview' then
1901 -- As a side effect of eps_clean, the modified or unmodified source file
1902 -- is copied to our temp subdirectory.
1903 -- We always create a new file.
1904 psp = psp:eps_clean()
1905 if options.bbox and psp.bb:nonnegative() then
1906 psp = psp:eps_crop()
1907 end
1908 if options.type=='eps' then
1909 if options.gray or options.bbox then
1910 -- bbox: eps_crop was apparently not applicable: pdf roundtrip
1911 psp = psp:eps_to_pdf()
1912 if options.bbox then
1913 psp = psp:pdf_crop()
1914 end
1915 psp = psp:pdf_to_eps()
1916 end
1917 elseif options.type=='pdf' then
1918 psp = psp:eps_to_pdf()
1919 if options.bbox then
1920 psp = psp:pdf_crop()
1921 end
1922 if psp:to_downgrade() then
1923 maybe_add_version_parameter()
1924 psp = psp:pdf_to_pdf()
1925 end
1926 elseif options.type=='ps' then
1927 -- often, the eps file is fine as a postscript file.
1928 -- however, it may lack a showpage operator, or have a weird
1929 -- boundingbox. converting back-and-forth to pdf solves both problems.
1930 -- eps_to_pdf will take care of grayscaling
1931 -- a tight boundingbox option is not supported for ps output.
1932 psp = psp:eps_to_pdf():pdf_to_ps()
1933 end
1934 slice_file(psp.path, outfile)
1935 return true
1936
1937 elseif psp.type=='ps' then
1938
1939 -- preliminary:
1940 -- copy infile to a file in the temp directory, needed for gs -dSAFER
1941 newfile = mktemp(psp.type)
1942 slice_file(psp.path, newfile)
1943 psp.path = newfile
1944
1945 if options.type=='ps' and not options.page then
1946 psp = psp:ps_to_ps()
1947 slice_file(psp.path, outfile)
1948 return true
1949 end
1950
1951 -- remaining options require initial conversion to pdf
1952 psp = psp:ps_to_pdf()
1953 -- AFAIK, all high-level ps constructs are covered by any pdf version
1954 -- so this option should not cause unnecessary loss of structure
1955 maybe_add_version_parameter()
1956
1957 if options.page and options.page>1 then
1958 -- could not check page option before
1959 local pgs = pdf_props(psp.path)
1960 if pgs<options.page then
1961 errror(infile..' has only '..pgs..' page(s).')
1962 elseif pgs==1 then
1963 options.page = false
1964 end
1965 end
1966
1967 -- actual conversion
1968 if options.type=='eps' then
1969 if options.bbox then
1970 psp = psp:pdf_crop()
1971 end
1972 psp = psp:pdf_to_eps()
1973 elseif options.type=='pdf' then
1974 if options.bbox or options.page then
1975 psp = psp:pdf_crop()
1976 -- else no action needed
1977 end
1978 elseif options.type=='ps' then
1979 psp = psp:pdf_to_ps()
1980 end -- pdf => ps
1981 slice_file(psp.path, outfile)
1982 return true
1983
1984 elseif psp.type=='pdf' then
1985
1986 if options.type=='pdf' and settings.pdf_target=='default' and
1987 not options.gray and not options.bbox and not options.page and
1988 not psp:to_downgrade() then
1989 if infile~=outfile then
1990 slice_file(infile, outfile)
1991 end
1992 return true
1993 end
1994
1995 -- preliminary:
1996 -- copy infile to a file in the temp directory, needed for gs -dSAFER
1997 newfile = mktemp(psp.type)
1998 slice_file(psp.path, newfile)
1999 psp = PsPdf:from_path(newfile)
2000 local pgbox
2001
2002 -- actual conversion
2003 if options.type=='eps' then
2004 if options.bbox then
2005 pgbox = psp:getpgbox() -- page n. available from options table
2006 if not pgbox:nonnegative() or options.gray then
2007 -- fix in extra pdf-to-pdf step
2008 psp = psp:pdf_to_pdf()
2009 end
2010 -- we want to calculate a tight boundingbox before conversion to eps,
2011 -- because this conversion may cause rasterization and baffle
2012 -- gs' boundingbox calculations
2013 psp = psp:pdf_crop()
2014 elseif options.gray and pdftops then
2015 psp = psp:pdf_to_pdf()
2016 end
2017 psp = psp:pdf_to_eps()
2018 elseif options.type=='pdf' then
2019 -- pdf_crop can take care of bbox and page,
2020 -- but not of gray and not of some pdf options
2021 if options.bbox then
2022 pgbox = psp:getpgbox()
2023 if not pgbox:nonnegative() then
2024 -- pdf_to_pdf fixes negative bbox parameters
2025 -- and also takes care of page and gray
2026 psp = psp:pdf_to_pdf()
2027 end
2028 psp = psp:pdf_crop()
2029 end
2030 need_gs = false
2031 if psp:to_downgrade() then
2032 need_gs = true
2033 maybe_add_version_parameter()
2034 end
2035 if settings.pdf_target~='default' then
2036 need_gs = true
2037 end
2038 if options.gray then
2039 need_gs = true
2040 end
2041 if (not need_gs) and options.page then
2042 psp = psp:pdf_crop()
2043 -- less invasive than page selection by gs
2044 end
2045 if need_gs then
2046 psp = psp:pdf_to_pdf() -- will handle page selection too
2047 end
2048 elseif options.type=='ps' then
2049 if options.gray and pdftops then
2050 psp = psp:pdf_to_pdf():pdf_to_ps()
2051 else
2052 psp = psp:pdf_to_ps()
2053 end
2054 end -- pdf => ps
2055 slice_file(psp.path, outfile)
2056 return true
2057 end
2058 end -- any_to_any
2059
2060 -- system-dependent initialization -----------------------------------
2061
2062 -- current directory, at program start
2063 cwd = lfs.currentdir()
2064 if os.type == 'windows' then cwd = string.gsub(cwd, '\\', '/') end
2065
2066 -- child searchpath initially set to parent searchpath
2067 -- childpath = os.getenv('PATH')
2068
2069 -- prepend (lua)tex directory to searchpath, if not already there
2070 maybe_add_path(os.selfdir, false)
2071
2072 -- Windows: miktex, TL or neither. is_miktex, is_tl_w32
2073 -- no support yet for separate ghostscript
2074 is_miktex = false
2075 is_tl_w32 = false
2076
2077 if os.type == 'windows' then
2078 if string.find (string.lower(kpse.version()), 'miktex') then
2079 is_miktex = true
2080 else
2081 local rt = string.gsub(os.selfdir,'[\\/][^\\/]+[\\/][^\\/]+$', '')
2082 if not rt then
2083 errror('Unrecognized TeX directory structure', 0)
2084 elseif lfs.isfile(rt..'/release-texlive.txt') then
2085 --[[
2086 -- TL version is easy to determine but is not needed
2087 local fin = io:open(rt..'release-texlive.txt', 'r')
2088 if fin then
2089 local l = fin:read('*line')
2090 tl_ver = string.match(l, 'version%s+(%d+)$')
2091 if tl_ver then tl_ver = tonumber(tl_ver) end
2092 end -- if fin
2093 --]]
2094 is_tl_w32 = true
2095 else
2096 errror('Not MikTeX and no file ' .. rt ..
2097 '/release-texlive.txt; TeX installation not supported.', 0)
2098 end -- if isfile
2099 end -- if not miktex
2100 end -- if windows
2101
2102 -- without Ghostscript we are dead in the water.
2103 gs_prog = false
2104 do
2105 local rt=''
2106 if os.type == 'unix' then
2107 if find_on_path('gs') then
2108 gs_prog = 'gs'
2109 else
2110 error('No ghostscript on searchpath!', 0)
2111 end
2112 elseif is_miktex then
2113 gs_prog = 'mgs.exe'
2114 -- neither MiKTeX's nor TL's ghostscript need GS_LIB to be set
2115 elseif is_tl_w32 then
2116 -- windows/TeX Live
2117 -- grandparent of texlua.exe directory .. ...
2118 -- rt = string.gsub(os.selfdir,'[\\/][^\\/]+[\\/][^\\/]+$', '')
2119 -- ..'/tlpkg/tlgs'
2120 -- maybe_add_path(rt..'/bin', false)
2121 -- -- gs_prog = 'gswin32c.exe'
2122 -- ---[[ problems with (at least) grayscaling
2123 gs_prog = 'rungs.exe'
2124 --]]
2125 else
2126 errror('Only TeX Live and MikTeX supported!', 0)
2127 end
2128 end -- do
2129
2130 -- directory for configuration and log
2131 epsdir = ''
2132 if os.type == 'windows' then
2133 epsdir = fw(os.getenv('APPDATA')) .. '/epspdf'
2134 else
2135 epsdir = os.getenv('HOME')..'/.epspdf'
2136 end
2137 rcfile = epsdir .. '/config'
2138 logfile = epsdir .. '/epspdf.log'
2139
2140 -- create epsdir if necessary
2141 if lfs.isfile(epsdir) then
2142 error('Cannot continue; epspdf directory ' .. epsdir .. ' is a file')
2143 elseif not lfs.isdir(epsdir) then
2144 if not lfs.mkdir(epsdir) then
2145 error('Failed to create epspdf directory ' .. epsdir)
2146 end
2147 end
2148
2149 -- start logging ---------------------------------
2150
2151 -- log rotate if logfile too big
2152 if lfs.attributes(logfile) and lfs.attributes(logfile).size > 100000 then
2153 local oldlog = logfile .. '.old'
2154 if lfs.attributes(oldlog) then
2155 if os.remove(oldlog) then os.rename(logfile,oldlog) end
2156 elseif lfs.attributes(logfile) then do
2157 -- separate epsdir runs with empty lines
2158 print_log('\n\nNew run')
2159 end end -- do elseif
2160 end -- if lfs...logfile
2161
2162 write_log('epspdf '..table.concat(arg, ' '))
2163
2164 --[[
2165
2166 settings, initial values
2167
2168 priority, from low to high:
2169
2170 - built-in defaults
2171 - settings read from and written to the configuration file
2172 - command-line options, defined in the opts table
2173
2174 The options- and settings tables are initialized from built-in
2175 defaults. We go for false rather than undefined, because this
2176 results in an actual settings- or options entry.
2177
2178 Command-line options are copied to either options or settings.
2179 We ignore illegal settings in the config file.
2180
2181 --]]
2182
2183 pdf_targets = {'screen', 'ebook', 'printer', 'prepress', 'default'}
2184 pdf_versions = {'1.2', '1.3', '1.4', '1.5', '1.6', '1.7', 'default'}
2185 -- ghostscript will substitute higher versions with
2186 -- the highest-supported version
2187
2188 settings = {}
2189 descriptions = {}
2190
2191 settings.pdf_target = 'default'
2192 descriptions.pdf_target = 'One of ' .. join(pdf_targets, ', ', ' or ')
2193
2194 settings.pdf_version = 'default'
2195 descriptions.pdf_version = 'One of ' .. join(pdf_versions, ', ', ' or ')
2196
2197 settings.use_pdftops = true
2198 descriptions.use_pdftops = 'Use pdftops if available'
2199
2200 -- epspdf stores ps- and pdf viewer settings on behalf of the gui interface
2201 -- but does not use them itself.
2202 -- They will not be used at all under macos or windows.
2203
2204 settings.ps_viewer = false
2205 descriptions.ps_viewer =
2206 'Epspdftk: viewer for PostScript files; not used on Windows or Mac OS'
2207
2208 settings.pdf_viewer = false
2209 descriptions.pdf_viewer =
2210 'Epspdftk: viewer for pdf files; not used on Windows or Mac OS'
2211
2212 -- default_dir, which is used on all platforms, is only for the gui.
2213
2214 if os.type == 'windows' then
2215 settings.default_dir =
2216 string.gsub(os.getenv('USERPROFILE'), '\\', '/')
2217 else
2218 settings.default_dir = os.getenv('HOME')
2219 end
2220 descriptions.default_dir =
2221 'Epspdftk: initial directory; ignored by epspdf itself'
2222
2223 -- options -------------------------------------
2224
2225 -- besides settings, which can be saved, we also use options which are not.
2226 -- these are mostly conversion options.
2227
2228 options = {}
2229 options.page = false
2230 options.gray = false
2231 options.bbox = false
2232 options.debug = false
2233 options.type = false -- implied via output filename on command line
2234
2235 -- command-line fragments for conversions --------------------
2236
2237 -- We could make these `class attributes' for PsPdf but to what purpose?
2238 -- For Windows shell commands, we need to substitute `#' for `='
2239 -- when invoking Ghostscript. For simplicity, we do this across the board.
2240 -- -P- : do not look first in current directory
2241
2242 gs_options = {'-q', '-dNOPAUSE', '-dBATCH', '-P-', '-dSAFER'}
2243
2244 -- may add custom options later
2245
2246 pdf_options = {'-sDEVICE#pdfwrite'} -- '-dUseCIEColor' causes serious slowdown
2247 -- options for final conversion to pdf;
2248 -- will be completed after reading settings and options
2249 -- -f ensures that the input filename is not added to a -c string
2250 pdf_tail_options = {'-f'}
2251 gray_options = {'-dProcessColorModel#/DeviceGray',
2252 '-sColorConversionStrategy#Gray'}
2253
2254 pdftops = false
2255 -- gets a value only if we are going to use pdftops
2256
2257 ps_options = {'-level3'}
2258
2259 -- `main program' inside scope-creating block ----------------------
2260
2261 do -- main program
2262
2263 local in_dir = false -- directory of infile
2264 local out_dir = false -- directory of outfile
2265
2266 do -- Handle settings and command-line inside nested scope --------------
2267
2268 read_settings(rcfile)
2269
2270 local opts = {}
2271
2272 opts.page = {
2273 type = 'string', val = nil,
2274 forms = {'-p', '--page', '--pagenumber'},
2275 placeholder = 'PNUM',
2276 negforms = nil,
2277 help = 'Page number; must be a positive integer'
2278 }
2279
2280 opts.gray = {
2281 type = 'boolean', val = nil,
2282 forms = {'-g', '--grey', '--gray', '-G', '--GREY', '--GRAY'},
2283 negforms = nil,
2284 help = 'Convert to grayscale'
2285 }
2286
2287 opts.bbox = {
2288 type = 'boolean', val = nil,
2289 forms = {'-b', '--bbox', '--BoundingBox'},
2290 negforms = nil,
2291 help = 'Compute tight boundingbox'
2292 }
2293
2294 ---[[ ignored; included for backward compatibility
2295 opts.use_hires_bb = {
2296 type = 'boolean', val = nil,
2297 forms = {'-r', '--hires'},
2298 negforms = {'-n', '--no-hires'},
2299 }
2300
2301 opts.custom = {
2302 type = 'string', val = nil,
2303 forms = {'-C', '--custom', '-P', '--psoptions'},
2304 negforms = nil
2305 }
2306 --]]
2307
2308 opts.pdf_target = {
2309 type = 'string', val = nil,
2310 forms = {'-T', '--target'},
2311 placeholder = 'TARGET',
2312 negforms = nil,
2313 help = descriptions.pdf_target
2314 }
2315 opts.pdf_version = {
2316 type = 'string', val = nil,
2317 forms = {'-N', '--pdfversion'},
2318 placeholder = 'VERSION',
2319 negforms = nil,
2320 help = descriptions.pdf_version
2321 }
2322
2323 opts.use_pdftops = {
2324 type = 'boolean', val = nil,
2325 forms = {'-U'},
2326 negforms = {'-I'},
2327 help = descriptions.use_pdftops
2328 }
2329
2330 opts.info = {
2331 type = 'boolean', val = nil,
2332 forms = {'-i', '--info'},
2333 negforms = nil,
2334 help = 'Info: display detected filetype and exit'
2335 }
2336
2337 opts.help = {
2338 type = 'boolean', val = nil,
2339 forms = {'-h', '--help'},
2340 negforms = nil,
2341 help = 'Display this help message and exit'
2342 }
2343
2344 opts.version = {
2345 type = 'boolean', val = nil,
2346 forms = {'-v', '--version'},
2347 negforms = nil,
2348 help = 'Display version info and exit'
2349 }
2350
2351 opts.save = {
2352 type = 'boolean', val = nil,
2353 forms = {'-s', '--save'},
2354 negforms = nil,
2355 help = 'Save some settings to configuration file'
2356 }
2357
2358 opts.debug = {
2359 type = 'boolean', val = nil,
2360 forms = {'-d'},
2361 negforms = nil,
2362 help = 'Debug: do not remove temp files'
2363 }
2364
2365 opts.gui = {
2366 type = 'string', val = nil,
2367 forms = {'--gui'},
2368 negforms = nil,
2369 help = nil -- reserved for use by epspdftk
2370 }
2371
2372 -- a couple of functions only available during command-line parsing
2373
2374 local function show_version ()
2375 print('Epspdf version 0.6.5.1\nCopyright (c) 2006-2023 Siep Kroonenberg')
2376 end
2377
2378 local function help (mess) -- requires opts array
2379 if mess then
2380 print(mess..eol)
2381 end
2382 show_version()
2383 -- below, string.gsub unindents its long-string parameter.
2384 -- string.format removes the second return value of string.gsub.
2385 print( -- string.format('%s',
2386 string.gsub([[
2387
2388 Convert between [e]ps and pdf formats
2389 Usage: epspdf[.tlu] [options] infile [outfile]
2390 Default for outfile is file.pdf if infile is file.eps or file.ps
2391 Default for outfile is file.eps if infile is file.pdf
2392 ]], '([\r\n]+) ', '%1')) --)
2393
2394 -- need to enforce an ordering, otherwise we could have used pairs(opts)
2395 -- omitted below: no-op options
2396 -- one line where possible
2397 local indent_n = 12
2398 local intent_sp = string.rep(' ', indent_n)
2399 local indent_fmt = '%-' .. tostring(indent_n) .. 's'
2400 for _, o in ipairs({'page', 'gray', 'bbox', 'pdf_target', 'pdf_version',
2401 'use_pdftops', 'save', 'info', 'debug', 'version', 'help'}) do
2402 local v = opts[o]
2403 if v and v.help then
2404 local synt = join(v.forms, ', ')
2405 if v.type ~= 'boolean' then synt = synt .. ' ' .. v.placeholder end
2406 if string.len(synt)<indent_n then
2407 print(string.format(indent_fmt, synt) .. v.help)
2408 else
2409 print(synt)
2410 print(intent_sp .. v.help)
2411 end
2412 if v.negforms then
2413 local neghelp = 'Reverses the above'
2414 synt = join(v.negforms, ', ')
2415 if string.len(synt)<indent_n then
2416 print(string.format(indent_fmt, synt) .. neghelp)
2417 else
2418 print(synt)
2419 print(intent_sp .. neghelp)
2420 end
2421 end
2422 end
2423 end -- for
2424 if mess then os.exit(1) else os.exit() end
2425 end -- help
2426
2427 if #arg < 1 then help('No parameters') end
2428
2429 -- command-line parsing
2430
2431 -- -r="tata tata" is parsed by [tex]lua as a single argument
2432 -- lua/linux retains the quotes,
2433 -- lua/windows strips them.
2434 -- texlua strips them, both on unix and on windows.
2435
2436 local i=1
2437 while i<=#arg and string.sub(arg[i],1,1)=='-' do
2438 local parsed = false
2439 local kk, vv = string.match(arg[i],'([^=]+)=(.*)$')
2440 if kk==nil then
2441 kk = arg[i] -- also vv==nil
2442 else
2443 vv = strip_outer_spaces(vv)
2444 end
2445 for p, o in pairs(opts) do
2446 if in_list(kk, o.forms) or in_list(kk, o.negforms) then
2447 parsed = true
2448 if o.type == 'boolean' then
2449 if vv then help(kk..' should not have a parameter.') end
2450 if in_list(kk, o.forms) then
2451 o.val = true
2452 else
2453 o.val = false
2454 end
2455 elseif vv then
2456 o.val = vv
2457 else
2458 i = i + 1
2459 if i>#arg then
2460 help('Missing parameter to '..kk)
2461 end
2462 o.val = strip_outer_spaces(arg[i])
2463 end -- testing for o.type or vv
2464 break -- for
2465 end -- if in_list
2466 end -- for
2467 if not parsed then help('illegal parameter '..kk) end
2468 i = i + 1
2469 end -- while
2470
2471 -- check and interpret opts.
2472 -- Copy to either settings or to options table.
2473 -- at syntax error, abort via help function.
2474
2475 -- page
2476
2477 if opts.page.val then
2478 local pnum = tonumber(opts.page.val)
2479 if pnum<=0 or math.floor(pnum) ~= pnum then
2480 help(opts.page.val..' not a positive integer')
2481 else
2482 options.page = pnum
2483 end
2484 end
2485
2486 -- grayscaling
2487
2488 if opts.gray.val then
2489 options.gray = true
2490 else
2491 options.gray = false
2492 end
2493
2494 -- boundingbox
2495
2496 if opts.bbox.val then
2497 options.bbox = true
2498 else
2499 options.bbox = false
2500 end
2501
2502 --[[
2503 -- using hires boundingbox
2504
2505 if opts.use_hires_bb.val~=nil then
2506 settings.use_hires_bb = opts.use_hires_bb.val
2507 end
2508 --]]
2509
2510 -- using pdftops
2511
2512 if opts.use_pdftops.val~=nil then
2513 settings.use_pdftops = opts.use_pdftops.val
2514 end
2515
2516 -- pdf target use
2517
2518 if opts.pdf_target.val~=nil then
2519 if in_list(opts.pdf_target.val, pdf_targets) then
2520 settings.pdf_target = opts.pdf_target.val
2521 else
2522 help('Illegal value '..opts.pdf_target.val..' for pdf_target')
2523 end
2524 end
2525
2526 -- pdf version
2527
2528 if opts.pdf_version.val~=nil then
2529 if in_list(opts.pdf_version.val, pdf_versions) then
2530 settings.pdf_version = opts.pdf_version.val
2531 else
2532 help('Illegal value '..opts.pdf_version.val..' for pdf_version')
2533 end
2534 end
2535
2536 -- pdftops should be on the path
2537 if settings.use_pdftops then
2538 if os.type=='windows' then
2539 pdftops = find_on_path('pdftops.exe')
2540 else
2541 pdftops = find_on_path('pdftops')
2542 end
2543 end
2544
2545 -- other options
2546
2547 if opts.save.val then
2548 write_settings(rcfile)
2549 end
2550
2551 if opts.debug.val then
2552 options.debug = true
2553 end
2554
2555 if opts.help.val then
2556 help()
2557 end
2558
2559 -- opts.info.val: do later; need to get infile first
2560
2561 if opts.version.val then
2562 show_version()
2563 os.exit()
2564 end
2565
2566 if opts.gui.val then
2567 gui(opts.gui.val)
2568 end
2569
2570 -- now we need 1 or 2 filenames, unless the user really only
2571 -- wanted to save options without further action.
2572
2573 if i>#arg then
2574 if opts.save.val then os.exit() else help('No filenames') end
2575 end
2576
2577 infile = arg[i]
2578 outfile = false
2579 if i<#arg then
2580 outfile = arg[i+1]
2581 end
2582 if (#arg>i and opts.info.val) or (#arg>i+1) then
2583 help('Surplus non-option parameters')
2584 end
2585
2586 if not outfile and not opts.info.val then
2587 -- derive outfile from infile: [e]ps => pdf, pdf => eps
2588 if intype=='pdf' then
2589 outfile = string.gsub(infile,'%.[^%.]*$','eps')
2590 else
2591 outfile = string.gsub(infile,'%.[^%.]*$','.pdf')
2592 end
2593 end
2594
2595 -- one final quick option
2596 if opts.info.val then
2597 info()
2598 end
2599
2600 end -- do (decoding command-line)
2601
2602 --[[
2603
2604 Once it becomes clear that real work needs to be done,
2605 we shall create a temp directory.
2606
2607 because of gs -dSAFER restrictions, infile must be in (a
2608 subdirectory of) the directory of the output file, e.g. in the
2609 temp directory. So we copy infile to the temp directory.
2610
2611 --]]
2612
2613 if not lfs.isfile(infile) or lfs.attributes(infile, 'size')==0 then
2614 errror(infile..' does not exist or is empty.')
2615 end
2616 infile, in_dir = absolute_path(infile)
2617 outfile, out_dir = absolute_path(outfile)
2618 if not out_dir then
2619 errror('Invalid output directory for '.. outfile)
2620 end
2621
2622 -- directory for temporary files
2623
2624 -- previously, we used a subdirectory of the target directory.
2625 -- however, since under windows cleanup may fail, we now try to use
2626 -- a directory under a dedicated temp directory, which has a better chance
2627 -- of getting cleaned up by the system.
2628
2629 for i, d in pairs({system_tempdir(), out_dir}) do
2630 if not lfs.chdir(d) then
2631 io.stdout:write('cannot cd into '..d..'\n')
2632 goto continue
2633 end
2634 tempdir = os.tmpdir()
2635 if not tempdir then goto continue end
2636 break
2637 ::continue::
2638 end
2639 if not tempdir then
2640 errror('Cannot create directory for temporary files')
2641 end
2642 lfs.chdir(tempdir)
2643
2644 -- determine filetype from first few bytes of file
2645 intype = identify(infile)
2646
2647 -- remaining cases: want a real conversion
2648 if not intype then
2649 errror(infile..' has an unsupported filetype')
2650 end
2651
2652 -- valid output filetype?
2653 options.type = string.match(outfile, '.*%.([^%.]+)$')
2654 if not options.type or (options.type~='ps' and
2655 options.type~='eps' and options.type~='pdf') then
2656 errror('Output file '..outfile..
2657 ' should have extension .eps, .ps or .pdf')
2658 end
2659
2660 if outfile==infile then
2661 slice_file(infile, infile..'.backup')
2662 -- copy, not move, since outfile may be infile if there was nothing to do
2663 end
2664
2665 result = any_to_any(infile, outfile)
2666 if not lfs.isfile(outfile) or lfs.attributes(outfile, 'size')==0 then
2667 errror('Failed to generate '..outfile)
2668 end
2669
2670 if not options.debug then
2671 cleantemp()
2672 end
2673 end