Printing instruction manuals, how to reorder postscript files

Today I had to solve the following quite interesting mostly mathematical problem:

I received an instruction manual with continuous pages (1, 2, …, n), where n is a multiple of 4.

I wanted to print them as DIN A5 on a DIN A4 sheet, two-sided. Usually, this means printing [ (1, 2), (3, 4) ], …, [ (n-3), (n-2), (n-1, n)] each of these pairs (“tuples”) on a side of a sheet. The [ … ] represents a DIN A4 sheet.

In my special case however, I wanted to stack all of the DIN A4 papers, fold them in the middle and staple them to stick together. Just pull out a random technical manual and you’ll see what I mean: The outer DIN A4 sheet contains the front and back cover, and the first and last inner page, the inner-next sheet contains the second and third, and penultimate and pre-penultimate inner page.

When the manual is closed, all the DIN A4 pages will be nested.

Since no office software I knew offered this special feature, I was stuck.

The required steps were:
1) Reorder the pages (1, …, n). The resulting ordered set (called n-tuple, which will contain all numbers between 1 and n) could look like (…, 1, …, n, …).
2) Print the reordered pages on a duplex printer.

That’s how I realized 1)

a) Consider the correct permutation. You’ll soon find out that for the outer side of the outer sheet, you’ll need (n, 1). This is because an open book viewed from the back has its back on the left side and its front on the right side.

For the inner side of the cover, you’ll need (2, n-1), then you’ll need (n-2, 3) and so on until you’re finished, i.e. you’ve reached (n/2, n/2+1).

I wrote a little python permutation algorithm as a proof of concept that also explains the algorithm.

#!/usr/bin/python

# reorder the numbers between 1 and n (argv[1]) according to the
# "alternating cut-zip sorting" algorithm, used for printing
# continuous pages (resized) to pages of twice the original size,
# in an order appropriate for instruction manuals that
# consist of nested sheets.
#
# I just called this algorithm "alternating cut-zip sorting" algorithm,
# feel free to correct me if there is another name for it!
#
# We have n pages, n must be even, and should be divisible by 4 to yield
# proper results. If it is not divisible by 4, you'll need a blank front
# and back page.
#
# Example:
#   Assuming n=8, we previously had DIN A5 pages as an n-tuple
#   (1, 2, 3, 4, 5, 6, 7, 8)
#   Now, we want to print this in duplex mode on DIN A4 paper like
#
#    sheet 1: [(Page 8 | Page 1), (Page 2 | Page 7)]
#    sheet 2: [(Page 6 | Page 3), (Page 4 | Page 5)]
#
#   This algorithm will arrange for the (8, 1, 2, 7, 6, 3, 4, 5)
#   order, and the printer driver just has to print the new document
#   duplex 2-on-1 resized on DIN A4 paper.
#
# Construction of this permutation:
#  We 'cut' the original tuple in the middle,
#  count up in one half and count down in the other half,
#  and in each iteration glue a pair together, swapping order
#  (greater number left, smaller number left) in each iteration.
#
#  The swapping is required because once you turn over pages, you'll
#  jump from the left half of a DIN A4 page to the right half and vice
#  versa.
#
# General pattern for new page order (spaces added for better readability):
#  n, 1,   2, n-1,   n-2, 3,   4, n-3,   , ..., ...,   (n/2), (n/2)+1

import sys

n = int (sys.argv[1])

if n % 2:
  print "expected even number, but " + str(n) + " is not even! Aborting."
  sys.exit(1)

for i in range(1, n/2+1):
  if i != 1:
    sys.stdout.write (' ')

  if i % 2:
    sys.stdout.write (str(n+1-i) + ' ' + str(i))
  else:
    sys.stdout.write (str(i) + ' ' + str(n+1-i))

sys.stdout.write ('\n')
sys.exit (0)

b) Modify an existing python script that extracts pages from a PostScript file and reverses them to use the permutation algorithm.

c) Use the modified script to reorder the pages of a PDF file.

This is done by converting the original PDF file with acroread, using

acroread -toPostScript -size A5 myfile.pdf

We use acroread because it yields way smaller compressed PS files than pdf2ps can ever produce due to usage of patented algorithms.

Now, the PS pages are reordered with the modified script, and converted back:

ps2pdf -sPAPERSIZE=a5 myreorderedfile.ps

Now proceed to step 2) and you have a pretty instruction manual.

Update

The comments on this article yielded some interesting comments: My python script could have been shorter and more elegant, the psutils package offers similar functionality and OpenOffice.org offers brochure printing which seems to be exactly what I’m looking for. Thanks for all your feedback.

nautilus-open-terminal 0.8 is out

Get it from ftp.gnome.org. Spread it by voting for it.

This is the first release that is distributed through the ftp.gnome.org server. Thanks to Davyd for making it happen.

Unfortunately, a pal of mine behind cluecoder.org that was used to host the old packages is still in clinch with the old hoster so I can’t access my old tarballs and some privare data.

