Anonymous avatar Anonymous committed 04ef9eb

Fixed indentation.
Added tests for outputFormat and multiplyPages Options.

Comments (1)

  1. Dinu Gherman repo owner

    Merged, thanks! Concerning testing "pdfnupping" multiple formats: you could combine the existing letter format test PDF with an A4 one. See also LayoutingTests.test2. I should probably add a legal format test PDF, too, for such purposes.

    BTW, I might want to change the --outformat option into --format only since it can apply only to that.

Files changed (2)

 """
 _mtA4Pdf = zlib.decompress(base64.decodestring(_mtA4PdfZip64))
 
-# Some basic paper dimensions calculated using reportlab
+# Some basic paper dimensions calculated using reportlab. Given in points (user space units = 1/72 inch)
 dimensions = {'a0': (2381.102362204724, 3367.55905511811),
               'a1': (1683.779527559055, 2381.102362204724),
               'a2': (1190.551181102362, 1683.779527559055),
               'letter': (612.0, 792.0)}
 
 def getDimensions(outputFormat):
-  if not outputFormat.lower() in dimensions:
-    raise LookupError("Unknown format: '%s'" % outputFormat)
-  return dimensions[outputFormat.lower()]
+    "Get the dimensions of the given paper format in points (user space units = 1/72 inch)"
+    if not outputFormat.lower() in dimensions:
+        raise LookupError("Unknown format: '%s'" % outputFormat)
+    return dimensions[outputFormat.lower()]
 
 def isSquare(n):
     "Is this a square number?"
         yscale = h / hp
 
     if keepPageRatio:
-      scale = min(xscale, yscale)
-      return scale, scale
+        scale = min(xscale, yscale)
+        return scale, scale
     else:
-      return xscale, yscale
+        return xscale, yscale
 
 
 
     outputPageSize = oldPageSize
     # force specific output format?
     if outputFormat:
-      outputPageSize = getDimensions(outputFormat)
-      # Landscape? Then switch dimensions
-      if docReader.getPage(0).mediaBox.upperRight[0] > docReader.getPage(0).mediaBox.upperRight[1]:
-        outputPageSize = outputPageSize[1], outputPageSize[0]
+        outputPageSize = getDimensions(outputFormat)
+        # Landscape? Then switch dimensions
+        if docReader.getPage(0).mediaBox.upperRight[0] > docReader.getPage(0).mediaBox.upperRight[1]:
+            outputPageSize = outputPageSize[1], outputPageSize[0]
 
     # create empty output document buffer
     if isSquare(n):
         newPageSize = outputPageSize
     elif isHalfSquare(n):
         newPageSize = outputPageSize[1], outputPageSize[0]
-    np = numPages / n + numPages % n
+    np = numPages 
+    if not multiplyPages:
+        np = numPages / n + numPages % n
     buf = exP1multiN(_mtA4Pdf, newPageSize, np)
 
     # calculate mini page areas
     newPageNum = -1
     pagesToRender = numPages
     if multiplyPages:
-      pagesToRender = numPages * n
+        pagesToRender = numPages * n
     for i in range(pagesToRender):
         if i % n == 0:
             newPageNum += 1
     _MSG = "Please install pyPdf first, see http://pybrary.net/pyPdf"
     raise RuntimeError(_MSG)
 
-from pdfnup import generateNup
+from pdfnup import generateNup, getDimensions
 
 
 def group(seq, groupLen=None):
                     exp = group([str(num) for num in range(np0)], n)[pn]
                     self.assertEqual(text, exp)
 
+    def test3(self):
+        "Test generating several 'n-up' docs with a different target paper size."
+
+        for path0 in ("samples/test-a4-l.pdf", "samples/test-a4-p.pdf"):
+            for n in (2, 4, 8, 9):
+                outName = os.path.splitext(path0)[0] + "-out-a2-%dup.pdf" % n
+                path1 = os.path.join(".", outName)
+                generateNup(path0, n, path1, verbose=False, outputFormat="a2")
+
+                # assert output has correct number of pages
+                input = PdfFileReader(file(path0, "rb"))
+                np0 = input.getNumPages()
+                input = PdfFileReader(file(path1, "rb"))
+                np1 = input.getNumPages()
+                self.assertEqual(np1, math.ceil(np0 / float(n)))
+
+                # assert output page(s) has/have correct text content and Dimensions
+                roundedA2Dim = map(round, getDimensions("a2"))
+                for pn in range(np1):
+                    page = input.getPage(pn)
+                    targetDim = map(round, page.mediaBox.upperRight)
+                    targetDim.sort()
+                    self.assertEqual(roundedA2Dim, targetDim)
+                    text = page.extractText().split()
+                    exp = group([str(num) for num in range(np0)], n)[pn]
+                    self.assertEqual(text, exp)
+
+
+    def test4(self):
+        "Test generating several 'n-up' docs with a different target paper size and page multiplication."
+
+        for path0 in ("samples/test-a4-l.pdf", "samples/test-a4-p.pdf"):
+            for n in (2, 4, 8, 9):
+                outName = os.path.splitext(path0)[0] + "-out-a2-multi-%dup.pdf" % n
+                path1 = os.path.join(".", outName)
+                generateNup(path0, n, path1, verbose=False, outputFormat="a2", multiplyPages=True)
+
+                # assert output has correct number of pages
+                input = PdfFileReader(file(path0, "rb"))
+                np0 = input.getNumPages()
+                input = PdfFileReader(file(path1, "rb"))
+                np1 = input.getNumPages()
+                self.assertEqual(np0, np1)
+
+                # assert output page(s) has/have correct text content and Dimensions
+                roundedA2Dim = map(round, getDimensions("a2"))
+                for pn in range(np1):
+                    page = input.getPage(pn)
+                    targetDim = map(round, page.mediaBox.upperRight)
+                    targetDim.sort()
+                    self.assertEqual(roundedA2Dim, targetDim)
+                    text = page.extractText().split()
+                    exp = [str(pn) for _ in range(n)]
+                    self.assertEqual(text, exp)
+
 
 class RotationTests(unittest.TestCase):
     "Test input documents with rotated pages."
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.