diff --git a/pdf-sign b/pdf-sign index e744a05..d14dc58 100755 --- a/pdf-sign +++ b/pdf-sign @@ -78,6 +78,50 @@ def main(args): signaturePositionY=Cell(args.y_coordinate, 'signaturePositionY') signatureScale=Cell(0, 'signatureScale') tdbg() + def translatablePDF(path): + cache = translatablePDF._cache + if path not in cache: + (w, h) = pdfGetSize(path) + (double_w, double_h) = (2*w, 2*h) + testFile = os.path.join(tempdir, 'translateTest.pdf') + subprocess.run([ + 'gs', '-dBATCH', '-dNOPAUSE', '-dSAFER', '-dQUIET', + f'-sOutputFile={testFile}', + '-sDEVICE=pdfwrite', + f'-dDEVICEWIDTHPOINTS={double_w}', f'-dDEVICEHEIGHTPOINTS={double_h}', '-dFIXEDMEDIA', + '-c', f'<> setpagedevice', + '-f', path, + ], check=True) + (test_w, test_h) = pdfGetSize(testFile) + if (test_w, test_h) == (double_w, double_h): + # The pdf file at path can be translated correctly + cache[path] = path + elif (test_w, test_h) == (w, h): + # The pdf file at path cannot be translated correctly. + # Rather, the size is unchanged. This can happen if the PDF + # has an explicit CropBox set. We have to remove it to make + # the PDF translatable and usable as a signature. + translatableFileName = os.path.join(tempdir, f'translatable{len(cache)}.pdf') + emptyFileName = os.path.join(tempdir, f'empty{len(cache)}.pdf') + subprocess.run([ + 'gs', '-dBATCH', '-dNOPAUSE', '-dSAFER', '-dQUIET', + f'-sOutputFile={emptyFileName}', + '-sDEVICE=pdfwrite', + f'-dDEVICEWIDTHPOINTS={w}', f'-dDEVICEHEIGHTPOINTS={h}', + ], check=True) + qpdfOrPdftk([ + 'qpdf', '--overlay', path, '--', + emptyFileName, translatableFileName, + ],[ + 'pdftk', emptyFileName, + 'stamp', path, + 'output', translatableFileName + ]) + cache[path] = translatableFileName + else: + die(f"The PDF at {path} is unusable as a signature. Reason unknown.") + return cache[path] + translatablePDF._cache={} @Cell def signaturePositionedPDF(): (w, h)=pageSize() @@ -92,7 +136,7 @@ def main(args): '-sDEVICE=pdfwrite', f'-dDEVICEWIDTHPOINTS={w}', f'-dDEVICEHEIGHTPOINTS={h}', '-dFIXEDMEDIA', '-c', f'<> setpagedevice', - '-f', signaturePath(), + '-f', translatablePDF(signaturePath()), ], check=True) return outFile # The signed page