summaryrefslogtreecommitdiff
path: root/Master/texmf-dist/scripts/pdfbook2/pdfbook2
blob: a288df70fd5d1da2ce41f8a1b19f7a50051ec856 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
#!/usr/bin/env python
""" pdfbook2 - transform pdf files to booklets
                   
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <http://www.gnu.org/licenses/>.
    """


import sys
import subprocess
import os
from optparse import OptionParser, OptionGroup, HelpFormatter
import shutil


#===============================================================================
# Create booklet for file $name
#===============================================================================

def booklify( name, opts ):
    #------------------------------------------------------ Check if file exists
    print "\nProcessing", name
    if not os.path.isfile( name ):
        print "SKIP: file not found."
        return
    print "Getting bounds...",
    sys.stdout.flush()

    #---------------------------------------------------------- useful constants
    bboxName = "%%HiResBoundingBox:"
    tmpFile = ".crop-tmp.pdf"

    #------------------------------------------------- find min/max bounding box
    if opts.crop:
        p = subprocess.Popen( ["pdfcrop", "--verbose",
                                "--resolution", repr( opts.resolution ),
                               name, tmpFile],
                             stdout = subprocess.PIPE,
                             stderr = subprocess.PIPE )
        p.wait()
        out, err = p.communicate()
        if len( err ) != 0:
            print err
            print "\n\nABORT: Problem getting bounds"
            sys.exit( 1 )
        lines = out.splitlines()
        bboxes = [s[len( bboxName ) + 1:] for s in lines if s.startswith( bboxName )]
        bounds = [[float( x ) for x in bbox.split()] for bbox in bboxes ]
        minLOdd = min( [bound[0] for bound in bounds[::2] ] )
        maxROdd = max( [bound[2] for bound in bounds[::2] ] )
        minLEven = min( [bound[0] for bound in bounds[1::2] ] )
        maxREven = max( [bound[2] for bound in bounds[1::2] ] )
        minT = min( [bound[1] for bound in bounds ] )
        maxB = max( [bound[3] for bound in bounds ] )

        widthOdd = maxROdd - minLOdd
        widthEven = maxREven - minLEven
        maxWidth = max( widthOdd, widthEven )
        minLOdd -= maxWidth - widthOdd
        maxREven += maxWidth - widthEven

        print "done"
        sys.stdout.flush()

    #--------------------------------------------- crop file to area of interest
        print "cropping...",
        sys.stdout.flush()
        p = subprocess.Popen( ["pdfcrop",
                               "--bbox-odd", "{L} {T} {R} {B}".format( L = minLOdd - opts.innerMargin / 2,
                                                                   T = minT - opts.topMargin,
                                                                   R = maxROdd + opts.outerMargin,
                                                                   B = maxB + opts.outerMargin ),
                               "--bbox-even", "{L} {T} {R} {B}".format( L = minLEven - opts.outerMargin,
                                                                   T = minT - opts.topMargin,
                                                                   R = maxREven + opts.innerMargin / 2,
                                                                   B = maxB + opts.outerMargin ),
                               "--resolution", repr( opts.resolution ),
                               name,
                               tmpFile],
                             stdout = subprocess.PIPE,
                             stderr = subprocess.PIPE )
        p.wait()
        out, err = p.communicate()
        if len( err ) != 0:
            print err
            print "\n\nABORT: Problem with cropping"
            sys.exit( 1 )
        print "done"
        sys.stdout.flush()
    else:
        shutil.copy( name, tmpFile )

    #-------------------------------------------------------- create the booklet
    print "create booklet...",
    sys.stdout.flush()
    pdfJamCallList = [ "pdfjam",
                       "--booklet", "true",
                       "--landscape",
                       "--suffix", "book",
                       "--signature", repr( opts.signature ),
                       tmpFile ]

    # add option --paper to call
    if opts.paper is not None:
        pdfJamCallList.append( "--paper" )
        pdfJamCallList.append( opts.paper )

    # add option --short-edge to call
    if opts.shortedge:
        # check if everyshi.sty exists as texlive recommends
        p = subprocess.Popen( ["kpsewhich", "everyshi.sty"],
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE )
        p.wait()
        out, err = p.communicate()
        if len( out ) == 0:
            print "\n\nABORT: The everyshi.sty latex package is needed for short-edge."
            sys.exit( 1 )
        else:
            pdfJamCallList.append( "--preamble" )
            pdfJamCallList.append( r"\usepackage{everyshi}\makeatletter\EveryShipout{\ifodd\c@page\pdfpageattr{/Rotate 180}\fi}\makeatother" )

    # run call to pdfJam to make booklet
    p = subprocess.Popen( pdfJamCallList,
                         stdout = subprocess.PIPE,
                         stderr = subprocess.PIPE )
    p.wait()

    #-------------------------------------------- move file and remove temp file
    os.rename( tmpFile[:-4] + "-book.pdf", name[:-4] + "-book.pdf" )
    os.remove( tmpFile )
    print "done"
    sys.stdout.flush()


