Skip to content

Instantly share code, notes, and snippets.

@lenrsmith
Created February 12, 2018 20:22
Show Gist options
  • Save lenrsmith/a15c2b36cc7118af30379e97eb2e54c8 to your computer and use it in GitHub Desktop.
Save lenrsmith/a15c2b36cc7118af30379e97eb2e54c8 to your computer and use it in GitHub Desktop.
Rough algorithm to calculate pages for a booklet
function collateBookletPages($totalPages)
{
// See if the page count is odd. If so, add 1 page to make it even
if($totalPages % 2) {
$totalPages++;
}
// $totalSides is a bit misleading, but couldn't think of a better term at the moment.
// We are referring to one side of a sheet of paper (obverso/reverso) upon which
// 2 pages will be printed on the left and right.
$totalSides = $totalPages / 2;
$side = []; // We will collect the pages in an array.
for($x = 0; $x < $totalSides; $x++)
{
$sideIdx = $x + 1;
if($sideIdx % 2) {
// Working with an odd side
$side[$sideIdx]["left"] = $totalPages - $x;
$side[$sideIdx}["right"] = $x + 1;
} else {
// Working with an even side
$side[$sideIdx]["left"] = $x + 1;
$side[$sideIdx]["right"] = $totalPages - $x;
}
}
}
// The above just determines which page numbers will be printed where. You will need to work out the logic for getting the correct
// content onto each page.
// Here is a trace:
collateBookletPages(15);
$totalPages = 15 --> count is Odd so we add 1 --> $totalPages = 16
$totalSize = $totalPages / 2 = 16 / 2 = 8
$x | $sideIdx | "left" | "right"
0 | 1 | 16 | 1
1 | 2 | 2 | 15
2 | 3 | 14 | 3
3 | 4 | 4 | 13
4 | 5 | 12 | 5
5 | 6 | 6 | 11
6 | 7 | 10 | 7
7 | 8 | 8 | 9
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment