As is common in Europe (due to the wonderful ISO 216 and its neat A-size series with the 1:√2 ratio), I'm making a booklet with pages that are the standard A5 size, portrait, but need to be printed on landscape A4 paper — in 2 columns, and double-sided too, so you end up with 4 A5 pages to an A4 sheet, and a booklet that can be stapled in the middle.
Now the stupid way to do it, which I've done before, is to manually work out how the pages need to be ordered, and compose them that way in your document editing software. This is a pain in the neck — even with a DTP that allows for arbitrary flowing of text around the document. The order is really not obvious, and you can easily get confused. And if you find you actually need another A4 sheet, it will be a nightmare.
The booklet in question is the order of service, and I was fed up with the stupid way, so this wedding has again has given me some reason to use my programming skills.
Without further ado, here is my solution, in case anyone else finds it useful:
It takes a PDF containing A5 sheets, and churns out a PDF with them organised into A4 sheets. In fact it isn't limited to those sizes — it will do anything, but it does assume all the pages of the input document are the same size.
It use the PyPDF2 library, which isn't brilliantly documented, but was easy enough to use for this purpose.
The algorithm for working out the order is nicely separated from the PDF specific code, so it could be easily repurposed for other formats.