#===============================================================================
# Help formatter
#===============================================================================

class MyHelpFormatter ( HelpFormatter ):
    """Format help with indented section bodies.
    """

    def __init__( self,
                 indent_increment = 4,
                 max_help_position = 16,
                 width = None,
                 short_first = 0 ):
        HelpFormatter.__init__( 
            self, indent_increment, max_help_position, width, short_first )

    def format_usage( self, usage ):
        return ( "USAGE\n\n%*s%s\n" ) % ( self.indent_increment, "", usage )

    def format_heading( self, heading ):
        return "%*s%s\n\n" % ( self.current_indent, "", heading.upper() )


#===============================================================================
# main programm
#===============================================================================

if __name__ == "__main__":
    #------------------------------------------------------------ useful strings
    usageString = "Usage: %prog [options] file1 [file2 ...]"
    versionString = """
    %prog v1.2
    (c) 2015 Johannes Neumann (http://www.neumannjo.de)
    licensed under GPLv3 (http://www.gnu.org/licenses/gpl-3.0)
    based on pdfbook by David Firth with help from Marco Pessotto\n"""
    defaultString = " (default: %default)"

    #------------------------------------------------- create commandline parser
    parser = OptionParser( usage = usageString, version = versionString,
                           formatter = MyHelpFormatter( indent_increment = 4 ) )

    generalGroup = OptionGroup( parser, "General" )
    generalGroup.add_option( "-p", "--paper", dest = "paper", type = "str", action = "store",
                       metavar = "STR",
                       help = "Format of the output paper dimensions as latex keyword (e.g. a4paper, letterpaper, legalpaper, ...)" )
    generalGroup.add_option( "-s", "--short-edge", dest = "shortedge", action = "store_true",
                       help = "Format the booklet for short-edge double-sided printing",
                       default = False )
    generalGroup.add_option( "-n", "--no-crop", dest = "crop", action = "store_false",
                       help = "Prevent the cropping to the content area",
                       default = True )
    parser.add_option_group( generalGroup )

    marginGroup = OptionGroup( parser, "Margins" )
    marginGroup.add_option( "-o", "--outer-margin", type = "int", default = 40,
                       dest = "outerMargin", action = "store", metavar = "INT",
                       help = "Defines the outer margin in the booklet" + defaultString )
    marginGroup.add_option( "-i", "--inner-margin", type = "int", default = 150,
                       dest = "innerMargin", action = "store", metavar = "INT",
                       help = "Defines the inner margin between the pages in the booklet" + defaultString )
    marginGroup.add_option( "-t", "--top-margin", type = "int", default = 30,
                       dest = "topMargin", action = "store", metavar = "INT",
                       help = "Defines the top margin in the booklet" + defaultString )
    marginGroup.add_option( "-b", "--bottom-margin", type = "int", default = 30, metavar = "INT",
                       dest = "bottomMargin", action = "store",
                       help = "Defines the bottom margin in the booklet" + defaultString )
    parser.add_option_group( marginGroup )

    advancedGroup = OptionGroup( parser, "Advanced" )
    advancedGroup.add_option( "--signature", dest = "signature", action = "store", type = "int",
                       help = "Define the signature for the booklet handed to pdfjam, needs to be multiple of 4" + defaultString,
                       default = 4, metavar = "INT" )
    advancedGroup.add_option( "--signature*", dest = "signature", action = "store", type = "int",
                       help = "Same as --signature", metavar = "INT" )
    advancedGroup.add_option( "--resolution", dest = "resolution", action = "store", type = "int",
                       help = "Resolution used by ghostscript in bp" + defaultString,
                       metavar = "INT", default = 72 )
    parser.add_option_group( advancedGroup )

    opts, args = parser.parse_args()

    #------------------------------------ show help if started without arguments
    if len( args ) == 0:
        parser.print_version()
        parser.print_help()
        print ""
        sys.exit( 2 )

    #------------------------------------------- run for each provided file name
    parser.print_version()
    for arg in args:
        booklify( arg, opts )