nautilus-open-terminal 0.8
==========================
"Alive"

        * Dedicated to Klaus Kreuzeder, an excellent Saxophonist. http://www.trick-music.de/klaus_kreuzeder.htm

        * Depend on Nautilus 2.17.2
        * Use activation URI of selected files for determining URI. This allows to use the extension for your Desktop bookmarks.
        * Also deal with "ssh" URIs and treat them like "sftp" URIs.
        * Use open() and cwd() to change directories. Should fix trouble with blocked media ejection.

        * Added translations
                ar      Khaled Hosny                    
                bn_IN   Runa Bhattacharjee              
                be      Ihar Hrachyshka                 
                da      Peter Bach                      
                dz      sonam pelden
                et      Ivar Smolin                     
                gu      Ankit Patel                     
                ka      Vladimer Sichinava              
                ml      Ani Peter                       
                sl      Matej Urbančič                  

        * Updated translations
                ca      Gil Forcada                     
                en_GB   David Lodge                     
                ne      Mahesh subedi                   
                nl      Wouter Bolsterlee               

media handling ("autoplay") followup

Joe [1]: I already proposed a “desktop-entry-hotplug-spec” [2] some time ago. I sent it two times and didn’t receive any feedback, so I wasn’t sure whether it is considered important.

The other feature you demanded (actions for files) is IIRC already implemented by KDE. I’m not sure how we should tackle this and I am not so happy with the KDE system.

Example:


[Desktop Action reSize640x480]
Name=Scale to 640x480
Icon=images
Exec=mogrify -resize 640x480! %U
Terminal=false
Type=Application

While it allows for maximum flexibility we’ll end up with a can of worms when internationalizing this since it will be distributed with each application, especially with routine actions like printing. Also, it doesn’t consider how many items are selected – it is common to use ngettext() for internationalizing strings referring to countable objects.

It would really be great if we at least had some actions – maybe similar to those in [2] – for printing and enqueueing. Applications would simply provide a special Exec parameter, and we could immediately see that an application provides this capability.

Oh, and while we’re at it I also have an old “keyword-spec” draft that might be of general interest. I’ll sent it to you by email to get some feedback.

[1] http://joeshaw.org/2007/01/14/452

[2] http://mail.gnome.org/archives/gnome-hackers/2006-October/msg00002.html

MIME Types/Applications: The next generation

For years I’ve been very unhappy with the MIME type/application association.

The Ubuntu guys did a spec [0] and came up with a not-so-pretty UI, so I hacked something together. The (not yet implemented) architecture is described under [1], a very first (failed) UI experiment can be found under [2] and the first serious proposal under [3]. I really like it :).

[2] and [3] provide python scripts that should run flawlessly under Ubuntu Edgy. It turns out that script languages extremely simplifiy communication between developers and usability experts as both can run a script and there is no compilation hurdle.

Feedback appreciated, preferably on the usability list.

I still don’t have a concept how we can properly integrate URI handling with MIME type handling. Maybe it’s best to just set the HTML/email message MIME type handler when changing the URI handler (the latter is stored in GConf).

[0] https://wiki.ubuntu.com/Usability/SpecEnhancedPreferredApps

[1] http://mail.gnome.org/archives/usability/2007-January/msg00064.html

[2] http://mail.gnome.org/archives/usability/2007-January/msg00065.html

[3] http://mail.gnome.org/archives/usability/2007-January/msg00068.html

Christmas Gifts: Much Joy :)

Christmas yielded For Musicians Only by Dizzie All Star Big G Gillespie and friends, and The Man Without Qualities (Der Mann ohne Eigenschaften) by Robert Musil, as well as a book on public speaking which is an excellent reference for giving talks. The kind of book you need when holding exercises at universities.

I recently found out that I also love popular swing, in particular Bei Mir Bist Du Schoen which has an interesting history. I’ve just heard the Benny Goodman’s Carnegie Hall Performance, and I find the melody amazing :). I’ve never before heard a trumpet that is played like a Clarinet.

It is great to see how large the spectrum of Klezmer-influenced music is, there are so many great performers like Giora Feidman. The Clarinet is really one of my favourite instruments!

Oh, dear lazyweb: Does anybody of you know whether John Philip Souza also made “operatic” music? I love “The Stars and Stripes Forever”, but listening through some CDs was a bit disappointing since most what I heard was very militaristic and not really virtuosic.

The Joy of Hacking

After quite some time without any GNOME code contribution, I invested a few dozen hours again and worked on the following issues:

* Fix stupid GnomeVFS crash due to lack of retval initialization (#381119)
* Cook up (not yet published) patch for having date-based axes (for charting your stocks) in Gnumeric/GOffice graphs, which made me
* Enable GOffice/libgsf XML (de)serialization of object properties whose types are derived from G_TYPE_ENUM, G_TYPE_FLAGS (#380396)
* Enable correct translation of Gnumeric functions (not yet reviewed) (#381564)

Conclusion: Hacking is fun, especially when you have to deal with many layers of a software stack! 🙂

Rants are great

Jeff: Thanks for bringing up Thom’s rants and going into his criticism. I disagree that this rant was superflous, though. Rants are very important, because they give people a voice who are not heard by the community and by the developers otherwise.

We’re all busy, and we all don’t have enough time to absorb enough feedback and valid criticism when it is scattered among thousands of bug reports, which is why we are perceived as arrogant although this is not the case, and often gain of momentum for specific improvements lacks not because we’re lazy, but because there aren’t enough people who get a significant amount of platform-related work done.

Sometimes we need an ISV or a distributor that sponsors and enforces a particular development to make framework improvments actually happen. Just imagine the current desktop without HAL and hotplugging. It would lack 50% sexiness. Kudos to David Zeuthen and everybody who helped to make this happen, including Red Hat that sponsored most of the recent significant platform improvements!

So we learn: Distributors can enforce development, end users (by definition they are no developers) can either ask nicely or rant, but identifying a tiny workflow problem is often harder than solving is, so this role is still very valuable, no matter how unfriendly the feedback may sound. That said, we were given very valuable and objective feedback as well, cf. the famous 40+ Suggestions for Better Desktop by Peter Chabada.

It’s like with personal relations: Subjective and loud, unfiltered clamor gives the criticized partner an opportunity to put himself in the partner’s place.

I find it personally refreshing to get bug reports presented in a concentrated and terse fashion, and I’ve heard most of the points myself during discussions with end users. Users often can’t distinguish between low-hanging fruit and demanding tasks, but they usually identify shortcomings (or their effects) of computer systems correctly.

At the moment, I’m in the process of upgrading my mother’s computer to Dapper, so that I can investigate and hopefully tackle the ZIP drive issue Thom writes about.

Why Federico is a Hero; GnomeVFS Documentation; Tango Nuevo; Quality Music

Many people whined about the lack of an entry in GtkFileChoosers located inside file chooser dialogs, probably because they were to lazy to press Ctrl-L and loved to flame. Federico did it: He merged code for a GtkEntry in GtkFileChoosers into GTK+ HEAD. This means that even the reactionists among the GNOME/GTK+ users will not cry anymore. Hooray! 🙂

Meanwhile, I’m improving GnomeVFS documentation and getting used to “Tango Nuevo”. If you also want to learn about that passionate music, I recommend you to grab Tango: Zero Hour, which contains excellent accoustic Tango, Maria de Buenos Aires, which is an excellent record of THE Tango Operita (doesn’t seem to be available on amazon.com, though), and Libertango, which is a real classic of Tango Nuevo, although I find the drums to bold sometimes. All of the above are excellent records, and for the more advanced of you there is also the very brilliant Tangoklezmer by Giora Feidman available.

It amazes me how strong, distinct and spiritual the musical visions by many modern and classical artists are. Unfortunately, popular music lacks this kind of visions, and often creativity. I assume it is not too uncommon that the way music sounds is dictated by producers, who seem to think that people are not interested in quality music. This applies for roughly for 90% of the music that can be found in charts in western countries. I mean, there are excellent modern works available, and there is an unbelievable amount of great classical music from Schönberg, Eisler, Bach, Dvorak and MANY others, and popular music nowadays just seems to be essentially a lifestyle product instead of something both the creators and the audience identify themselves with, which is a pitty.

Update

It was pointed out in the comment section of this blog posting that my claims about some people who complained about the lack of an entry in the file chooser were arrogant. I accused them of being to lazy to use Ctrl-L.

I’m very sorry, I didn’t want to insult anybody (I obviously did), and I appreciate ANY constructive criticism. Having spent hundrets of hours on bug triaging and polishing of GNOME software, I am aware that much feedback out there is very useful, and I’d like to hug everybody who invested time to give the developers feedback, or to help the developers dealing with the huge amount of feedback (i.e. the bugsquad).

I must also admit that while we offer some nice features to advanced users in GTK+, they are not really documented wery well (at least from the user’s POV), so people keep asking the same questions over and over. Unfortunately, to my knowledge we have no publicly available documents explaining why the entry is not in the GtkFileChooser dialog by default, and how quickly it can be accessed as of writing (~, /, Ctrl-L are all shortcuts). A GTK+ manpage and a GTK+ web FAQ might save both our users and our developers much stress :).

Productive Week

Improved GnomeVFS performance, GnomeVFS SFTP symlink support and Nautilus session management. The last one was implemented in response to a user rant within half a day. At least they can’t claim that we don’t work our butts off :).

SFTP policy rant

It’s a PITA to fiddle out the differences of the various (as the current draft’s URI suggests 12!) SFTP drafts. Maybe somebody has the whole history of them, so that we can compile some diffs which can be published on a publicly accessible site? It’s a shame that the version 6 draft is online but for version 3 implemented by OpenSSH no documentation seems to be online anymore on the IETF.

Studies

Although spending lots of time on GNOME I as able to complete at least 3/4 university tests (the results of no. 4 are still pending), and for two of them (Maths, Electrophysics) I was under the top 20 out of 600, which is quite pleasing considering how much time I wasted :).