summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--CHANGES.rst8
-rw-r--r--MANIFEST.in1
-rw-r--r--PKG-INFO4
-rw-r--r--setup.py2
-rw-r--r--src/img2pdf.egg-info/PKG-INFO4
-rw-r--r--src/img2pdf.egg-info/SOURCES.txt1
-rwxr-xr-xsrc/img2pdf.py1648
-rw-r--r--src/tests/__init__.py77
-rwxr-xr-xtest.sh1468
9 files changed, 2708 insertions, 505 deletions
diff --git a/CHANGES.rst b/CHANGES.rst
index cbe43ce..a9ab56b 100644
--- a/CHANGES.rst
+++ b/CHANGES.rst
@@ -2,6 +2,14 @@
CHANGES
=======
+0.3.3 (2019-01-07)
+------------------
+
+ - restore basic support for Python 2
+ - also ship test.sh
+ - add legal and tabloid paper formats
+ - respect exif rotation tag
+
0.3.2 (2018-11-20)
------------------
diff --git a/MANIFEST.in b/MANIFEST.in
index 9249d3f..d86af25 100644
--- a/MANIFEST.in
+++ b/MANIFEST.in
@@ -1,5 +1,6 @@
include README.md
include test_comp.sh
+include test.sh
include CHANGES.rst
include LICENSE
recursive-include src *.jpg
diff --git a/PKG-INFO b/PKG-INFO
index 7925752..7553591 100644
--- a/PKG-INFO
+++ b/PKG-INFO
@@ -1,12 +1,12 @@
Metadata-Version: 2.1
Name: img2pdf
-Version: 0.3.2
+Version: 0.3.3
Summary: Convert images to PDF via direct JPEG inclusion.
Home-page: https://gitlab.mister-muffin.de/josch/img2pdf
Author: Johannes 'josch' Schauer
Author-email: josch@mister-muffin.de
License: LGPL
-Download-URL: https://gitlab.mister-muffin.de/josch/img2pdf/repository/archive.tar.gz?ref=0.3.2
+Download-URL: https://gitlab.mister-muffin.de/josch/img2pdf/repository/archive.tar.gz?ref=0.3.3
Description: img2pdf
=======
diff --git a/setup.py b/setup.py
index 8160035..b0438fe 100644
--- a/setup.py
+++ b/setup.py
@@ -3,7 +3,7 @@ from setuptools import setup
PY3 = sys.version_info[0] >= 3
-VERSION = "0.3.2"
+VERSION = "0.3.3"
INSTALL_REQUIRES = (
'Pillow',
diff --git a/src/img2pdf.egg-info/PKG-INFO b/src/img2pdf.egg-info/PKG-INFO
index 7925752..7553591 100644
--- a/src/img2pdf.egg-info/PKG-INFO
+++ b/src/img2pdf.egg-info/PKG-INFO
@@ -1,12 +1,12 @@
Metadata-Version: 2.1
Name: img2pdf
-Version: 0.3.2
+Version: 0.3.3
Summary: Convert images to PDF via direct JPEG inclusion.
Home-page: https://gitlab.mister-muffin.de/josch/img2pdf
Author: Johannes 'josch' Schauer
Author-email: josch@mister-muffin.de
License: LGPL
-Download-URL: https://gitlab.mister-muffin.de/josch/img2pdf/repository/archive.tar.gz?ref=0.3.2
+Download-URL: https://gitlab.mister-muffin.de/josch/img2pdf/repository/archive.tar.gz?ref=0.3.3
Description: img2pdf
=======
diff --git a/src/img2pdf.egg-info/SOURCES.txt b/src/img2pdf.egg-info/SOURCES.txt
index 3271401..6fa068a 100644
--- a/src/img2pdf.egg-info/SOURCES.txt
+++ b/src/img2pdf.egg-info/SOURCES.txt
@@ -4,6 +4,7 @@ MANIFEST.in
README.md
setup.cfg
setup.py
+test.sh
test_comp.sh
src/img2pdf.py
src/jp2.py
diff --git a/src/img2pdf.py b/src/img2pdf.py
index e9402b3..27e5b8c 100755
--- a/src/img2pdf.py
+++ b/src/img2pdf.py
@@ -23,7 +23,9 @@ import os
import zlib
import argparse
from PIL import Image, TiffImagePlugin
-#TiffImagePlugin.DEBUG = True
+
+# TiffImagePlugin.DEBUG = True
+from PIL.ExifTags import TAGS
from datetime import datetime
from jp2 import parsejp2
from enum import Enum
@@ -33,84 +35,313 @@ import struct
PY3 = sys.version_info[0] >= 3
-__version__ = "0.3.2"
+__version__ = "0.3.3"
default_dpi = 96.0
papersizes = {
"letter": "8.5inx11in",
- "a0": "841mmx1189mm",
- "a1": "594mmx841mm",
- "a2": "420mmx594mm",
- "a3": "297mmx420mm",
- "a4": "210mmx297mm",
- "a5": "148mmx210mm",
- "a6": "105mmx148mm",
+ "a0": "841mmx1189mm",
+ "a1": "594mmx841mm",
+ "a2": "420mmx594mm",
+ "a3": "297mmx420mm",
+ "a4": "210mmx297mm",
+ "a5": "148mmx210mm",
+ "a6": "105mmx148mm",
+ "legal": "8.5inx14in",
+ "tabloid": "11inx17in",
}
papernames = {
"letter": "Letter",
- "a0": "A0",
- "a1": "A1",
- "a2": "A2",
- "a3": "A3",
- "a4": "A4",
- "a5": "A5",
- "a6": "A6",
+ "a0": "A0",
+ "a1": "A1",
+ "a2": "A2",
+ "a3": "A3",
+ "a4": "A4",
+ "a5": "A5",
+ "a6": "A6",
+ "legal": "Legal",
+ "tabloid": "Tabloid",
}
-FitMode = Enum('FitMode', 'into fill exact shrink enlarge')
+FitMode = Enum("FitMode", "into fill exact shrink enlarge")
-PageOrientation = Enum('PageOrientation', 'portrait landscape')
+PageOrientation = Enum("PageOrientation", "portrait landscape")
-Colorspace = Enum('Colorspace', 'RGB L 1 CMYK CMYK;I RGBA P other')
+Colorspace = Enum("Colorspace", "RGB L 1 CMYK CMYK;I RGBA P other")
-ImageFormat = Enum('ImageFormat', 'JPEG JPEG2000 CCITTGroup4 PNG TIFF other')
+ImageFormat = Enum("ImageFormat", "JPEG JPEG2000 CCITTGroup4 PNG TIFF other")
-PageMode = Enum('PageMode', 'none outlines thumbs')
+PageMode = Enum("PageMode", "none outlines thumbs")
-PageLayout = Enum('PageLayout',
- 'single onecolumn twocolumnright twocolumnleft')
+PageLayout = Enum("PageLayout", "single onecolumn twocolumnright twocolumnleft")
-Magnification = Enum('Magnification', 'fit fith fitbh')
+Magnification = Enum("Magnification", "fit fith fitbh")
-ImgSize = Enum('ImgSize', 'abs perc dpi')
+ImgSize = Enum("ImgSize", "abs perc dpi")
-Unit = Enum('Unit', 'pt cm mm inch')
+Unit = Enum("Unit", "pt cm mm inch")
-ImgUnit = Enum('ImgUnit', 'pt cm mm inch perc dpi')
+ImgUnit = Enum("ImgUnit", "pt cm mm inch perc dpi")
TIFFBitRevTable = [
- 0x00, 0x80, 0x40, 0xC0, 0x20, 0xA0, 0x60, 0xE0,
- 0x10, 0x90, 0x50, 0xD0, 0x30, 0xB0, 0x70, 0xF0,
- 0x08, 0x88, 0x48, 0xC8, 0x28, 0xA8, 0x68, 0xE8,
- 0x18, 0x98, 0x58, 0xD8, 0x38, 0xB8, 0x78, 0xF8,
- 0x04, 0x84, 0x44, 0xC4, 0x24, 0xA4, 0x64, 0xE4,
- 0x14, 0x94, 0x54, 0xD4, 0x34, 0xB4, 0x74, 0xF4,
- 0x0C, 0x8C, 0x4C, 0xCC, 0x2C, 0xAC, 0x6C, 0xEC,
- 0x1C, 0x9C, 0x5C, 0xDC, 0x3C, 0xBC, 0x7C, 0xFC,
- 0x02, 0x82, 0x42, 0xC2, 0x22, 0xA2, 0x62, 0xE2,
- 0x12, 0x92, 0x52, 0xD2, 0x32, 0xB2, 0x72, 0xF2,
- 0x0A, 0x8A, 0x4A, 0xCA, 0x2A, 0xAA, 0x6A, 0xEA,
- 0x1A, 0x9A, 0x5A, 0xDA, 0x3A, 0xBA, 0x7A, 0xFA,
- 0x06, 0x86, 0x46, 0xC6, 0x26, 0xA6, 0x66, 0xE6,
- 0x16, 0x96, 0x56, 0xD6, 0x36, 0xB6, 0x76, 0xF6,
- 0x0E, 0x8E, 0x4E, 0xCE, 0x2E, 0xAE, 0x6E, 0xEE,
- 0x1E, 0x9E, 0x5E, 0xDE, 0x3E, 0xBE, 0x7E, 0xFE,
- 0x01, 0x81, 0x41, 0xC1, 0x21, 0xA1, 0x61, 0xE1,
- 0x11, 0x91, 0x51, 0xD1, 0x31, 0xB1, 0x71, 0xF1,
- 0x09, 0x89, 0x49, 0xC9, 0x29, 0xA9, 0x69, 0xE9,
- 0x19, 0x99, 0x59, 0xD9, 0x39, 0xB9, 0x79, 0xF9,
- 0x05, 0x85, 0x45, 0xC5, 0x25, 0xA5, 0x65, 0xE5,
- 0x15, 0x95, 0x55, 0xD5, 0x35, 0xB5, 0x75, 0xF5,
- 0x0D, 0x8D, 0x4D, 0xCD, 0x2D, 0xAD, 0x6D, 0xED,
- 0x1D, 0x9D, 0x5D, 0xDD, 0x3D, 0xBD, 0x7D, 0xFD,
- 0x03, 0x83, 0x43, 0xC3, 0x23, 0xA3, 0x63, 0xE3,
- 0x13, 0x93, 0x53, 0xD3, 0x33, 0xB3, 0x73, 0xF3,
- 0x0B, 0x8B, 0x4B, 0xCB, 0x2B, 0xAB, 0x6B, 0xEB,
- 0x1B, 0x9B, 0x5B, 0xDB, 0x3B, 0xBB, 0x7B, 0xFB,
- 0x07, 0x87, 0x47, 0xC7, 0x27, 0xA7, 0x67, 0xE7,
- 0x17, 0x97, 0x57, 0xD7, 0x37, 0xB7, 0x77, 0xF7,
- 0x0F, 0x8F, 0x4F, 0xCF, 0x2F, 0xAF, 0x6F, 0xEF,
- 0x1F, 0x9F, 0x5F, 0xDF, 0x3F, 0xBF, 0x7F, 0xFF]
+ 0x00,
+ 0x80,
+ 0x40,
+ 0xC0,
+ 0x20,
+ 0xA0,
+ 0x60,
+ 0xE0,
+ 0x10,
+ 0x90,
+ 0x50,
+ 0xD0,
+ 0x30,
+ 0xB0,
+ 0x70,
+ 0xF0,
+ 0x08,
+ 0x88,
+ 0x48,
+ 0xC8,
+ 0x28,
+ 0xA8,
+ 0x68,
+ 0xE8,
+ 0x18,
+ 0x98,
+ 0x58,
+ 0xD8,
+ 0x38,
+ 0xB8,
+ 0x78,
+ 0xF8,
+ 0x04,
+ 0x84,
+ 0x44,
+ 0xC4,
+ 0x24,
+ 0xA4,
+ 0x64,
+ 0xE4,
+ 0x14,
+ 0x94,
+ 0x54,
+ 0xD4,
+ 0x34,
+ 0xB4,
+ 0x74,
+ 0xF4,
+ 0x0C,
+ 0x8C,
+ 0x4C,
+ 0xCC,
+ 0x2C,
+ 0xAC,
+ 0x6C,
+ 0xEC,
+ 0x1C,
+ 0x9C,
+ 0x5C,
+ 0xDC,
+ 0x3C,
+ 0xBC,
+ 0x7C,
+ 0xFC,
+ 0x02,
+ 0x82,
+ 0x42,
+ 0xC2,
+ 0x22,
+ 0xA2,
+ 0x62,
+ 0xE2,
+ 0x12,
+ 0x92,
+ 0x52,
+ 0xD2,
+ 0x32,
+ 0xB2,
+ 0x72,
+ 0xF2,
+ 0x0A,
+ 0x8A,
+ 0x4A,
+ 0xCA,
+ 0x2A,
+ 0xAA,
+ 0x6A,
+ 0xEA,
+ 0x1A,
+ 0x9A,
+ 0x5A,
+ 0xDA,
+ 0x3A,
+ 0xBA,
+ 0x7A,
+ 0xFA,
+ 0x06,
+ 0x86,
+ 0x46,
+ 0xC6,
+ 0x26,
+ 0xA6,
+ 0x66,
+ 0xE6,
+ 0x16,
+ 0x96,
+ 0x56,
+ 0xD6,
+ 0x36,
+ 0xB6,
+ 0x76,
+ 0xF6,
+ 0x0E,
+ 0x8E,
+ 0x4E,
+ 0xCE,
+ 0x2E,
+ 0xAE,
+ 0x6E,
+ 0xEE,
+ 0x1E,
+ 0x9E,
+ 0x5E,
+ 0xDE,
+ 0x3E,
+ 0xBE,
+ 0x7E,
+ 0xFE,
+ 0x01,
+ 0x81,
+ 0x41,
+ 0xC1,
+ 0x21,
+ 0xA1,
+ 0x61,
+ 0xE1,
+ 0x11,
+ 0x91,
+ 0x51,
+ 0xD1,
+ 0x31,
+ 0xB1,
+ 0x71,
+ 0xF1,
+ 0x09,
+ 0x89,
+ 0x49,
+ 0xC9,
+ 0x29,
+ 0xA9,
+ 0x69,
+ 0xE9,
+ 0x19,
+ 0x99,
+ 0x59,
+ 0xD9,
+ 0x39,
+ 0xB9,
+ 0x79,
+ 0xF9,
+ 0x05,
+ 0x85,
+ 0x45,
+ 0xC5,
+ 0x25,
+ 0xA5,
+ 0x65,
+ 0xE5,
+ 0x15,
+ 0x95,
+ 0x55,
+ 0xD5,
+ 0x35,
+ 0xB5,
+ 0x75,
+ 0xF5,
+ 0x0D,
+ 0x8D,
+ 0x4D,
+ 0xCD,
+ 0x2D,
+ 0xAD,
+ 0x6D,
+ 0xED,
+ 0x1D,
+ 0x9D,
+ 0x5D,
+ 0xDD,
+ 0x3D,
+ 0xBD,
+ 0x7D,
+ 0xFD,
+ 0x03,
+ 0x83,
+ 0x43,
+ 0xC3,
+ 0x23,
+ 0xA3,
+ 0x63,
+ 0xE3,
+ 0x13,
+ 0x93,
+ 0x53,
+ 0xD3,
+ 0x33,
+ 0xB3,
+ 0x73,
+ 0xF3,
+ 0x0B,
+ 0x8B,
+ 0x4B,
+ 0xCB,
+ 0x2B,
+ 0xAB,
+ 0x6B,
+ 0xEB,
+ 0x1B,
+ 0x9B,
+ 0x5B,
+ 0xDB,
+ 0x3B,
+ 0xBB,
+ 0x7B,
+ 0xFB,
+ 0x07,
+ 0x87,
+ 0x47,
+ 0xC7,
+ 0x27,
+ 0xA7,
+ 0x67,
+ 0xE7,
+ 0x17,
+ 0x97,
+ 0x57,
+ 0xD7,
+ 0x37,
+ 0xB7,
+ 0x77,
+ 0xF7,
+ 0x0F,
+ 0x8F,
+ 0x4F,
+ 0xCF,
+ 0x2F,
+ 0xAF,
+ 0x6F,
+ 0xEF,
+ 0x1F,
+ 0x9F,
+ 0x5F,
+ 0xDF,
+ 0x3F,
+ 0xBF,
+ 0x7F,
+ 0xFF,
+]
+
class NegativeDimensionError(Exception):
pass
@@ -139,9 +370,18 @@ def my_convert_load(string):
def parse(cont, indent=1):
if type(cont) is dict:
- return b"<<\n"+b"\n".join(
- [4 * indent * b" " + k + b" " + parse(v, indent+1)
- for k, v in sorted(cont.items())])+b"\n"+4*(indent-1)*b" "+b">>"
+ return (
+ b"<<\n"
+ + b"\n".join(
+ [
+ 4 * indent * b" " + k + b" " + parse(v, indent + 1)
+ for k, v in sorted(cont.items())
+ ]
+ )
+ + b"\n"
+ + 4 * (indent - 1) * b" "
+ + b">>"
+ )
elif type(cont) is int:
return str(cont).encode()
elif type(cont) is float:
@@ -159,13 +399,13 @@ def parse(cont, indent=1):
elif type(cont) is str or isinstance(cont, bytes):
if type(cont) is str and type(cont) is not bytes:
raise TypeError(
- "parse must be passed a bytes object in py3. Got: %s" % cont)
+ "parse must be passed a bytes object in py3. Got: %s" % cont
+ )
return cont
elif isinstance(cont, list):
- return b"[ "+b" ".join([parse(c, indent) for c in cont])+b" ]"
+ return b"[ " + b" ".join([parse(c, indent) for c in cont]) + b" ]"
else:
- raise TypeError("cannot handle type %s with content %s" % (type(cont),
- cont))
+ raise TypeError("cannot handle type %s with content %s" % (type(cont), cont))
class MyPdfDict(object):
@@ -188,12 +428,18 @@ class MyPdfDict(object):
def tostring(self):
if self.stream is not None:
return (
- ("%d 0 obj\n" % self.identifier).encode() +
- parse(self.content) +
- b"\nstream\n" + self.stream + b"\nendstream\nendobj\n")
+ ("%d 0 obj\n" % self.identifier).encode()
+ + parse(self.content)
+ + b"\nstream\n"
+ + self.stream
+ + b"\nendstream\nendobj\n"
+ )
else:
- return ("%d 0 obj\n" % self.identifier).encode() + \
- parse(self.content) + b"\nendobj\n"
+ return (
+ ("%d 0 obj\n" % self.identifier).encode()
+ + parse(self.content)
+ + b"\nendobj\n"
+ )
def __setitem__(self, key, value):
self.content[key] = value
@@ -202,9 +448,9 @@ class MyPdfDict(object):
return self.content[key]
-class MyPdfName():
+class MyPdfName:
def __getattr__(self, name):
- return b'/' + name.encode('ascii')
+ return b"/" + name.encode("ascii")
MyPdfName = MyPdfName()
@@ -212,14 +458,14 @@ MyPdfName = MyPdfName()
class MyPdfObject(bytes):
def __new__(cls, string):
- return bytes.__new__(cls, string.encode('ascii'))
+ return bytes.__new__(cls, string.encode("ascii"))
class MyPdfArray(list):
pass
-class MyPdfWriter():
+class MyPdfWriter:
def __init__(self, version="1.3"):
self.objects = []
# create an incomplete pages object so that a /Parent entry can be
@@ -230,7 +476,7 @@ class MyPdfWriter():
self.pagearray = []
def addobj(self, obj):
- newid = len(self.objects)+1
+ newid = len(self.objects) + 1
obj.identifier = newid
self.objects.append(obj)
@@ -251,8 +497,8 @@ class MyPdfWriter():
#
# the choice of binary characters is arbitrary but those four seem to
# be used elsewhere.
- pdfheader = ('%%PDF-%s\n' % self.version).encode('ascii')
- pdfheader += b'%\xe2\xe3\xcf\xd3\n'
+ pdfheader = ("%%PDF-%s\n" % self.version).encode("ascii")
+ pdfheader += b"%\xe2\xe3\xcf\xd3\n"
stream.write(pdfheader)
# From section 3.4.3 of the PDF Reference (version 1.7):
@@ -291,8 +537,10 @@ class MyPdfWriter():
for x in xreftable:
stream.write(x)
stream.write(b"trailer\n")
- stream.write(parse({b"/Size": len(xreftable), b"/Info": info,
- b"/Root": self.catalog})+b"\n")
+ stream.write(
+ parse({b"/Size": len(xreftable), b"/Info": info, b"/Root": self.catalog})
+ + b"\n"
+ )
stream.write(b"startxref\n")
stream.write(("%d\n" % xrefoffset).encode())
stream.write(b"%%EOF\n")
@@ -307,49 +555,76 @@ class MyPdfWriter():
if PY3:
- class MyPdfString():
+
+ class MyPdfString:
@classmethod
def encode(cls, string, hextype=False):
if hextype:
- return b'< ' + b' '.join(
- ("%06x" % c).encode('ascii') for c in string) + b' >'
+ return (
+ b"< "
+ + b" ".join(("%06x" % c).encode("ascii") for c in string)
+ + b" >"
+ )
else:
try:
- string = string.encode('ascii')
+ string = string.encode("ascii")
except UnicodeEncodeError:
- string = b"\xfe\xff"+string.encode("utf-16-be")
+ string = b"\xfe\xff" + string.encode("utf-16-be")
# We should probably encode more here because at least
# ghostscript interpretes a carriage return byte (0x0D) as a
# new line byte (0x0A)
# PDF supports: \n, \r, \t, \b and \f
- string = string.replace(b'\\', b'\\\\')
- string = string.replace(b'(', b'\\(')
- string = string.replace(b')', b'\\)')
- return b'(' + string + b')'
+ string = string.replace(b"\\", b"\\\\")
+ string = string.replace(b"(", b"\\(")
+ string = string.replace(b")", b"\\)")
+ return b"(" + string + b")"
+
+
else:
+
class MyPdfString(object):
@classmethod
def encode(cls, string, hextype=False):
if hextype:
- return b'< ' + b' '.join(
- ("%06x" % c).encode('ascii') for c in string) + b' >'
+ return (
+ b"< "
+ + b" ".join(("%06x" % c).encode("ascii") for c in string)
+ + b" >"
+ )
else:
# This mimics exactely to what pdfrw does.
- string = string.replace(b'\\', b'\\\\')
- string = string.replace(b'(', b'\\(')
- string = string.replace(b')', b'\\)')
- return b'(' + string + b')'
+ string = string.replace(b"\\", b"\\\\")
+ string = string.replace(b"(", b"\\(")
+ string = string.replace(b")", b"\\)")
+ return b"(" + string + b")"
class pdfdoc(object):
- def __init__(self, version="1.3", title=None, author=None, creator=None,
- producer=None, creationdate=None, moddate=None, subject=None,
- keywords=None, nodate=False, panes=None, initial_page=None,
- magnification=None, page_layout=None, fit_window=False,
- center_window=False, fullscreen=False, with_pdfrw=True):
+ def __init__(
+ self,
+ version="1.3",
+ title=None,
+ author=None,
+ creator=None,
+ producer=None,
+ creationdate=None,
+ moddate=None,
+ subject=None,
+ keywords=None,
+ nodate=False,
+ panes=None,
+ initial_page=None,
+ magnification=None,
+ page_layout=None,
+ fit_window=False,
+ center_window=False,
+ fullscreen=False,
+ with_pdfrw=True,
+ ):
if with_pdfrw:
try:
from pdfrw import PdfWriter, PdfDict, PdfName, PdfString
+
self.with_pdfrw = True
except ImportError:
PdfWriter = MyPdfWriter
@@ -379,17 +654,21 @@ class pdfdoc(object):
if producer is not None and producer != "":
self.info[PdfName.Producer] = PdfString.encode(producer)
if creationdate is not None:
- self.info[PdfName.CreationDate] = \
- PdfString.encode("D:"+datetime_to_pdfdate(creationdate))
+ self.info[PdfName.CreationDate] = PdfString.encode(
+ "D:" + datetime_to_pdfdate(creationdate)
+ )
elif not nodate:
- self.info[PdfName.CreationDate] = \
- PdfString.encode("D:"+datetime_to_pdfdate(now))
+ self.info[PdfName.CreationDate] = PdfString.encode(
+ "D:" + datetime_to_pdfdate(now)
+ )
if moddate is not None:
- self.info[PdfName.ModDate] = \
- PdfString.encode("D:"+datetime_to_pdfdate(moddate))
+ self.info[PdfName.ModDate] = PdfString.encode(
+ "D:" + datetime_to_pdfdate(moddate)
+ )
elif not nodate:
self.info[PdfName.ModDate] = PdfString.encode(
- "D:"+datetime_to_pdfdate(now))
+ "D:" + datetime_to_pdfdate(now)
+ )
if subject is not None:
self.info[PdfName.Subject] = PdfString.encode(subject)
if keywords is not None:
@@ -412,10 +691,25 @@ class pdfdoc(object):
self.center_window = center_window
self.fullscreen = fullscreen
- def add_imagepage(self, color, imgwidthpx, imgheightpx, imgformat, imgdata,
- imgwidthpdf, imgheightpdf, imgxpdf, imgypdf, pagewidth,
- pageheight, userunit=None, palette=None, inverted=False,
- depth=0):
+ def add_imagepage(
+ self,
+ color,
+ imgwidthpx,
+ imgheightpx,
+ imgformat,
+ imgdata,
+ imgwidthpdf,
+ imgheightpdf,
+ imgxpdf,
+ imgypdf,
+ pagewidth,
+ pageheight,
+ userunit=None,
+ palette=None,
+ inverted=False,
+ depth=0,
+ rotate=0,
+ ):
if self.with_pdfrw:
from pdfrw import PdfDict, PdfName, PdfObject, PdfString
from pdfrw.py23_diffs import convert_load
@@ -426,22 +720,27 @@ class pdfdoc(object):
PdfString = MyPdfString
convert_load = my_convert_load
- if color == Colorspace['1'] or color == Colorspace.L:
+ if color == Colorspace["1"] or color == Colorspace.L:
colorspace = PdfName.DeviceGray
elif color == Colorspace.RGB:
colorspace = PdfName.DeviceRGB
- elif color == Colorspace.CMYK or color == Colorspace['CMYK;I']:
+ elif color == Colorspace.CMYK or color == Colorspace["CMYK;I"]:
colorspace = PdfName.DeviceCMYK
elif color == Colorspace.P:
if self.with_pdfrw:
- raise Exception("pdfrw does not support hex strings for "
- "palette image input, re-run with "
- "--without-pdfrw")
- colorspace = [PdfName.Indexed, PdfName.DeviceRGB, len(palette)-1,
- PdfString.encode(palette, hextype=True)]
+ raise Exception(
+ "pdfrw does not support hex strings for "
+ "palette image input, re-run with "
+ "--without-pdfrw"
+ )
+ colorspace = [
+ PdfName.Indexed,
+ PdfName.DeviceRGB,
+ len(palette) - 1,
+ PdfString.encode(palette, hextype=True),
+ ]
else:
- raise UnsupportedColorspaceError("unsupported color space: %s"
- % color.name)
+ raise UnsupportedColorspaceError("unsupported color space: %s" % color.name)
# either embed the whole jpeg or deflate the bitmap representation
if imgformat is ImageFormat.JPEG:
@@ -464,7 +763,7 @@ class pdfdoc(object):
image[PdfName.ColorSpace] = colorspace
image[PdfName.BitsPerComponent] = depth
- if color == Colorspace['CMYK;I']:
+ if color == Colorspace["CMYK;I"]:
# Inverts all four channels
image[PdfName.Decode] = [1.0, 0.0, 1.0, 0.0, 1.0, 0.0, 1.0, 0.0]
@@ -474,16 +773,16 @@ class pdfdoc(object):
# encoding. We set it to -1 because we want Group 4 encoding.
decodeparms[PdfName.K] = -1
if inverted:
- decodeparms[PdfName.BlackIs1] = PdfObject('false')
+ decodeparms[PdfName.BlackIs1] = PdfObject("false")
else:
- decodeparms[PdfName.BlackIs1] = PdfObject('true')
+ decodeparms[PdfName.BlackIs1] = PdfObject("true")
decodeparms[PdfName.Columns] = imgwidthpx
decodeparms[PdfName.Rows] = imgheightpx
image[PdfName.DecodeParms] = [decodeparms]
elif imgformat is ImageFormat.PNG:
decodeparms = PdfDict()
decodeparms[PdfName.Predictor] = 15
- if color in [Colorspace.P, Colorspace['1'], Colorspace.L]:
+ if color in [Colorspace.P, Colorspace["1"], Colorspace.L]:
decodeparms[PdfName.Colors] = 1
else:
decodeparms[PdfName.Colors] = 3
@@ -491,8 +790,10 @@ class pdfdoc(object):
decodeparms[PdfName.BitsPerComponent] = depth
image[PdfName.DecodeParms] = decodeparms
- text = ("q\n%0.4f 0 0 %0.4f %0.4f %0.4f cm\n/Im0 Do\nQ" %
- (imgwidthpdf, imgheightpdf, imgxpdf, imgypdf)).encode("ascii")
+ text = (
+ "q\n%0.4f 0 0 %0.4f %0.4f %0.4f cm\n/Im0 Do\nQ"
+ % (imgwidthpdf, imgheightpdf, imgxpdf, imgypdf)
+ ).encode("ascii")
content = PdfDict(stream=convert_load(text))
resources = PdfDict(XObject=PdfDict(Im0=image))
@@ -502,10 +803,12 @@ class pdfdoc(object):
page[PdfName.MediaBox] = [0, 0, pagewidth, pageheight]
page[PdfName.Resources] = resources
page[PdfName.Contents] = content
+ if rotate != 0:
+ page[PdfName.Rotate] = rotate
if userunit is not None:
# /UserUnit requires PDF 1.6
- if self.writer.version < '1.6':
- self.writer.version = '1.6'
+ if self.writer.version < "1.6":
+ self.writer.version = "1.6"
page[PdfName.UserUnit] = userunit
self.writer.addpage(page)
@@ -527,8 +830,8 @@ class pdfdoc(object):
PdfName = MyPdfName
PdfObject = MyPdfObject
PdfArray = MyPdfArray
- NullObject = PdfObject('null')
- TrueObject = PdfObject('true')
+ NullObject = PdfObject("null")
+ TrueObject = PdfObject("true")
# We fill the catalog with more information like /ViewerPreferences,
# /PageMode, /PageLayout or /OpenAction because the latter refers to a
@@ -543,23 +846,30 @@ class pdfdoc(object):
else:
catalog = self.writer.catalog
- if self.fullscreen or self.fit_window or self.center_window or \
- self.panes is not None:
+ if (
+ self.fullscreen
+ or self.fit_window
+ or self.center_window
+ or self.panes is not None
+ ):
catalog[PdfName.ViewerPreferences] = PdfDict()
if self.fullscreen:
# this setting might be overwritten later by the page mode
- catalog[PdfName.ViewerPreferences][PdfName.NonFullScreenPageMode] \
- = PdfName.UseNone
+ catalog[PdfName.ViewerPreferences][
+ PdfName.NonFullScreenPageMode
+ ] = PdfName.UseNone
if self.panes == PageMode.thumbs:
- catalog[PdfName.ViewerPreferences][PdfName.NonFullScreenPageMode] \
- = PdfName.UseThumbs
+ catalog[PdfName.ViewerPreferences][
+ PdfName.NonFullScreenPageMode
+ ] = PdfName.UseThumbs
# this setting might be overwritten later if fullscreen
catalog[PdfName.PageMode] = PdfName.UseThumbs
elif self.panes == PageMode.outlines:
- catalog[PdfName.ViewerPreferences][PdfName.NonFullScreenPageMode] \
- = PdfName.UseOutlines
+ catalog[PdfName.ViewerPreferences][
+ PdfName.NonFullScreenPageMode
+ ] = PdfName.UseOutlines
# this setting might be overwritten later if fullscreen
catalog[PdfName.PageMode] = PdfName.UseOutlines
elif self.panes in [PageMode.none, None]:
@@ -571,8 +881,7 @@ class pdfdoc(object):
catalog[PdfName.ViewerPreferences][PdfName.FitWindow] = TrueObject
if self.center_window:
- catalog[PdfName.ViewerPreferences][PdfName.CenterWindow] = \
- TrueObject
+ catalog[PdfName.ViewerPreferences][PdfName.CenterWindow] = TrueObject
if self.fullscreen:
catalog[PdfName.PageMode] = PdfName.FullScreen
@@ -598,24 +907,27 @@ class pdfdoc(object):
# account
if self.initial_page is not None:
initial_page = self.writer.pagearray[self.initial_page - 1]
- catalog[PdfName.OpenAction] = PdfArray([initial_page, PdfName.XYZ,
- NullObject, NullObject, 0])
+ catalog[PdfName.OpenAction] = PdfArray(
+ [initial_page, PdfName.XYZ, NullObject, NullObject, 0]
+ )
if self.magnification == Magnification.fit:
catalog[PdfName.OpenAction] = PdfArray([initial_page, PdfName.Fit])
elif self.magnification == Magnification.fith:
pagewidth = initial_page[PdfName.MediaBox][2]
catalog[PdfName.OpenAction] = PdfArray(
- [initial_page, PdfName.FitH, pagewidth])
+ [initial_page, PdfName.FitH, pagewidth]
+ )
elif self.magnification == Magnification.fitbh:
# quick hack to determine the image width on the page
imgwidth = float(initial_page[PdfName.Contents].stream.split()[4])
catalog[PdfName.OpenAction] = PdfArray(
- [initial_page, PdfName.FitBH, imgwidth])
+ [initial_page, PdfName.FitBH, imgwidth]
+ )
elif isinstance(self.magnification, float):
catalog[PdfName.OpenAction] = PdfArray(
- [initial_page, PdfName.XYZ, NullObject, NullObject,
- self.magnification])
+ [initial_page, PdfName.XYZ, NullObject, NullObject, self.magnification]
+ )
elif self.magnification is None:
pass
else:
@@ -643,8 +955,7 @@ class pdfdoc(object):
def get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata=None):
- if imgformat == ImageFormat.JPEG2000 \
- and rawdata is not None and imgdata is None:
+ if imgformat == ImageFormat.JPEG2000 and rawdata is not None and imgdata is None:
# this codepath gets called if the PIL installation is not able to
# handle JPEG2000 files
imgwidthpx, imgheightpx, ics, hdpi, vdpi = parsejp2(rawdata)
@@ -667,12 +978,15 @@ def get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata=None):
ics = imgdata.mode
if ics in ["LA", "PA", "RGBA"] or "transparency" in imgdata.info:
- logging.warning("Image contains transparency which cannot be retained "
- "in PDF.")
+ logging.warning(
+ "Image contains transparency which cannot be retained " "in PDF."
+ )
logging.warning("img2pdf will not perform a lossy operation.")
logging.warning("You can remove the alpha channel using imagemagick:")
- logging.warning(" $ convert input.png -background white -alpha "
- "remove -alpha off output.png")
+ logging.warning(
+ " $ convert input.png -background white -alpha "
+ "remove -alpha off output.png"
+ )
raise Exception("Refusing to work on images with alpha channel")
# Since commit 07a96209597c5e8dfe785c757d7051ce67a980fb or release 4.1.0
@@ -685,11 +999,39 @@ def get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata=None):
# PIL defaults to a dpi of 1 if a TIFF image does not specify the dpi.
# In that case, we want to use a different default.
if ndpi == (1, 1) and imgformat == ImageFormat.TIFF:
- ndpi = (imgdata.tag_v2.get(TiffImagePlugin.X_RESOLUTION, default_dpi),
- imgdata.tag_v2.get(TiffImagePlugin.Y_RESOLUTION, default_dpi))
+ ndpi = (
+ imgdata.tag_v2.get(TiffImagePlugin.X_RESOLUTION, default_dpi),
+ imgdata.tag_v2.get(TiffImagePlugin.Y_RESOLUTION, default_dpi),
+ )
logging.debug("input dpi = %d x %d", *ndpi)
+ rotation = 0
+ if hasattr(imgdata, "_getexif") and imgdata._getexif() is not None:
+ for tag, value in imgdata._getexif().items():
+ if TAGS.get(tag, tag) == "Orientation":
+ # Detailed information on EXIF rotation tags:
+ # http://impulseadventure.com/photo/exif-orientation.html
+ if value == 1:
+ rotation = 0
+ elif value == 6:
+ rotation = 90
+ elif value == 3:
+ rotation = 180
+ elif value == 8:
+ rotation = 270
+ elif value in (2, 4, 5, 7):
+ raise Exception(
+ 'Image "%s": Unsupported flipped '
+ "rotation mode (%d)" % (im.name, value)
+ )
+ else:
+ raise Exception(
+ 'Image "%s": invalid rotation (%d)' % (im.name, value)
+ )
+
+ logging.debug("rotation = %d°", rotation)
+
if colorspace:
color = colorspace
logging.debug("input colorspace (forced) = %s", color)
@@ -704,8 +1046,11 @@ def get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata=None):
# that info manually by looking at byte 10 in the IHDR chunk. We
# know where to find that in the file because the IHDR chunk must
# be the first chunk
- if rawdata is not None and imgformat == ImageFormat.PNG \
- and rawdata[25] == 0:
+ if (
+ rawdata is not None
+ and imgformat == ImageFormat.PNG
+ and rawdata[25] == 0
+ ):
color = Colorspace.L
else:
raise ValueError("unknown colorspace")
@@ -718,25 +1063,27 @@ def get_imgmetadata(imgdata, imgformat, default_dpi, colorspace, rawdata=None):
# better for images currently in the wild, so I'm going
# with the first approach for now.
if "adobe" in imgdata.info:
- color = Colorspace['CMYK;I']
+ color = Colorspace["CMYK;I"]
logging.debug("input colorspace = %s", color.name)
logging.debug("width x height = %dpx x %dpx", imgwidthpx, imgheightpx)
- return (color, ndpi, imgwidthpx, imgheightpx)
+ return (color, ndpi, imgwidthpx, imgheightpx, rotation)
def ccitt_payload_location_from_pil(img):
# If Pillow is passed an invalid compression argument it will ignore it;
# make sure the image actually got compressed.
- if img.info['compression'] != 'group4':
- raise ValueError("Image not compressed with CCITT Group 4 but with: %s"
- % img.info['compression'])
+ if img.info["compression"] != "group4":
+ raise ValueError(
+ "Image not compressed with CCITT Group 4 but with: %s"
+ % img.info["compression"]
+ )
# Read the TIFF tags to find the offset(s) of the compressed data strips.
strip_offsets = img.tag_v2[TiffImagePlugin.STRIPOFFSETS]
strip_bytes = img.tag_v2[TiffImagePlugin.STRIPBYTECOUNTS]
- rows_per_strip = img.tag_v2.get(TiffImagePlugin.ROWSPERSTRIP, 2**32 - 1)
+ rows_per_strip = img.tag_v2.get(TiffImagePlugin.ROWSPERSTRIP, 2 ** 32 - 1)
# PIL always seems to create a single strip even for very large TIFFs when
# it saves images, so assume we only have to read a single strip.
@@ -745,7 +1092,7 @@ def ccitt_payload_location_from_pil(img):
if len(strip_offsets) != 1 or len(strip_bytes) != 1:
raise NotImplementedError("Transcoding multiple strips not supported")
- (offset, ), (length, ) = strip_offsets, strip_bytes
+ (offset,), (length,) = strip_offsets, strip_bytes
logging.debug("TIFF strip_offsets: %d" % offset)
logging.debug("TIFF strip_bytes: %d" % length)
@@ -767,7 +1114,7 @@ def transcode_monochrome(imgdata):
# killed by a SIGABRT:
# https://gitlab.mister-muffin.de/josch/img2pdf/issues/46
im = Image.frombytes(imgdata.mode, imgdata.size, imgdata.tobytes())
- im.save(newimgio, format='TIFF', compression='group4')
+ im.save(newimgio, format="TIFF", compression="group4")
# Open new image in memory
newimgio.seek(0)
@@ -785,12 +1132,12 @@ def parse_png(rawdata):
i = 16
while i < len(rawdata):
# once we can require Python >= 3.2 we can use int.from_bytes() instead
- n, = struct.unpack('>I', rawdata[i-8:i-4])
+ n, = struct.unpack(">I", rawdata[i - 8 : i - 4])
if i + n > len(rawdata):
raise Exception("invalid png: %d %d %d" % (i, n, len(rawdata)))
- if rawdata[i-4:i] == b"IDAT":
- pngidat += rawdata[i:i+n]
- elif rawdata[i-4:i] == b"PLTE":
+ if rawdata[i - 4 : i] == b"IDAT":
+ pngidat += rawdata[i : i + n]
+ elif rawdata[i - 4 : i] == b"PLTE":
# This could be as simple as saying "palette = rawdata[i:i+n]" but
# pdfrw does only escape parenthesis and backslashes in the raw
# byte stream. But raw carriage return bytes are interpreted as
@@ -800,10 +1147,10 @@ def parse_png(rawdata):
# (and escape more bytes) but since we cannot use pdfrw anyways,
# we choose the more human readable variant.
# See https://github.com/pmaupin/pdfrw/issues/147
- for j in range(i, i+n, 3):
+ for j in range(i, i + n, 3):
# with int.from_bytes() we would not have to prepend extra
# zeroes
- color, = struct.unpack('>I', b'\x00'+rawdata[j:j+3])
+ color, = struct.unpack(">I", b"\x00" + rawdata[j : j + 3])
palette.append(color)
i += n
i += 12
@@ -819,8 +1166,10 @@ def read_images(rawdata, colorspace, first_frame_only=False):
except IOError as e:
# test if it is a jpeg2000 image
if rawdata[:12] != b"\x00\x00\x00\x0C\x6A\x50\x20\x20\x0D\x0A\x87\x0A":
- raise ImageOpenError("cannot read input image (not jpeg2000). "
- "PIL: error reading image: %s" % e)
+ raise ImageOpenError(
+ "cannot read input image (not jpeg2000). "
+ "PIL: error reading image: %s" % e
+ )
# image is jpeg2000
imgformat = ImageFormat.JPEG2000
else:
@@ -838,18 +1187,31 @@ def read_images(rawdata, colorspace, first_frame_only=False):
# JPEG and JPEG2000 can be embedded into the PDF as-is
if imgformat == ImageFormat.JPEG or imgformat == ImageFormat.JPEG2000:
- color, ndpi, imgwidthpx, imgheightpx = get_imgmetadata(
- imgdata, imgformat, default_dpi, colorspace, rawdata)
- if color == Colorspace['1']:
+ color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(
+ imgdata, imgformat, default_dpi, colorspace, rawdata
+ )
+ if color == Colorspace["1"]:
raise JpegColorspaceError("jpeg can't be monochrome")
- if color == Colorspace['P']:
+ if color == Colorspace["P"]:
raise JpegColorspaceError("jpeg can't have a color palette")
- if color == Colorspace['RGBA']:
+ if color == Colorspace["RGBA"]:
raise JpegColorspaceError("jpeg can't have an alpha channel")
im.close()
logging.debug("read_images() embeds a JPEG")
- return [(color, ndpi, imgformat, rawdata, imgwidthpx, imgheightpx, [],
- False, 8)]
+ return [
+ (
+ color,
+ ndpi,
+ imgformat,
+ rawdata,
+ imgwidthpx,
+ imgheightpx,
+ [],
+ False,
+ 8,
+ rotation,
+ )
+ ]
# We can directly embed the IDAT chunk of PNG images if the PNG is not
# interlaced
@@ -859,8 +1221,9 @@ def read_images(rawdata, colorspace, first_frame_only=False):
# IHDR chunk. We know where to find that in the file because the IHDR chunk
# must be the first chunk.
if imgformat == ImageFormat.PNG and rawdata[28] == 0:
- color, ndpi, imgwidthpx, imgheightpx = get_imgmetadata(
- imgdata, imgformat, default_dpi, colorspace, rawdata)
+ color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(
+ imgdata, imgformat, default_dpi, colorspace, rawdata
+ )
pngidat, palette = parse_png(rawdata)
im.close()
# PIL does not provide the information about the original bits per
@@ -871,8 +1234,20 @@ def read_images(rawdata, colorspace, first_frame_only=False):
if depth not in [1, 2, 4, 8, 16]:
raise ValueError("invalid bit depth: %d" % depth)
logging.debug("read_images() embeds a PNG")
- return [(color, ndpi, imgformat, pngidat, imgwidthpx, imgheightpx,
- palette, False, depth)]
+ return [
+ (
+ color,
+ ndpi,
+ imgformat,
+ pngidat,
+ imgwidthpx,
+ imgheightpx,
+ palette,
+ False,
+ depth,
+ rotation,
+ )
+ ]
# If our input is not JPEG or PNG, then we might have a format that
# supports multiple frames (like TIFF or GIF), so we need a loop to
@@ -905,24 +1280,31 @@ def read_images(rawdata, colorspace, first_frame_only=False):
#
# Some tiff images do not have BITSPERSAMPLE set. Use this to create
# such a tiff: tiffset -u 258 test.tif
- if imgformat == ImageFormat.TIFF \
- and max(imgdata.tag_v2.get(TiffImagePlugin.BITSPERSAMPLE, [1])) > 8:
+ if (
+ imgformat == ImageFormat.TIFF
+ and max(imgdata.tag_v2.get(TiffImagePlugin.BITSPERSAMPLE, [1])) > 8
+ ):
raise ValueError("PIL is unable to preserve more than 8 bits per sample")
# We can directly copy the data out of a CCITT Group 4 encoded TIFF, if it
# only contains a single strip
- if imgformat == ImageFormat.TIFF \
- and imgdata.info['compression'] == "group4" \
- and len(imgdata.tag_v2[TiffImagePlugin.STRIPOFFSETS]) == 1:
+ if (
+ imgformat == ImageFormat.TIFF
+ and imgdata.info["compression"] == "group4"
+ and len(imgdata.tag_v2[TiffImagePlugin.STRIPOFFSETS]) == 1
+ ):
photo = imgdata.tag_v2[TiffImagePlugin.PHOTOMETRIC_INTERPRETATION]
inverted = False
if photo == 0:
inverted = True
elif photo != 1:
- raise ValueError("unsupported photometric interpretation for "
- "group4 tiff: %d" % photo)
- color, ndpi, imgwidthpx, imgheightpx = get_imgmetadata(
- imgdata, imgformat, default_dpi, colorspace, rawdata)
+ raise ValueError(
+ "unsupported photometric interpretation for "
+ "group4 tiff: %d" % photo
+ )
+ color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(
+ imgdata, imgformat, default_dpi, colorspace, rawdata
+ )
offset, length = ccitt_payload_location_from_pil(imgdata)
im.seek(offset)
rawdata = im.read(length)
@@ -943,45 +1325,85 @@ def read_images(rawdata, colorspace, first_frame_only=False):
else:
raise ValueError("unsupported FillOrder: %d" % fillorder)
logging.debug("read_images() embeds Group4 from TIFF")
- result.append((color, ndpi, ImageFormat.CCITTGroup4, rawdata,
- imgwidthpx, imgheightpx, [], inverted, 1))
+ result.append(
+ (
+ color,
+ ndpi,
+ ImageFormat.CCITTGroup4,
+ rawdata,
+ imgwidthpx,
+ imgheightpx,
+ [],
+ inverted,
+ 1,
+ rotation,
+ )
+ )
img_page_count += 1
continue
logging.debug("Converting frame: %d" % img_page_count)
- color, ndpi, imgwidthpx, imgheightpx = get_imgmetadata(
- imgdata, imgformat, default_dpi, colorspace)
+ color, ndpi, imgwidthpx, imgheightpx, rotation = get_imgmetadata(
+ imgdata, imgformat, default_dpi, colorspace
+ )
newimg = None
- if color == Colorspace['1']:
+ if color == Colorspace["1"]:
try:
ccittdata = transcode_monochrome(imgdata)
- logging.debug(
- "read_images() encoded a B/W image as CCITT group 4")
- result.append((color, ndpi, ImageFormat.CCITTGroup4, ccittdata,
- imgwidthpx, imgheightpx, [], False, 1))
+ logging.debug("read_images() encoded a B/W image as CCITT group 4")
+ result.append(
+ (
+ color,
+ ndpi,
+ ImageFormat.CCITTGroup4,
+ ccittdata,
+ imgwidthpx,
+ imgheightpx,
+ [],
+ False,
+ 1,
+ rotation,
+ )
+ )
img_page_count += 1
continue
except Exception as e:
logging.debug(e)
logging.debug("Converting colorspace 1 to L")
- newimg = imgdata.convert('L')
+ newimg = imgdata.convert("L")
color = Colorspace.L
- elif color in [Colorspace.RGB, Colorspace.L, Colorspace.CMYK,
- Colorspace["CMYK;I"], Colorspace.P]:
+ elif color in [
+ Colorspace.RGB,
+ Colorspace.L,
+ Colorspace.CMYK,
+ Colorspace["CMYK;I"],
+ Colorspace.P,
+ ]:
logging.debug("Colorspace is OK: %s", color)
newimg = imgdata
else:
- raise ValueError("unknown or unsupported colorspace: %s"
- % color.name)
+ raise ValueError("unknown or unsupported colorspace: %s" % color.name)
# the PNG format does not support CMYK, so we fall back to normal
# compression
if color in [Colorspace.CMYK, Colorspace["CMYK;I"]]:
imggz = zlib.compress(newimg.tobytes())
logging.debug("read_images() encoded CMYK with flate compression")
- result.append((color, ndpi, imgformat, imggz, imgwidthpx,
- imgheightpx, [], False, 8))
+ result.append(
+ (
+ color,
+ ndpi,
+ imgformat,
+ imggz,
+ imgwidthpx,
+ imgheightpx,
+ [],
+ False,
+ 8,
+ rotation,
+ )
+ )
else:
# cheapo version to retrieve a PNG encoding of the payload is to
# just save it with PIL. In the future this could be replaced by
@@ -998,8 +1420,20 @@ def read_images(rawdata, colorspace, first_frame_only=False):
if depth not in [1, 2, 4, 8, 16]:
raise ValueError("invalid bit depth: %d" % depth)
logging.debug("read_images() encoded an image as PNG")
- result.append((color, ndpi, ImageFormat.PNG, pngidat, imgwidthpx,
- imgheightpx, palette, False, depth))
+ result.append(
+ (
+ color,
+ ndpi,
+ ImageFormat.PNG,
+ pngidat,
+ imgwidthpx,
+ imgheightpx,
+ palette,
+ False,
+ depth,
+ rotation,
+ )
+ )
img_page_count += 1
# the python-pil version 2.3.0-1ubuntu3 in Ubuntu does not have the
# close() method
@@ -1013,71 +1447,80 @@ def read_images(rawdata, colorspace, first_frame_only=False):
# converts a length in pixels to a length in PDF units (1/72 of an inch)
def px_to_pt(length, dpi):
- return 72.0*length/dpi
+ return 72.0 * length / dpi
def cm_to_pt(length):
- return (72.0*length)/2.54
+ return (72.0 * length) / 2.54
def mm_to_pt(length):
- return (72.0*length)/25.4
+ return (72.0 * length) / 25.4
def in_to_pt(length):
- return 72.0*length
+ return 72.0 * length
-def get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None,
- auto_orient=False):
+def get_layout_fun(
+ pagesize=None, imgsize=None, border=None, fit=None, auto_orient=False
+):
def fitfun(fit, imgwidth, imgheight, fitwidth, fitheight):
if fitwidth is None and fitheight is None:
raise ValueError("fitwidth and fitheight cannot both be None")
# if fit is fill or enlarge then it is okay if one of the dimensions
# are negative but one of them must still be positive
# if fit is not fill or enlarge then both dimensions must be positive
- if fit in [FitMode.fill, FitMode.enlarge] and \
- fitwidth is not None and fitwidth < 0 and \
- fitheight is not None and fitheight < 0:
- raise ValueError("cannot fit into a rectangle where both "
- "dimensions are negative")
- elif fit not in [FitMode.fill, FitMode.enlarge] and \
- ((fitwidth is not None and fitwidth < 0) or
- (fitheight is not None and fitheight < 0)):
- raise Exception("cannot fit into a rectangle where either "
- "dimensions are negative")
+ if (
+ fit in [FitMode.fill, FitMode.enlarge]
+ and fitwidth is not None
+ and fitwidth < 0
+ and fitheight is not None
+ and fitheight < 0
+ ):
+ raise ValueError(
+ "cannot fit into a rectangle where both " "dimensions are negative"
+ )
+ elif fit not in [FitMode.fill, FitMode.enlarge] and (
+ (fitwidth is not None and fitwidth < 0)
+ or (fitheight is not None and fitheight < 0)
+ ):
+ raise Exception(
+ "cannot fit into a rectangle where either " "dimensions are negative"
+ )
def default():
if fitwidth is not None and fitheight is not None:
newimgwidth = fitwidth
- newimgheight = (newimgwidth * imgheight)/imgwidth
+ newimgheight = (newimgwidth * imgheight) / imgwidth
if newimgheight > fitheight:
newimgheight = fitheight
- newimgwidth = (newimgheight * imgwidth)/imgheight
+ newimgwidth = (newimgheight * imgwidth) / imgheight
elif fitwidth is None and fitheight is not None:
newimgheight = fitheight
- newimgwidth = (newimgheight * imgwidth)/imgheight
+ newimgwidth = (newimgheight * imgwidth) / imgheight
elif fitheight is None and fitwidth is not None:
newimgwidth = fitwidth
- newimgheight = (newimgwidth * imgheight)/imgwidth
+ newimgheight = (newimgwidth * imgheight) / imgwidth
else:
raise ValueError("fitwidth and fitheight cannot both be None")
return newimgwidth, newimgheight
+
if fit is None or fit == FitMode.into:
return default()
elif fit == FitMode.fill:
if fitwidth is not None and fitheight is not None:
newimgwidth = fitwidth
- newimgheight = (newimgwidth * imgheight)/imgwidth
+ newimgheight = (newimgwidth * imgheight) / imgwidth
if newimgheight < fitheight:
newimgheight = fitheight
- newimgwidth = (newimgheight * imgwidth)/imgheight
+ newimgwidth = (newimgheight * imgwidth) / imgheight
elif fitwidth is None and fitheight is not None:
newimgheight = fitheight
- newimgwidth = (newimgheight * imgwidth)/imgheight
+ newimgwidth = (newimgheight * imgwidth) / imgheight
elif fitheight is None and fitwidth is not None:
newimgwidth = fitwidth
- newimgheight = (newimgwidth * imgheight)/imgwidth
+ newimgheight = (newimgwidth * imgheight) / imgwidth
else:
raise ValueError("fitwidth and fitheight cannot both be None")
return newimgwidth, newimgheight
@@ -1086,10 +1529,10 @@ def get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None,
return fitwidth, fitheight
elif fitwidth is None and fitheight is not None:
newimgheight = fitheight
- newimgwidth = (newimgheight * imgwidth)/imgheight
+ newimgwidth = (newimgheight * imgwidth) / imgheight
elif fitheight is None and fitwidth is not None:
newimgwidth = fitwidth
- newimgheight = (newimgwidth * imgheight)/imgwidth
+ newimgheight = (newimgwidth * imgheight) / imgwidth
else:
raise ValueError("fitwidth and fitheight cannot both be None")
return newimgwidth, newimgheight
@@ -1121,17 +1564,20 @@ def get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None,
return default()
else:
raise NotImplementedError
+
# if no layout arguments are given, then the image size is equal to the
# page size and will be drawn with the default dpi
if pagesize is None and imgsize is None and border is None:
return default_layout_fun
if pagesize is None and imgsize is None and border is not None:
+
def layout_fun(imgwidthpx, imgheightpx, ndpi):
imgwidthpdf = px_to_pt(imgwidthpx, ndpi[0])
imgheightpdf = px_to_pt(imgheightpx, ndpi[1])
- pagewidth = imgwidthpdf+2*border[1]
- pageheight = imgheightpdf+2*border[0]
+ pagewidth = imgwidthpdf + 2 * border[1]
+ pageheight = imgheightpdf + 2 * border[0]
return pagewidth, pageheight, imgwidthpdf, imgheightpdf
+
return layout_fun
if border is None:
border = (0, 0)
@@ -1139,46 +1585,62 @@ def get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None,
# will be calculated from the pagesize, taking into account the border
# and the fitting
if pagesize is not None and imgsize is None:
+
def layout_fun(imgwidthpx, imgheightpx, ndpi):
- if pagesize[0] is not None and pagesize[1] is not None and \
- auto_orient and \
- ((imgwidthpx > imgheightpx and
- pagesize[0] < pagesize[1]) or
- (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1])):
+ if (
+ pagesize[0] is not None
+ and pagesize[1] is not None
+ and auto_orient
+ and (
+ (imgwidthpx > imgheightpx and pagesize[0] < pagesize[1])
+ or (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1])
+ )
+ ):
pagewidth, pageheight = pagesize[1], pagesize[0]
newborder = border[1], border[0]
else:
pagewidth, pageheight = pagesize[0], pagesize[1]
newborder = border
if pagewidth is not None:
- fitwidth = pagewidth-2*newborder[1]
+ fitwidth = pagewidth - 2 * newborder[1]
else:
fitwidth = None
if pageheight is not None:
- fitheight = pageheight-2*newborder[0]
+ fitheight = pageheight - 2 * newborder[0]
else:
fitheight = None
- if fit in [FitMode.fill, FitMode.enlarge] and \
- fitwidth is not None and fitwidth < 0 and \
- fitheight is not None and fitheight < 0:
+ if (
+ fit in [FitMode.fill, FitMode.enlarge]
+ and fitwidth is not None
+ and fitwidth < 0
+ and fitheight is not None
+ and fitheight < 0
+ ):
raise NegativeDimensionError(
"at least one border dimension musts be smaller than half "
- "the respective page dimension")
- elif fit not in [FitMode.fill, FitMode.enlarge] \
- and ((fitwidth is not None and fitwidth < 0) or
- (fitheight is not None and fitheight < 0)):
+ "the respective page dimension"
+ )
+ elif fit not in [FitMode.fill, FitMode.enlarge] and (
+ (fitwidth is not None and fitwidth < 0)
+ or (fitheight is not None and fitheight < 0)
+ ):
raise NegativeDimensionError(
"one border dimension is larger than half of the "
- "respective page dimension")
- imgwidthpdf, imgheightpdf = \
- fitfun(fit, px_to_pt(imgwidthpx, ndpi[0]),
- px_to_pt(imgheightpx, ndpi[1]),
- fitwidth, fitheight)
+ "respective page dimension"
+ )
+ imgwidthpdf, imgheightpdf = fitfun(
+ fit,
+ px_to_pt(imgwidthpx, ndpi[0]),
+ px_to_pt(imgheightpx, ndpi[1]),
+ fitwidth,
+ fitheight,
+ )
if pagewidth is None:
- pagewidth = imgwidthpdf+border[1]*2
+ pagewidth = imgwidthpdf + border[1] * 2
if pageheight is None:
- pageheight = imgheightpdf+border[0]*2
+ pageheight = imgheightpdf + border[0] * 2
return pagewidth, pageheight, imgwidthpdf, imgheightpdf
+
return layout_fun
def scale_imgsize(s, px, dpi):
@@ -1188,37 +1650,50 @@ def get_layout_fun(pagesize=None, imgsize=None, border=None, fit=None,
if mode == ImgSize.abs:
return value
if mode == ImgSize.perc:
- return (px_to_pt(px, dpi)*value)/100
+ return (px_to_pt(px, dpi) * value) / 100
if mode == ImgSize.dpi:
return px_to_pt(px, value)
raise NotImplementedError
+
if pagesize is None and imgsize is not None:
+
def layout_fun(imgwidthpx, imgheightpx, ndpi):
- imgwidthpdf, imgheightpdf = \
- fitfun(fit, px_to_pt(imgwidthpx, ndpi[0]),
- px_to_pt(imgheightpx, ndpi[1]),
- scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),
- scale_imgsize(imgsize[1], imgheightpx, ndpi[1]))
- pagewidth = imgwidthpdf+2*border[1]
- pageheight = imgheightpdf+2*border[0]
+ imgwidthpdf, imgheightpdf = fitfun(
+ fit,
+ px_to_pt(imgwidthpx, ndpi[0]),
+ px_to_pt(imgheightpx, ndpi[1]),
+ scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),
+ scale_imgsize(imgsize[1], imgheightpx, ndpi[1]),
+ )
+ pagewidth = imgwidthpdf + 2 * border[1]
+ pageheight = imgheightpdf + 2 * border[0]
return pagewidth, pageheight, imgwidthpdf, imgheightpdf
+
return layout_fun
if pagesize is not None and imgsize is not None:
+
def layout_fun(imgwidthpx, imgheightpx, ndpi):
- if pagesize[0] is not None and pagesize[1] is not None and \
- auto_orient and \
- ((imgwidthpx > imgheightpx and
- pagesize[0] < pagesize[1]) or
- (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1])):
+ if (
+ pagesize[0] is not None
+ and pagesize[1] is not None
+ and auto_orient
+ and (
+ (imgwidthpx > imgheightpx and pagesize[0] < pagesize[1])
+ or (imgwidthpx < imgheightpx and pagesize[0] > pagesize[1])
+ )
+ ):
pagewidth, pageheight = pagesize[1], pagesize[0]
else:
pagewidth, pageheight = pagesize[0], pagesize[1]
- imgwidthpdf, imgheightpdf = \
- fitfun(fit, px_to_pt(imgwidthpx, ndpi[0]),
- px_to_pt(imgheightpx, ndpi[1]),
- scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),
- scale_imgsize(imgsize[1], imgheightpx, ndpi[1]))
+ imgwidthpdf, imgheightpdf = fitfun(
+ fit,
+ px_to_pt(imgwidthpx, ndpi[0]),
+ px_to_pt(imgheightpx, ndpi[1]),
+ scale_imgsize(imgsize[0], imgwidthpx, ndpi[0]),
+ scale_imgsize(imgsize[1], imgheightpx, ndpi[1]),
+ )
return pagewidth, pageheight, imgwidthpdf, imgheightpdf
+
return layout_fun
raise NotImplementedError
@@ -1235,8 +1710,10 @@ def get_fixed_dpi_layout_fun(fixed_dpi):
>>> layout_fun = get_fixed_dpi_layout_fun((300, 300))
>>> convert(image1, layout_fun=layout_fun, ... outputstream=...)
"""
+
def fixed_dpi_layout_fun(imgwidthpx, imgheightpx, ndpi):
return default_layout_fun(imgwidthpx, imgheightpx, fixed_dpi)
+
return fixed_dpi_layout_fun
@@ -1262,27 +1739,52 @@ def convert(*images, **kwargs):
_default_kwargs = dict(
title=None,
- author=None, creator=None, producer=None, creationdate=None,
- moddate=None, subject=None, keywords=None, colorspace=None,
- nodate=False, layout_fun=default_layout_fun, viewer_panes=None,
- viewer_initial_page=None, viewer_magnification=None,
- viewer_page_layout=None, viewer_fit_window=False,
- viewer_center_window=False, viewer_fullscreen=False,
- with_pdfrw=True, outputstream=None, first_frame_only=False,
- allow_oversized=True)
+ author=None,
+ creator=None,
+ producer=None,
+ creationdate=None,
+ moddate=None,
+ subject=None,
+ keywords=None,
+ colorspace=None,
+ nodate=False,
+ layout_fun=default_layout_fun,
+ viewer_panes=None,
+ viewer_initial_page=None,
+ viewer_magnification=None,
+ viewer_page_layout=None,
+ viewer_fit_window=False,
+ viewer_center_window=False,
+ viewer_fullscreen=False,
+ with_pdfrw=True,
+ outputstream=None,
+ first_frame_only=False,
+ allow_oversized=True,
+ )
for kwname, default in _default_kwargs.items():
if kwname not in kwargs:
kwargs[kwname] = default
pdf = pdfdoc(
"1.3",
- kwargs['title'], kwargs['author'], kwargs['creator'],
- kwargs['producer'], kwargs['creationdate'], kwargs['moddate'],
- kwargs['subject'], kwargs['keywords'], kwargs['nodate'],
- kwargs['viewer_panes'], kwargs['viewer_initial_page'],
- kwargs['viewer_magnification'], kwargs['viewer_page_layout'],
- kwargs['viewer_fit_window'], kwargs['viewer_center_window'],
- kwargs['viewer_fullscreen'], kwargs['with_pdfrw'])
+ kwargs["title"],
+ kwargs["author"],
+ kwargs["creator"],
+ kwargs["producer"],
+ kwargs["creationdate"],
+ kwargs["moddate"],
+ kwargs["subject"],
+ kwargs["keywords"],
+ kwargs["nodate"],
+ kwargs["viewer_panes"],
+ kwargs["viewer_initial_page"],
+ kwargs["viewer_magnification"],
+ kwargs["viewer_page_layout"],
+ kwargs["viewer_fit_window"],
+ kwargs["viewer_center_window"],
+ kwargs["viewer_fullscreen"],
+ kwargs["with_pdfrw"],
+ )
# backwards compatibility with older img2pdf versions where the first
# argument to the function had to be given as a list
@@ -1301,8 +1803,7 @@ def convert(*images, **kwargs):
rawdata = img.read()
except AttributeError:
if not isinstance(img, (str, bytes)):
- raise TypeError(
- "Neither implements read() nor is str or bytes")
+ raise TypeError("Neither implements read() nor is str or bytes")
# the thing doesn't have a read() function, so try if we can treat
# it as a file name
try:
@@ -1314,18 +1815,29 @@ def convert(*images, **kwargs):
# name so we now try treating it as raw image content
rawdata = img
- for color, ndpi, imgformat, imgdata, imgwidthpx, imgheightpx, \
- palette, inverted, depth in read_images(
- rawdata, kwargs['colorspace'], kwargs['first_frame_only']):
- pagewidth, pageheight, imgwidthpdf, imgheightpdf = \
- kwargs['layout_fun'](imgwidthpx, imgheightpx, ndpi)
+ for (
+ color,
+ ndpi,
+ imgformat,
+ imgdata,
+ imgwidthpx,
+ imgheightpx,
+ palette,
+ inverted,
+ depth,
+ rotation,
+ ) in read_images(rawdata, kwargs["colorspace"], kwargs["first_frame_only"]):
+ pagewidth, pageheight, imgwidthpdf, imgheightpdf = kwargs["layout_fun"](
+ imgwidthpx, imgheightpx, ndpi
+ )
userunit = None
if pagewidth < 3.00 or pageheight < 3.00:
- logging.warning("pdf width or height is below 3.00 - too "
- "small for some viewers!")
+ logging.warning(
+ "pdf width or height is below 3.00 - too " "small for some viewers!"
+ )
elif pagewidth > 14400.0 or pageheight > 14400.0:
- if kwargs['allow_oversized']:
+ if kwargs["allow_oversized"]:
userunit = find_scale(pagewidth, pageheight)
pagewidth /= userunit
pageheight /= userunit
@@ -1333,24 +1845,39 @@ def convert(*images, **kwargs):
imgheightpdf /= userunit
else:
raise PdfTooLargeError(
- "pdf width or height must not exceed 200 inches.")
+ "pdf width or height must not exceed 200 inches."
+ )
# the image is always centered on the page
- imgxpdf = (pagewidth - imgwidthpdf)/2.0
- imgypdf = (pageheight - imgheightpdf)/2.0
- pdf.add_imagepage(color, imgwidthpx, imgheightpx, imgformat,
- imgdata, imgwidthpdf, imgheightpdf, imgxpdf,
- imgypdf, pagewidth, pageheight, userunit,
- palette, inverted, depth)
-
- if kwargs['outputstream']:
- pdf.tostream(kwargs['outputstream'])
+ imgxpdf = (pagewidth - imgwidthpdf) / 2.0
+ imgypdf = (pageheight - imgheightpdf) / 2.0
+ pdf.add_imagepage(
+ color,
+ imgwidthpx,
+ imgheightpx,
+ imgformat,
+ imgdata,
+ imgwidthpdf,
+ imgheightpdf,
+ imgxpdf,
+ imgypdf,
+ pagewidth,
+ pageheight,
+ userunit,
+ palette,
+ inverted,
+ depth,
+ rotation,
+ )
+
+ if kwargs["outputstream"]:
+ pdf.tostream(kwargs["outputstream"])
return
return pdf.tostring()
def parse_num(num, name):
- if num == '':
+ if num == "":
return None
unit = None
if num.endswith("pt"):
@@ -1365,8 +1892,10 @@ def parse_num(num, name):
try:
num = float(num)
except ValueError:
- msg = "%s is not a floating point number and doesn't have a " \
- "valid unit: %s" % (name, num)
+ msg = (
+ "%s is not a floating point number and doesn't have a "
+ "valid unit: %s" % (name, num)
+ )
raise argparse.ArgumentTypeError(msg)
if unit is None:
unit = Unit.pt
@@ -1387,7 +1916,7 @@ def parse_num(num, name):
def parse_imgsize_num(num, name):
- if num == '':
+ if num == "":
return None
unit = None
if num.endswith("pt"):
@@ -1406,8 +1935,10 @@ def parse_imgsize_num(num, name):
try:
num = float(num)
except ValueError:
- msg = "%s is not a floating point number and doesn't have a " \
- "valid unit: %s" % (name, num)
+ msg = (
+ "%s is not a floating point number and doesn't have a "
+ "valid unit: %s" % (name, num)
+ )
raise argparse.ArgumentTypeError(msg)
if unit is None:
unit = ImgUnit.pt
@@ -1445,20 +1976,19 @@ def parse_pagesize_rectarg(string):
string = string[:-2]
if papersizes.get(string.lower()):
string = papersizes[string.lower()]
- if 'x' not in string:
+ if "x" not in string:
# if there is no separating "x" in the string, then the string is
# interpreted as the width
w = parse_num(string, "width")
h = None
else:
- w, h = string.split('x', 1)
+ w, h = string.split("x", 1)
w = parse_num(w, "width")
h = parse_num(h, "height")
if transposed:
w, h = h, w
if w is None and h is None:
- raise argparse.ArgumentTypeError("at least one dimension must be "
- "specified")
+ raise argparse.ArgumentTypeError("at least one dimension must be " "specified")
return w, h
@@ -1468,20 +1998,19 @@ def parse_imgsize_rectarg(string):
string = string[:-2]
if papersizes.get(string.lower()):
string = papersizes[string.lower()]
- if 'x' not in string:
+ if "x" not in string:
# if there is no separating "x" in the string, then the string is
# interpreted as the width
w = parse_imgsize_num(string, "width")
h = None
else:
- w, h = string.split('x', 1)
+ w, h = string.split("x", 1)
w = parse_imgsize_num(w, "width")
h = parse_imgsize_num(h, "height")
if transposed:
w, h = h, w
if w is None and h is None:
- raise argparse.ArgumentTypeError("at least one dimension must be "
- "specified")
+ raise argparse.ArgumentTypeError("at least one dimension must be " "specified")
return w, h
@@ -1490,19 +2019,20 @@ def parse_colorspacearg(string):
if c.name == string:
return c
allowed = ", ".join([c.name for c in Colorspace])
- raise argparse.ArgumentTypeError("Unsupported colorspace: %s. Must be one "
- "of: %s." % (string, allowed))
+ raise argparse.ArgumentTypeError(
+ "Unsupported colorspace: %s. Must be one " "of: %s." % (string, allowed)
+ )
def parse_borderarg(string):
- if ':' in string:
- h, v = string.split(':', 1)
- if h == '':
+ if ":" in string:
+ h, v = string.split(":", 1)
+ if h == "":
raise argparse.ArgumentTypeError("missing value before colon")
- if v == '':
+ if v == "":
raise argparse.ArgumentTypeError("missing value after colon")
else:
- if string == '':
+ if string == "":
raise argparse.ArgumentTypeError("border option cannot be empty")
h, v = string, string
h, v = parse_num(h, "left/right border"), parse_num(v, "top/bottom border")
@@ -1512,28 +2042,41 @@ def parse_borderarg(string):
def input_images(path):
- if path == '-':
+ if path == "-":
# we slurp in all data from stdin because we need to seek in it later
- result = sys.stdin.buffer.read()
+ if PY3:
+ result = sys.stdin.buffer.read()
+ else:
+ result = sys.stdin.read()
if len(result) == 0:
- raise argparse.ArgumentTypeError("\"%s\" is empty" % path)
+ raise argparse.ArgumentTypeError('"%s" is empty' % path)
else:
- try:
- if os.path.getsize(path) == 0:
- raise argparse.ArgumentTypeError("\"%s\" is empty" % path)
- # test-read a byte from it so that we can abort early in case
- # we cannot read data from the file
- with open(path, "rb") as im:
- im.read(1)
- except IsADirectoryError:
- raise argparse.ArgumentTypeError(
- "\"%s\" is a directory" % path)
- except PermissionError:
- raise argparse.ArgumentTypeError(
- "\"%s\" permission denied" % path)
- except FileNotFoundError:
- raise argparse.ArgumentTypeError(
- "\"%s\" does not exist" % path)
+ if PY3:
+ try:
+ if os.path.getsize(path) == 0:
+ raise argparse.ArgumentTypeError('"%s" is empty' % path)
+ # test-read a byte from it so that we can abort early in case
+ # we cannot read data from the file
+ with open(path, "rb") as im:
+ im.read(1)
+ except IsADirectoryError:
+ raise argparse.ArgumentTypeError('"%s" is a directory' % path)
+ except PermissionError:
+ raise argparse.ArgumentTypeError('"%s" permission denied' % path)
+ except FileNotFoundError:
+ raise argparse.ArgumentTypeError('"%s" does not exist' % path)
+ else:
+ try:
+ if os.path.getsize(path) == 0:
+ raise argparse.ArgumentTypeError('"%s" is empty' % path)
+ # test-read a byte from it so that we can abort early in case
+ # we cannot read data from the file
+ with open(path, "rb") as im:
+ im.read(1)
+ except IOError as err:
+ raise argparse.ArgumentTypeError(str(err))
+ except OSError as err:
+ raise argparse.ArgumentTypeError(str(err))
result = path
return result
@@ -1550,8 +2093,9 @@ def parse_panes(string):
if m.name == string.lower():
return m
allowed = ", ".join([m.name for m in PageMode])
- raise argparse.ArgumentTypeError("Unsupported page mode: %s. Must be one "
- "of: %s." % (string, allowed))
+ raise argparse.ArgumentTypeError(
+ "Unsupported page mode: %s. Must be one " "of: %s." % (string, allowed)
+ )
def parse_magnification(string):
@@ -1563,9 +2107,10 @@ def parse_magnification(string):
except ValueError:
pass
allowed = ", ".join([m.name for m in Magnification])
- raise argparse.ArgumentTypeError("Unsupported magnification: %s. Must be "
- "a floating point number or one of: %s." %
- (string, allowed))
+ raise argparse.ArgumentTypeError(
+ "Unsupported magnification: %s. Must be "
+ "a floating point number or one of: %s." % (string, allowed)
+ )
def parse_layout(string):
@@ -1573,8 +2118,9 @@ def parse_layout(string):
if l.name == string.lower():
return l
allowed = ", ".join([l.name for l in PageLayout])
- raise argparse.ArgumentTypeError("Unsupported page layout: %s. Must be "
- "one of: %s." % (string, allowed))
+ raise argparse.ArgumentTypeError(
+ "Unsupported page layout: %s. Must be " "one of: %s." % (string, allowed)
+ )
def valid_date(string):
@@ -1616,14 +2162,14 @@ def valid_date(string):
raise argparse.ArgumentTypeError("cannot parse date: %s" % string)
-def main():
+def main(argv=sys.argv):
rendered_papersizes = ""
for k, v in sorted(papersizes.items()):
rendered_papersizes += " %-8s %s\n" % (papernames[k], v)
parser = argparse.ArgumentParser(
- formatter_class=argparse.RawDescriptionHelpFormatter,
- description='''\
+ formatter_class=argparse.RawDescriptionHelpFormatter,
+ description="""\
Losslessly convert raster images to PDF without re-encoding PNG, JPEG, and
JPEG2000 images. This leads to a lossless conversion of PNG, JPEG and JPEG2000
images with the only added file size coming from the PDF container itself.
@@ -1637,8 +2183,8 @@ or to another program as part of a shell pipe. To directly write the output
into a file, use the -o or --output option.
Options:
-''',
- epilog='''\
+""",
+ epilog="""\
Colorspace:
Currently, the colorspace must be forced for JPEG 2000 images that are not in
the RGB colorspace. Available colorspace options are based on Python Imaging
@@ -1745,78 +2291,113 @@ Examples:
Written by Johannes 'josch' Schauer <josch@mister-muffin.de>
Report bugs at https://gitlab.mister-muffin.de/josch/img2pdf/issues
-''' % rendered_papersizes)
+"""
+ % rendered_papersizes,
+ )
parser.add_argument(
- 'images', metavar='infile', type=input_images, nargs='*',
- help='Specifies the input file(s) in any format that can be read by '
- 'the Python Imaging Library (PIL). If no input images are given, then '
+ "images",
+ metavar="infile",
+ type=input_images,
+ nargs="*",
+ help="Specifies the input file(s) in any format that can be read by "
+ "the Python Imaging Library (PIL). If no input images are given, then "
'a single image is read from standard input. The special filename "-" '
- 'can be used once to read an image from standard input. To read a '
+ "can be used once to read an image from standard input. To read a "
'file in the current directory with the filename "-", pass it to '
- 'img2pdf by explicitly stating its relative path like "./-".')
+ 'img2pdf by explicitly stating its relative path like "./-".',
+ )
parser.add_argument(
- '-v', '--verbose', action="store_true",
- help='Makes the program operate in verbose mode, printing messages on '
- 'standard error.')
+ "-v",
+ "--verbose",
+ action="store_true",
+ help="Makes the program operate in verbose mode, printing messages on "
+ "standard error.",
+ )
parser.add_argument(
- '-V', '--version', action='version', version='%(prog)s '+__version__,
- help="Prints version information and exits.")
+ "-V",
+ "--version",
+ action="version",
+ version="%(prog)s " + __version__,
+ help="Prints version information and exits.",
+ )
outargs = parser.add_argument_group(
- title='General output arguments',
- description='Arguments controlling the output format.')
-
+ title="General output arguments",
+ description="Arguments controlling the output format.",
+ )
+
+ # In Python3 we have to output to sys.stdout.buffer because we write are
+ # bytes and not strings. In certain situations, like when the main
+ # function is wrapped by contextlib.redirect_stdout(), sys.stdout does not
+ # have the buffer attribute. Thus we write to sys.stdout by default and
+ # to sys.stdout.buffer if it exists.
outargs.add_argument(
- '-o', '--output', metavar='out', type=argparse.FileType('wb'),
- default=sys.stdout.buffer,
- help='Makes the program output to a file instead of standard output.')
+ "-o",
+ "--output",
+ metavar="out",
+ type=argparse.FileType("wb"),
+ default=sys.stdout.buffer if hasattr(sys.stdout, "buffer") else sys.stdout,
+ help="Makes the program output to a file instead of standard output.",
+ )
outargs.add_argument(
- '-C', '--colorspace', metavar='colorspace', type=parse_colorspacearg,
- help='''
+ "-C",
+ "--colorspace",
+ metavar="colorspace",
+ type=parse_colorspacearg,
+ help="""
Forces the PIL colorspace. See the epilogue for a list of possible values.
Usually the PDF colorspace would be derived from the color space of the input
image. This option overwrites the automatically detected colorspace from the
input image and thus forces a certain colorspace in the output PDF /ColorSpace
property. This is useful for JPEG 2000 images with a different colorspace than
-RGB.''')
+RGB.""",
+ )
outargs.add_argument(
- '-D', '--nodate', action="store_true",
- help='Suppresses timestamps in the output and thus makes the output '
- 'deterministic between individual runs. You can also manually '
- 'set a date using the --moddate and --creationdate options.')
+ "-D",
+ "--nodate",
+ action="store_true",
+ help="Suppresses timestamps in the output and thus makes the output "
+ "deterministic between individual runs. You can also manually "
+ "set a date using the --moddate and --creationdate options.",
+ )
outargs.add_argument(
- "--without-pdfrw", action="store_true",
+ "--without-pdfrw",
+ action="store_true",
help="By default, img2pdf uses the pdfrw library to create the output "
- "PDF if pdfrw is available. If you want to use the internal PDF "
- "generator of img2pdf even if pdfrw is present, then pass this "
- "option. This can be useful if you want to have unicode metadata "
- "values which pdfrw does not yet support (See "
- "https://github.com/pmaupin/pdfrw/issues/39) or if you want the "
- "PDF code to be more human readable.")
+ "PDF if pdfrw is available. If you want to use the internal PDF "
+ "generator of img2pdf even if pdfrw is present, then pass this "
+ "option. This can be useful if you want to have unicode metadata "
+ "values which pdfrw does not yet support (See "
+ "https://github.com/pmaupin/pdfrw/issues/39) or if you want the "
+ "PDF code to be more human readable.",
+ )
outargs.add_argument(
- "--first-frame-only", action="store_true",
+ "--first-frame-only",
+ action="store_true",
help="By default, img2pdf will convert multi-frame images like "
- "multi-page TIFF or animated GIF images to one page per frame. "
- "This option will only let the first frame of every multi-frame "
- "input image be converted into a page in the resulting PDF."
- )
+ "multi-page TIFF or animated GIF images to one page per frame. "
+ "This option will only let the first frame of every multi-frame "
+ "input image be converted into a page in the resulting PDF.",
+ )
outargs.add_argument(
- "--pillow-limit-break", action="store_true",
+ "--pillow-limit-break",
+ action="store_true",
help="img2pdf uses the Python Imaging Library Pillow to read input "
- "images. Pillow limits the maximum input image size to %d pixels "
- "to prevent decompression bomb denial of service attacks. If "
- "your input image contains more pixels than that, use this "
- "option to disable this safety measure during this run of img2pdf"
- % Image.MAX_IMAGE_PIXELS)
+ "images. Pillow limits the maximum input image size to %d pixels "
+ "to prevent decompression bomb denial of service attacks. If "
+ "your input image contains more pixels than that, use this "
+ "option to disable this safety measure during this run of img2pdf"
+ % Image.MAX_IMAGE_PIXELS,
+ )
sizeargs = parser.add_argument_group(
- title='Image and page size and layout arguments',
- description='''\
+ title="Image and page size and layout arguments",
+ description="""\
Every input image will be placed on its own page. The image size is controlled
by the dpi value of the input image or, if unset or missing, the default dpi of
%.2f. By default, each page will have the same size as the image it shows.
@@ -1858,26 +2439,39 @@ the image size will be calculated from the page size, respecting the border
setting. If the --border option is given while both the --pagesize and
--imgsize options are passed, then the --border option will be ignored.
-''' % default_dpi)
+"""
+ % default_dpi,
+ )
sizeargs.add_argument(
- '-S', '--pagesize', metavar='LxL', type=parse_pagesize_rectarg,
- help='''
+ "-S",
+ "--pagesize",
+ metavar="LxL",
+ type=parse_pagesize_rectarg,
+ help="""
Sets the size of the PDF pages. The short-option is the upper case S because
-it is an mnemonic for being bigger than the image size.''')
+it is an mnemonic for being bigger than the image size.""",
+ )
sizeargs.add_argument(
- '-s', '--imgsize', metavar='LxL', type=parse_imgsize_rectarg,
- help='''
+ "-s",
+ "--imgsize",
+ metavar="LxL",
+ type=parse_imgsize_rectarg,
+ help="""
Sets the size of the images on the PDF pages. In addition, the unit dpi is
allowed which will set the image size as a value of dots per inch. Instead of
a unit, width and height values may also have a percentage sign appended,
indicating a resize of the image by that percentage. The short-option is the
lower case s because it is an mnemonic for being smaller than the page size.
-''')
+""",
+ )
sizeargs.add_argument(
- '-b', '--border', metavar='L[:L]', type=parse_borderarg,
- help='''
+ "-b",
+ "--border",
+ metavar="L[:L]",
+ type=parse_borderarg,
+ help="""
Specifies the minimal distance between the image border and the PDF page
border. This value Is overwritten by explicit values set by --pagesize or
--imgsize. The value will be used when calculating page dimensions from the
@@ -1886,103 +2480,144 @@ as an argument, separated by a colon. One value specifies the minimal border on
all four sides. Two values specify the minimal border on the top/bottom and
left/right, respectively. It is not possible to specify asymmetric borders
because images will always be centered on the page.
-''')
+""",
+ )
sizeargs.add_argument(
- '-f', '--fit', metavar='FIT', type=parse_fitarg,
- default=FitMode.into, help='''
+ "-f",
+ "--fit",
+ metavar="FIT",
+ type=parse_fitarg,
+ default=FitMode.into,
+ help="""
If --imgsize is given, fits the image using these dimensions. Otherwise, fit
the image into the dimensions given by --pagesize. FIT is one of into, fill,
exact, shrink and enlarge. The default value is "into". See the epilogue at the
bottom for a description of the FIT options.
-''')
+""",
+ )
sizeargs.add_argument(
- '-a', '--auto-orient', action="store_true",
- help='''
+ "-a",
+ "--auto-orient",
+ action="store_true",
+ help="""
If both dimensions of the page are given via --pagesize, conditionally swaps
these dimensions such that the page orientation is the same as the orientation
of the input image. If the orientation of a page gets flipped, then so do the
values set via the --border option.
-''')
+""",
+ )
metaargs = parser.add_argument_group(
- title='Arguments setting metadata',
- description='Options handling embedded timestamps, title and author '
- 'information.')
+ title="Arguments setting metadata",
+ description="Options handling embedded timestamps, title and author "
+ "information.",
+ )
metaargs.add_argument(
- '--title', metavar='title', type=str,
- help='Sets the title metadata value')
+ "--title", metavar="title", type=str, help="Sets the title metadata value"
+ )
metaargs.add_argument(
- '--author', metavar='author', type=str,
- help='Sets the author metadata value')
+ "--author", metavar="author", type=str, help="Sets the author metadata value"
+ )
metaargs.add_argument(
- '--creator', metavar='creator', type=str,
- help='Sets the creator metadata value')
+ "--creator", metavar="creator", type=str, help="Sets the creator metadata value"
+ )
metaargs.add_argument(
- '--producer', metavar='producer', type=str,
+ "--producer",
+ metavar="producer",
+ type=str,
default="img2pdf " + __version__,
- help='Sets the producer metadata value '
- '(default is: img2pdf ' + __version__ + ')')
+ help="Sets the producer metadata value "
+ "(default is: img2pdf " + __version__ + ")",
+ )
metaargs.add_argument(
- '--creationdate', metavar='creationdate', type=valid_date,
- help='Sets the UTC creation date metadata value in YYYY-MM-DD or '
- 'YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS format or any format '
- 'understood by python dateutil module or any format understood '
- 'by `date --date`')
+ "--creationdate",
+ metavar="creationdate",
+ type=valid_date,
+ help="Sets the UTC creation date metadata value in YYYY-MM-DD or "
+ "YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS format or any format "
+ "understood by python dateutil module or any format understood "
+ "by `date --date`",
+ )
metaargs.add_argument(
- '--moddate', metavar='moddate', type=valid_date,
- help='Sets the UTC modification date metadata value in YYYY-MM-DD '
- 'or YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS format or any format '
- 'understood by python dateutil module or any format understood '
- 'by `date --date`')
+ "--moddate",
+ metavar="moddate",
+ type=valid_date,
+ help="Sets the UTC modification date metadata value in YYYY-MM-DD "
+ "or YYYY-MM-DDTHH:MM or YYYY-MM-DDTHH:MM:SS format or any format "
+ "understood by python dateutil module or any format understood "
+ "by `date --date`",
+ )
metaargs.add_argument(
- '--subject', metavar='subject', type=str,
- help='Sets the subject metadata value')
+ "--subject", metavar="subject", type=str, help="Sets the subject metadata value"
+ )
metaargs.add_argument(
- '--keywords', metavar='kw', type=str, nargs='+',
- help='Sets the keywords metadata value (can be given multiple times)')
+ "--keywords",
+ metavar="kw",
+ type=str,
+ nargs="+",
+ help="Sets the keywords metadata value (can be given multiple times)",
+ )
viewerargs = parser.add_argument_group(
- title='PDF viewer arguments',
- description='PDF files can specify how they are meant to be '
- 'presented to the user by a PDF viewer')
+ title="PDF viewer arguments",
+ description="PDF files can specify how they are meant to be "
+ "presented to the user by a PDF viewer",
+ )
viewerargs.add_argument(
- '--viewer-panes', metavar="PANES", type=parse_panes,
- help='Instruct the PDF viewer which side panes to show. Valid values '
- 'are "outlines" and "thumbs". It is not possible to specify both '
- 'at the same time.')
+ "--viewer-panes",
+ metavar="PANES",
+ type=parse_panes,
+ help="Instruct the PDF viewer which side panes to show. Valid values "
+ 'are "outlines" and "thumbs". It is not possible to specify both '
+ "at the same time.",
+ )
viewerargs.add_argument(
- '--viewer-initial-page', metavar="NUM", type=int,
- help='Instead of showing the first page, instruct the PDF viewer to '
- 'show the given page instead. Page numbers start with 1.')
+ "--viewer-initial-page",
+ metavar="NUM",
+ type=int,
+ help="Instead of showing the first page, instruct the PDF viewer to "
+ "show the given page instead. Page numbers start with 1.",
+ )
viewerargs.add_argument(
- '--viewer-magnification', metavar="MAG", type=parse_magnification,
- help='Instruct the PDF viewer to open the PDF with a certain zoom '
- 'level. Valid values are either a floating point number giving '
- 'the exact zoom level, "fit" (zoom to fit whole page), "fith" '
- '(zoom to fit page width) and "fitbh" (zoom to fit visible page '
- 'width).')
+ "--viewer-magnification",
+ metavar="MAG",
+ type=parse_magnification,
+ help="Instruct the PDF viewer to open the PDF with a certain zoom "
+ "level. Valid values are either a floating point number giving "
+ 'the exact zoom level, "fit" (zoom to fit whole page), "fith" '
+ '(zoom to fit page width) and "fitbh" (zoom to fit visible page '
+ "width).",
+ )
viewerargs.add_argument(
- '--viewer-page-layout', metavar="LAYOUT", type=parse_layout,
- help='Instruct the PDF viewer how to arrange the pages on the screen. '
- 'Valid values are "single" (display single pages), "onecolumn" '
- '(one continuous column), "twocolumnright" (two continuous '
- 'columns with odd number pages on the right) and "twocolumnleft" '
- '(two continuous columns with odd numbered pages on the left)')
+ "--viewer-page-layout",
+ metavar="LAYOUT",
+ type=parse_layout,
+ help="Instruct the PDF viewer how to arrange the pages on the screen. "
+ 'Valid values are "single" (display single pages), "onecolumn" '
+ '(one continuous column), "twocolumnright" (two continuous '
+ 'columns with odd number pages on the right) and "twocolumnleft" '
+ "(two continuous columns with odd numbered pages on the left)",
+ )
viewerargs.add_argument(
- '--viewer-fit-window', action="store_true",
- help='Instruct the PDF viewer to resize the window to fit the page '
- 'size')
+ "--viewer-fit-window",
+ action="store_true",
+ help="Instruct the PDF viewer to resize the window to fit the page " "size",
+ )
viewerargs.add_argument(
- '--viewer-center-window', action="store_true",
- help='Instruct the PDF viewer to center the PDF viewer window')
+ "--viewer-center-window",
+ action="store_true",
+ help="Instruct the PDF viewer to center the PDF viewer window",
+ )
viewerargs.add_argument(
- '--viewer-fullscreen', action="store_true",
- help='Instruct the PDF viewer to open the PDF in fullscreen mode')
+ "--viewer-fullscreen",
+ action="store_true",
+ help="Instruct the PDF viewer to open the PDF in fullscreen mode",
+ )
- args = parser.parse_args()
+ args = parser.parse_args(argv[1:])
if args.verbose:
logging.basicConfig(level=logging.DEBUG)
@@ -1990,15 +2625,19 @@ values set via the --border option.
if args.pillow_limit_break:
Image.MAX_IMAGE_PIXELS = None
- layout_fun = get_layout_fun(args.pagesize, args.imgsize, args.border,
- args.fit, args.auto_orient)
+ layout_fun = get_layout_fun(
+ args.pagesize, args.imgsize, args.border, args.fit, args.auto_orient
+ )
# if no positional arguments were supplied, read a single image from
# standard input
if len(args.images) == 0:
logging.info("reading image from standard input")
try:
- args.images = [sys.stdin.buffer.read()]
+ if PY3:
+ args.images = [sys.stdin.buffer.read()]
+ else:
+ args.images = [sys.stdin.read()]
except KeyboardInterrupt:
exit(0)
@@ -2007,39 +2646,52 @@ values set via the --border option.
if args.viewer_initial_page is not None:
if args.viewer_initial_page < 1:
parser.print_usage(file=sys.stderr)
- logging.error("%s: error: argument --viewer-initial-page: must be "
- "greater than zero" % parser.prog)
+ logging.error(
+ "%s: error: argument --viewer-initial-page: must be "
+ "greater than zero" % parser.prog
+ )
exit(2)
if args.viewer_initial_page > len(args.images):
parser.print_usage(file=sys.stderr)
- logging.error("%s: error: argument --viewer-initial-page: must be "
- "less than or equal to the total number of pages" %
- parser.prog)
+ logging.error(
+ "%s: error: argument --viewer-initial-page: must be "
+ "less than or equal to the total number of pages" % parser.prog
+ )
exit(2)
try:
convert(
- *args.images, title=args.title, author=args.author,
- creator=args.creator, producer=args.producer,
- creationdate=args.creationdate, moddate=args.moddate,
- subject=args.subject, keywords=args.keywords,
- colorspace=args.colorspace, nodate=args.nodate,
- layout_fun=layout_fun, viewer_panes=args.viewer_panes,
+ *args.images,
+ title=args.title,
+ author=args.author,
+ creator=args.creator,
+ producer=args.producer,
+ creationdate=args.creationdate,
+ moddate=args.moddate,
+ subject=args.subject,
+ keywords=args.keywords,
+ colorspace=args.colorspace,
+ nodate=args.nodate,
+ layout_fun=layout_fun,
+ viewer_panes=args.viewer_panes,
viewer_initial_page=args.viewer_initial_page,
viewer_magnification=args.viewer_magnification,
viewer_page_layout=args.viewer_page_layout,
viewer_fit_window=args.viewer_fit_window,
viewer_center_window=args.viewer_center_window,
- viewer_fullscreen=args.viewer_fullscreen, with_pdfrw=not
- args.without_pdfrw, outputstream=args.output,
- first_frame_only=args.first_frame_only)
+ viewer_fullscreen=args.viewer_fullscreen,
+ with_pdfrw=not args.without_pdfrw,
+ outputstream=args.output,
+ first_frame_only=args.first_frame_only
+ )
except Exception as e:
logging.error("error: " + str(e))
if logging.getLogger().isEnabledFor(logging.DEBUG):
import traceback
+
traceback.print_exc(file=sys.stderr)
exit(1)
-if __name__ == '__main__':
+if __name__ == "__main__":
main()
diff --git a/src/tests/__init__.py b/src/tests/__init__.py
index c9b85e3..807aa84 100644
--- a/src/tests/__init__.py
+++ b/src/tests/__init__.py
@@ -6,7 +6,7 @@ import struct
import sys
import zlib
from PIL import Image
-from io import StringIO, BytesIO
+from io import StringIO, BytesIO, TextIOWrapper
HERE = os.path.dirname(__file__)
@@ -17,6 +17,51 @@ if PY3:
else:
PdfReaderIO = BytesIO
+# Recompressing the image stream makes the comparison robust against output
+# preserving changes in the zlib compress output bitstream
+# (e.g. between different zlib implementations/versions/releases).
+# Without this, some img2pdf 0.3.2 tests fail on Fedora 29/aarch64.
+# See also:
+# https://gitlab.mister-muffin.de/josch/img2pdf/issues/51
+# https://lists.fedoraproject.org/archives/list/devel@lists.fedoraproject.org/thread/R7GD4L5Z6HELCDAL2RDESWR2F3ZXHWVX/
+def recompress_last_stream(bs):
+ length_pos = bs.rindex(b'/Length')
+ li = length_pos + 8
+ lj = bs.index(b' ', li)
+ n = int(bs[li:lj])
+ stream_pos = bs.index(b'\nstream\n', lj)
+ si = stream_pos + 8
+ sj = si + n
+ startx_pos = bs.rindex(b'\nstartxref\n')
+ xi = startx_pos + 11
+ xj = bs.index(b'\n', xi)
+ m = int(bs[xi:xj])
+
+ unc_t = zlib.decompress(bs[si:sj])
+ t = zlib.compress(unc_t)
+
+ new_len = str(len(t)).encode('ascii')
+ u = (lj-li) + n
+ v = len(new_len) + len(t)
+ off = v - u
+
+ rs = (bs[:li] + new_len + bs[lj:si] + t + bs[sj:xi]
+ + str(m+off).encode('ascii') + bs[xj:])
+
+ return rs
+
+def compare_pdf(outx, outy):
+ if b'/FlateDecode' in outx:
+ x = recompress_last_stream(outx)
+ y = recompress_last_stream(outy)
+ if x != y:
+ print('original outx:\n{}\nouty:\n{}\n'.format(outx, outy), file=sys.stderr)
+ print('recompressed outx:\n{}\nouty:\n{}\n'.format(x, y), file=sys.stderr)
+ return False
+ else:
+ if outx != outy:
+ print('original outx:\n{}\nouty:\n{}\n'.format(outx, outy), file=sys.stderr)
+ return True
# convert +set date:create +set date:modify -define png:exclude-chunk=time
@@ -433,6 +478,33 @@ def tiff_header_for_ccitt(width, height, img_size, ccitt_group=4):
)
+class CommandLineTests(unittest.TestCase):
+ def test_main_help(self):
+ if PY3:
+ from contextlib import redirect_stdout
+ f = StringIO()
+ with redirect_stdout(f):
+ try:
+ img2pdf.main(['img2pdf', '--help'])
+ except SystemExit:
+ pass
+ res = f.getvalue()
+ self.assertIn('img2pdf', res)
+ else:
+ # silence output
+ sys_stdout = sys.stdout
+ sys.stdout = BytesIO()
+
+ try:
+ img2pdf.main(['img2pdf', '--help'])
+ except SystemExit:
+ # argparse does sys.exit(0) on --help
+ res = sys.stdout.getvalue()
+ self.assertIn('img2pdf', res)
+ finally:
+ sys.stdout = sys_stdout
+
+
def test_suite():
class TestImg2Pdf(unittest.TestCase):
pass
@@ -642,7 +714,7 @@ def test_suite():
ywriter.trailer = y
xwriter.write(outx)
ywriter.write(outy)
- self.assertEqual(outx.getvalue(), outy.getvalue())
+ self.assertEqual(compare_pdf(outx.getvalue(), outy.getvalue()), True)
# the python-pil version 2.3.0-1ubuntu3 in Ubuntu does not have the
# close() method
try:
@@ -656,4 +728,5 @@ def test_suite():
return unittest.TestSuite((
unittest.makeSuite(TestImg2Pdf),
+ unittest.makeSuite(CommandLineTests),
))
diff --git a/test.sh b/test.sh
new file mode 100755
index 0000000..5b34a30
--- /dev/null
+++ b/test.sh
@@ -0,0 +1,1468 @@
+#!/bin/sh
+
+set -eu
+
+similar()
+{
+ psnr=$(compare -metric PSNR "$1" "$2" null: 2>&1 || true)
+ if [ -z "$psnr" ]; then
+ echo "compare failed"
+ return 1
+ fi
+
+ # PSNR of zero means that they are identical
+ if [ "$psnr" = 0 ]; then
+ echo "images are equal -- don't use similar() but require exactness"
+ exit 2
+ fi
+
+ # The lower PSNR value, the fewer the similarities
+ # The lowest (and worst) value is 1.0
+ min_psnr=50
+ if [ "$min_psnr" != "$( printf "$psnr\n$min_psnr\n" | sort --general-numeric-sort | head --lines=1)" ]; then
+ echo "pdf wrongly rendered"
+ return 1
+ fi
+ return 0
+}
+
+compare_rendered()
+{
+ pdf="$1"
+ img="$2"
+ gsdevice=png16m
+ if [ "$#" -eq 3 ]; then
+ gsdevice="$3"
+ fi
+
+ compare_ghostscript "$pdf" "$img" "$gsdevice"
+
+ compare_poppler "$pdf" "$img"
+
+ compare_mupdf "$pdf" "$img"
+}
+
+compare_ghostscript()
+{
+ pdf="$1"
+ img="$2"
+ gsdevice="$3"
+ gs -dQUIET -dNOPAUSE -dBATCH -sDEVICE="$gsdevice" -r96 -sOutputFile="$tempdir/gs-%00d.png" "$pdf"
+ compare -metric AE "$img" "$tempdir/gs-1.png" null: 2>/dev/null
+ rm "$tempdir/gs-1.png"
+}
+
+compare_poppler()
+{
+ pdf="$1"
+ img="$2"
+ pdftocairo -r 96 -png "$pdf" "$tempdir/poppler"
+ compare -metric AE "$img" "$tempdir/poppler-1.png" null: 2>/dev/null
+ rm "$tempdir/poppler-1.png"
+}
+
+compare_mupdf()
+{
+ pdf="$1"
+ img="$2"
+ mutool draw -o "$tempdir/mupdf.png" -r 96 "$pdf" 2>/dev/null
+ compare -metric AE "$img" "$tempdir/mupdf.png" null: 2>/dev/null
+ rm "$tempdir/mupdf.png"
+}
+
+compare_pdfimages()
+{
+ pdf="$1"
+ img="$2"
+ pdfimages -png "$pdf" "$tempdir/images"
+ compare -metric AE "$img" "$tempdir/images-000.png" null: 2>/dev/null
+ rm "$tempdir/images-000.png"
+}
+
+error()
+{
+ echo test $j failed
+ echo intermediate data is left in $tempdir
+ exit 1
+}
+
+tempdir=$(mktemp --directory --tmpdir img2pdf.XXXXXXXXXX)
+
+trap error EXIT
+
+# we use -strip to remove all timestamps (tIME chunk and exif data)
+convert -size 60x60 \( xc:none -fill red -draw 'circle 30,21 30,3' -gaussian-blur 0x3 \) \
+ \( \( xc:none -fill lime -draw 'circle 39,39 36,57' -gaussian-blur 0x3 \) \
+ \( xc:none -fill blue -draw 'circle 21,39 24,57' -gaussian-blur 0x3 \) \
+ -compose plus -composite \
+ \) -compose plus -composite \
+ -strip \
+ "$tempdir/alpha.png"
+
+convert "$tempdir/alpha.png" -background black -alpha remove -alpha off -strip "$tempdir/normal16.png"
+
+convert "$tempdir/normal16.png" -depth 8 -strip "$tempdir/normal.png"
+
+convert "$tempdir/normal.png" -negate -strip "$tempdir/inverse.png"
+
+convert "$tempdir/normal16.png" -colorspace Gray -depth 16 -strip "$tempdir/gray16.png"
+convert "$tempdir/normal16.png" -colorspace Gray -dither FloydSteinberg -colors 256 -depth 8 -strip "$tempdir/gray8.png"
+convert "$tempdir/normal16.png" -colorspace Gray -dither FloydSteinberg -colors 16 -depth 4 -strip "$tempdir/gray4.png"
+convert "$tempdir/normal16.png" -colorspace Gray -dither FloydSteinberg -colors 4 -depth 2 -strip "$tempdir/gray2.png"
+convert "$tempdir/normal16.png" -colorspace Gray -dither FloydSteinberg -colors 2 -depth 1 -strip "$tempdir/gray1.png"
+
+# use "-define png:exclude-chunk=bkgd" because otherwise, imagemagick will
+# add the background color (white) as an additional entry to the palette
+convert "$tempdir/normal.png" -dither FloydSteinberg -colors 2 -define png:exclude-chunk=bkgd -strip "$tempdir/palette1.png"
+convert "$tempdir/normal.png" -dither FloydSteinberg -colors 4 -define png:exclude-chunk=bkgd -strip "$tempdir/palette2.png"
+convert "$tempdir/normal.png" -dither FloydSteinberg -colors 16 -define png:exclude-chunk=bkgd -strip "$tempdir/palette4.png"
+convert "$tempdir/normal.png" -dither FloydSteinberg -colors 256 -define png:exclude-chunk=bkgd -strip "$tempdir/palette8.png"
+
+cat << END | ( cd "$tempdir"; md5sum --check --status - )
+a99ef2a356c315090b6939fa4ce70516 alpha.png
+0df21ebbce5292654119b17f6e52bc81 gray16.png
+6faee81b8db446caa5004ad71bddcb5b gray1.png
+97e423da517ede069348484a1283aa6c gray2.png
+cbed1b6da5183aec0b86909e82b77c41 gray4.png
+c0df42fdd69ae2a16ad0c23adb39895e gray8.png
+ac6bb850fb5aaee9fa7dcb67525cd0fc inverse.png
+3f3f8579f5054270e79a39e7cc4e89e0 normal16.png
+cbe63b21443af8321b213bde6666951f normal.png
+2f00705cca05fd94406fc39ede4d7322 palette1.png
+6cb250d1915c2af99c324c43ff8286eb palette2.png
+ab7b3d3907a851692ee36f5349ed0b2c palette4.png
+03829af4af8776adf56ba2e68f5b111e palette8.png
+END
+
+# use img2pdfprog environment variable if it is set
+if [ -z ${img2pdfprog+x} ]; then
+ img2pdfprog=src/img2pdf.py
+fi
+
+img2pdf()
+{
+ # we use --without-pdfrw to better "grep" the result and because we
+ # cannot write palette based images otherwise
+ $img2pdfprog --without-pdfrw --producer="" --nodate "$1" > "$2" 2>/dev/null
+}
+
+tests=51 # number of tests
+j=1 # current test
+
+###############################################################################
+echo "Test $j/$tests JPEG"
+
+convert "$tempdir/normal.png" "$tempdir/normal.jpg"
+
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Format: JPEG (Joint Photographic Experts Group JFIF format)$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Mime type: image/jpeg$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Compression: JPEG$'
+
+img2pdf "$tempdir/normal.jpg" "$tempdir/out.pdf"
+
+# We have to use jpegtopnm with the original JPG before being able to compare
+# it with imagemagick because imagemagick will decode the JPG slightly
+# differently than ghostscript, poppler and mupdf do it.
+# We have to use jpegtopnm and cannot use djpeg because the latter produces
+# slightly different results as well when called like this:
+# djpeg -dct int -pnm "$tempdir/normal.jpg" > "$tempdir/normal.pnm"
+# An alternative way to compare the JPG would be to require a different DCT
+# method when decoding by setting -define jpeg:dct-method=ifast in the
+# compare command.
+jpegtopnm -dct int "$tempdir/normal.jpg" > "$tempdir/normal.pnm" 2>/dev/null
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal.pnm"
+
+pdfimages -j "$tempdir/out.pdf" "$tempdir/images"
+cmp "$tempdir/normal.jpg" "$tempdir/images-000.jpg"
+rm "$tempdir/images-000.jpg"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /DCTDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/normal.jpg" "$tempdir/normal.pnm" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests JPEG (90° rotated)"
+
+convert "$tempdir/normal.png" "$tempdir/normal.jpg"
+exiftool -overwrite_original -all= "$tempdir/normal.jpg" -n >/dev/null
+exiftool -overwrite_original -Orientation=6 -XResolution=96 -YResolution=96 -n "$tempdir/normal.jpg" >/dev/null
+
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Format: JPEG (Joint Photographic Experts Group JFIF format)$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Mime type: image/jpeg$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Compression: JPEG$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ exif:Orientation: 6$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ exif:ResolutionUnit: 2$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ exif:XResolution: 96/1$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ exif:YResolution: 96/1$'
+
+img2pdf "$tempdir/normal.jpg" "$tempdir/out.pdf"
+
+# We have to use jpegtopnm with the original JPG before being able to compare
+# it with imagemagick because imagemagick will decode the JPG slightly
+# differently than ghostscript, poppler and mupdf do it.
+# We have to use jpegtopnm and cannot use djpeg because the latter produces
+# slightly different results as well when called like this:
+# djpeg -dct int -pnm "$tempdir/normal.jpg" > "$tempdir/normal.pnm"
+# An alternative way to compare the JPG would be to require a different DCT
+# method when decoding by setting -define jpeg:dct-method=ifast in the
+# compare command.
+jpegtopnm -dct int "$tempdir/normal.jpg" > "$tempdir/normal.pnm" 2>/dev/null
+convert -rotate "90" "$tempdir/normal.pnm" "$tempdir/normal_rotated.png"
+#convert -rotate "0" "$tempdir/normal.pnm" "$tempdir/normal_rotated.png"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal_rotated.png"
+
+pdfimages -j "$tempdir/out.pdf" "$tempdir/images"
+cmp "$tempdir/normal.jpg" "$tempdir/images-000.jpg"
+rm "$tempdir/images-000.jpg"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /DCTDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Rotate 90$' "$tempdir/out.pdf"
+
+rm "$tempdir/normal.jpg" "$tempdir/normal.pnm" "$tempdir/out.pdf" "$tempdir/normal_rotated.png"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests JPEG CMYK"
+
+convert "$tempdir/normal.png" -colorspace cmyk "$tempdir/normal.jpg"
+
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Format: JPEG (Joint Photographic Experts Group JFIF format)$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Mime type: image/jpeg$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Colorspace: CMYK$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Type: ColorSeparation$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jpg" | grep --quiet '^ Compression: JPEG$'
+
+img2pdf "$tempdir/normal.jpg" "$tempdir/out.pdf"
+
+gs -dQUIET -dNOPAUSE -dBATCH -sDEVICE=tiff32nc -r96 -sOutputFile="$tempdir/gs-%00d.tiff" "$tempdir/out.pdf"
+similar "$tempdir/normal.jpg" "$tempdir/gs-1.tiff"
+rm "$tempdir/gs-1.tiff"
+
+# not testing with poppler as it cannot write CMYK images
+
+mutool draw -o "$tempdir/mupdf.pam" -r 96 -c cmyk "$pdf" 2>/dev/null
+similar "$tempdir/normal.jpg" "$tempdir/mupdf.pam"
+rm "$tempdir/mupdf.pam"
+
+pdfimages -j "$tempdir/out.pdf" "$tempdir/images"
+cmp "$tempdir/normal.jpg" "$tempdir/images-000.jpg"
+rm "$tempdir/images-000.jpg"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceCMYK$' "$tempdir/out.pdf"
+grep --quiet '^ /Decode \[ 1 0 1 0 1 0 1 0 \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /DCTDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/normal.jpg" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests JPEG2000"
+
+convert "$tempdir/normal.png" "$tempdir/normal.jp2"
+
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Format: JP2 (JPEG-2000 File Format Syntax)$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Mime type: image/jp2$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.jp2" | grep --quiet '^ Compression: JPEG2000$'
+
+img2pdf "$tempdir/normal.jp2" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal.jp2"
+
+pdfimages -jp2 "$tempdir/out.pdf" "$tempdir/images"
+cmp "$tempdir/normal.jp2" "$tempdir/images-000.jp2"
+rm "$tempdir/images-000.jp2"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /JPXDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/normal.jp2" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+#echo Test JPEG2000 CMYK
+#
+# cannot test because imagemagick does not support JPEG2000 CMYK
+
+###############################################################################
+echo "Test $j/$tests PNG RGB8"
+
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 8$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ png:IHDR.bit_depth: 8$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ png:IHDR.color-type-orig: 2$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ png:IHDR.color_type: 2 (Truecolor)$'
+identify -verbose "$tempdir/normal.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/normal.png" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal.png"
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/normal.png"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /Colors 3$' "$tempdir/out.pdf"
+grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG RGB16"
+
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 16$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ png:IHDR.bit_depth: 16$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ png:IHDR.color-type-orig: 2$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ png:IHDR.color_type: 2 (Truecolor)$'
+identify -verbose "$tempdir/normal16.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/normal16.png" "$tempdir/out.pdf"
+
+compare_ghostscript "$tempdir/out.pdf" "$tempdir/normal16.png" tiff48nc
+
+# poppler outputs 8-bit RGB so the comparison will not be exact
+pdftocairo -r 96 -png "$tempdir/out.pdf" "$tempdir/poppler"
+similar "$tempdir/normal16.png" "$tempdir/poppler-1.png"
+rm "$tempdir/poppler-1.png"
+
+# pdfimages is unable to write 16 bit output
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 16$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 16$' "$tempdir/out.pdf"
+grep --quiet '^ /Colors 3$' "$tempdir/out.pdf"
+grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG RGBA8"
+
+convert "$tempdir/alpha.png" -depth 8 -strip "$tempdir/alpha8.png"
+
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Type: TrueColorAlpha$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 8$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ png:IHDR.bit_depth: 8$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ png:IHDR.color-type-orig: 6$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ png:IHDR.color_type: 6 (RGBA)$'
+identify -verbose "$tempdir/alpha8.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/alpha8.png" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha8.png"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG RGBA16"
+
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Type: TrueColorAlpha$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 16$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ png:IHDR.bit_depth: 16$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ png:IHDR.color-type-orig: 6$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ png:IHDR.color_type: 6 (RGBA)$'
+identify -verbose "$tempdir/alpha.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/alpha.png" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG Gray8 Alpha"
+
+convert "$tempdir/alpha.png" -colorspace Gray -dither FloydSteinberg -colors 256 -depth 8 -strip "$tempdir/alpha_gray8.png"
+
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Colorspace: Gray$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Type: GrayscaleAlpha$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 8$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ png:IHDR.bit_depth: 8$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ png:IHDR.color-type-orig: 4$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ png:IHDR.color_type: 4 (GrayAlpha)$'
+identify -verbose "$tempdir/alpha_gray8.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/alpha_gray8.png" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha_gray8.png"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG Gray16 Alpha"
+
+convert "$tempdir/alpha.png" -colorspace Gray -depth 16 -strip "$tempdir/alpha_gray16.png"
+
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Colorspace: Gray$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Type: GrayscaleAlpha$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 16$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ png:IHDR.bit_depth: 16$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ png:IHDR.color-type-orig: 4$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ png:IHDR.color_type: 4 (GrayAlpha)$'
+identify -verbose "$tempdir/alpha_gray16.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/alpha_gray16.png" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha_gray16.png"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests PNG interlaced"
+
+convert "$tempdir/normal.png" -interlace PNG -strip "$tempdir/interlace.png"
+
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 8$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ png:IHDR.bit_depth: 8$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ png:IHDR.color-type-orig: 2$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ png:IHDR.color_type: 2 (Truecolor)$'
+identify -verbose "$tempdir/interlace.png" | grep --quiet '^ png:IHDR.interlace_method: 1 (Adam7 method)$'
+
+img2pdf "$tempdir/interlace.png" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal.png"
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/normal.png"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /Colors 3$' "$tempdir/out.pdf"
+grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/interlace.png" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+for i in 1 2 4 8; do
+ echo "Test $j/$tests PNG Gray$i"
+
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Mime type: image/png$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Colorspace: Gray$'
+ if [ "$i" -eq 1 ]; then
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Type: Bilevel$'
+ else
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Type: Grayscale$'
+ fi
+ if [ "$i" -eq 8 ]; then
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet "^ Depth: 8-bit$"
+ else
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet "^ Depth: 8/$i-bit$"
+ fi
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ Compression: Zip$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet "^ png:IHDR.bit-depth-orig: $i$"
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet "^ png:IHDR.bit_depth: $i$"
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ png:IHDR.color-type-orig: 0$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ png:IHDR.color_type: 0 (Grayscale)$'
+ identify -verbose "$tempdir/gray$i.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+ img2pdf "$tempdir/gray$i.png" "$tempdir/out.pdf"
+
+ compare_rendered "$tempdir/out.pdf" "$tempdir/gray$i.png" pnggray
+
+ compare_pdfimages "$tempdir/out.pdf" "$tempdir/gray$i.png"
+
+ grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+ grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+ grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+ grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+ grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+ rm "$tempdir/out.pdf"
+ j=$((j+1))
+done
+
+###############################################################################
+echo "Test $j/$tests PNG Gray16"
+
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Mime type: image/png$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Colorspace: Gray$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Type: Grayscale$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ png:IHDR.bit-depth-orig: 16$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ png:IHDR.bit_depth: 16$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ png:IHDR.color-type-orig: 0$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ png:IHDR.color_type: 0 (Grayscale)$'
+identify -verbose "$tempdir/gray16.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+img2pdf "$tempdir/gray16.png" "$tempdir/out.pdf"
+
+# ghostscript outputs 8-bit grayscale, so the comparison will not be exact
+gs -dQUIET -dNOPAUSE -dBATCH -sDEVICE=pnggray -r96 -sOutputFile="$tempdir/gs-%00d.png" "$tempdir/out.pdf"
+similar "$tempdir/gray16.png" "$tempdir/gs-1.png"
+rm "$tempdir/gs-1.png"
+
+# poppler outputs 8-bit grayscale so the comparison will not be exact
+pdftocairo -r 96 -png "$tempdir/out.pdf" "$tempdir/poppler"
+similar "$tempdir/gray16.png" "$tempdir/poppler-1.png"
+rm "$tempdir/poppler-1.png"
+
+# pdfimages outputs 8-bit grayscale so the comparison will not be exact
+pdfimages -png "$tempdir/out.pdf" "$tempdir/images"
+similar "$tempdir/gray16.png" "$tempdir/images-000.png"
+rm "$tempdir/images-000.png"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 16$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 16$' "$tempdir/out.pdf"
+grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+for i in 1 2 4 8; do
+ echo "Test $j/$tests PNG Palette$i"
+
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Format: PNG (Portable Network Graphics)$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Mime type: image/png$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Colorspace: sRGB$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Type: Palette$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Depth: 8-bit$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ Compression: Zip$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet "^ png:IHDR.bit-depth-orig: $i$"
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet "^ png:IHDR.bit_depth: $i$"
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ png:IHDR.color-type-orig: 3$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ png:IHDR.color_type: 3 (Indexed)$'
+ identify -verbose "$tempdir/palette$i.png" | grep --quiet '^ png:IHDR.interlace_method: 0 (Not interlaced)$'
+
+ img2pdf "$tempdir/palette$i.png" "$tempdir/out.pdf"
+
+ compare_rendered "$tempdir/out.pdf" "$tempdir/palette$i.png"
+
+ # pdfimages cannot export palette based images
+
+ grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /ColorSpace \[ /Indexed /DeviceRGB ' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+ grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+ grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+ grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+ grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+ rm "$tempdir/out.pdf"
+ j=$((j+1))
+done
+
+###############################################################################
+echo "Test $j/$tests GIF transparent"
+
+convert "$tempdir/alpha.png" "$tempdir/alpha.gif"
+
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Format: GIF (CompuServe graphics interchange format)$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Mime type: image/gif$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Type: PaletteAlpha$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Colormap entries: 256$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha.gif" | grep --quiet '^ Compression: LZW$'
+
+img2pdf "$tempdir/alpha.gif" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha.gif"
+j=$((j+1))
+
+###############################################################################
+for i in 1 2 4 8; do
+ echo "Test $j/$tests GIF Palette$i"
+
+ convert "$tempdir/palette$i.png" "$tempdir/palette$i.gif"
+
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Format: GIF (CompuServe graphics interchange format)$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Mime type: image/gif$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Colorspace: sRGB$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Type: Palette$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Depth: 8-bit$'
+ case $i in
+ 1) identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Colormap entries: 2$';;
+ 2) identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Colormap entries: 4$';;
+ 4) identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Colormap entries: 16$';;
+ 8) identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Colormap entries: 256$';;
+ esac
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.gif" | grep --quiet '^ Compression: LZW$'
+
+ img2pdf "$tempdir/palette$i.gif" "$tempdir/out.pdf"
+
+ compare_rendered "$tempdir/out.pdf" "$tempdir/palette$i.png"
+
+ # pdfimages cannot export palette based images
+
+ grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /ColorSpace \[ /Indexed /DeviceRGB ' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+ grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+ grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+ grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+ grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+ rm "$tempdir/out.pdf" "$tempdir/palette$i.gif"
+ j=$((j+1))
+done
+
+###############################################################################
+echo "Test $j/$tests GIF animation"
+
+convert "$tempdir/normal.png" "$tempdir/inverse.png" -strip "$tempdir/animation.gif"
+
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Format: GIF (CompuServe graphics interchange format)$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Mime type: image/gif$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Type: Palette$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Colormap entries: 256$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/animation.gif[0]" | grep --quiet '^ Compression: LZW$'
+
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Format: GIF (CompuServe graphics interchange format)$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Mime type: image/gif$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Type: Palette$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Colormap entries: 256$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Compression: LZW$'
+identify -verbose "$tempdir/animation.gif[1]" | grep --quiet '^ Scene: 1$'
+
+img2pdf "$tempdir/animation.gif" "$tempdir/out.pdf"
+
+if [ "$(pdfinfo "$tempdir/out.pdf" | awk '/Pages:/ {print $2}')" != 2 ]; then
+ echo "pdf does not have 2 pages"
+ exit 1
+fi
+
+pdfseparate "$tempdir/out.pdf" "$tempdir/page-%d.pdf"
+rm "$tempdir/out.pdf"
+
+for page in 1 2; do
+ compare_rendered "$tempdir/page-$page.pdf" "$tempdir/animation.gif[$((page-1))]"
+
+ # pdfimages cannot export palette based images
+
+ # We cannot grep the PDF metadata here, because the page was
+ # rewritten into a non-greppable format by pdfseparate. but that's
+ # okay, because we already grepped single pages before and multipage
+ # PDF should not be different.
+
+ rm "$tempdir/page-$page.pdf"
+done
+
+rm "$tempdir/animation.gif"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF float"
+
+convert "$tempdir/normal.png" -depth 32 -define quantum:format=floating-point "$tempdir/float.tiff"
+
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Depth: 32/8-bit$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ quantum:format: floating-point$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/float.tiff" | grep --quiet '^ tiff:photometric: RGB$'
+
+img2pdf "$tempdir/float.tiff" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/float.tiff"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CMYK8"
+
+convert "$tempdir/normal.png" -colorspace cmyk "$tempdir/cmyk8.tiff"
+
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Colorspace: CMYK$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Type: ColorSeparation$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/cmyk8.tiff" | grep --quiet '^ tiff:photometric: separated$'
+
+img2pdf "$tempdir/cmyk8.tiff" "$tempdir/out.pdf"
+
+compare_ghostscript "$tempdir/out.pdf" "$tempdir/cmyk8.tiff" tiff32nc
+
+# not testing with poppler as it cannot write CMYK images
+
+mutool draw -o "$tempdir/mupdf.pam" -r 96 -c cmyk "$pdf" 2>/dev/null
+compare -metric AE "$tempdir/cmyk8.tiff" "$tempdir/mupdf.pam" null: 2>/dev/null
+rm "$tempdir/mupdf.pam"
+
+pdfimages -tiff "$tempdir/out.pdf" "$tempdir/images"
+compare -metric AE "$tempdir/cmyk8.tiff" "$tempdir/images-000.tif" null: 2>/dev/null
+rm "$tempdir/images-000.tif"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceCMYK$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/cmyk8.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CMYK16"
+
+convert "$tempdir/normal.png" -depth 16 -colorspace cmyk "$tempdir/cmyk16.tiff"
+
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Colorspace: CMYK$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Type: ColorSeparation$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/cmyk16.tiff" | grep --quiet '^ tiff:photometric: separated$'
+
+# PIL is unable to read 16 bit CMYK images
+img2pdf "$tempdir/cmyk16.gif" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/cmyk16.tiff"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF RGB8"
+
+convert "$tempdir/normal.png" "$tempdir/normal.tiff"
+
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/normal.tiff" | grep --quiet '^ tiff:photometric: RGB$'
+
+img2pdf "$tempdir/normal.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/normal.tiff" tiff24nc
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/normal.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceRGB$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+grep --quiet '^ /Colors 3$' "$tempdir/out.pdf"
+grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/normal.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF RGBA8"
+
+convert "$tempdir/alpha.png" -depth 8 -strip "$tempdir/alpha8.tiff"
+
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Type: TrueColorAlpha$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ tiff:alpha: unassociated$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/alpha8.tiff" | grep --quiet '^ tiff:photometric: RGB$'
+
+img2pdf "$tempdir/alpha8.tiff" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha8.tiff"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF RGBA16"
+
+convert "$tempdir/alpha.png" -strip "$tempdir/alpha16.tiff"
+
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Type: TrueColorAlpha$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Depth: 16-bit$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ tiff:alpha: unassociated$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/alpha16.tiff" | grep --quiet '^ tiff:photometric: RGB$'
+
+img2pdf "$tempdir/alpha16.tiff" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/alpha16.tiff"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF Gray1"
+
+convert "$tempdir/gray1.png" -depth 1 "$tempdir/gray1.tiff"
+
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Colorspace: Gray$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Type: Bilevel$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Depth: 1-bit$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/gray1.tiff" | grep --quiet '^ tiff:photometric: min-is-black$'
+
+img2pdf "$tempdir/gray1.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/gray1.png" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/gray1.png"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 true$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/gray1.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+for i in 2 4 8; do
+ echo "Test $j/$tests TIFF Gray$i"
+
+ convert "$tempdir/gray$i.png" -depth $i "$tempdir/gray$i.tiff"
+
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Mime type: image/tiff$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Colorspace: Gray$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Type: Grayscale$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Endianess: LSB$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet "^ Depth: $i-bit$"
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ Compression: Zip$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ tiff:endian: lsb$'
+ identify -verbose "$tempdir/gray$i.tiff" | grep --quiet '^ tiff:photometric: min-is-black$'
+
+ img2pdf "$tempdir/gray$i.tiff" "$tempdir/out.pdf"
+
+ compare_rendered "$tempdir/out.pdf" "$tempdir/gray$i.png" pnggray
+
+ compare_pdfimages "$tempdir/out.pdf" "$tempdir/gray$i.png"
+
+ # When saving a PNG, PIL will store it as 8-bit data
+ grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+ grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent 8$' "$tempdir/out.pdf"
+ grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+ grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+ grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+ grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+ grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+ rm "$tempdir/gray$i.tiff" "$tempdir/out.pdf"
+ j=$((j+1))
+done
+
+################################################################################
+echo "Test $j/$tests TIFF Gray16"
+
+convert "$tempdir/gray16.png" -depth 16 "$tempdir/gray16.tiff"
+
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Colorspace: Gray$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Type: Grayscale$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet "^ Depth: 16-bit$"
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/gray16.tiff" | grep --quiet '^ tiff:photometric: min-is-black$'
+
+img2pdf "$tempdir/gray16.tiff" /dev/null && rc=$? || rc=$?
+if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+fi
+
+rm "$tempdir/gray16.tiff"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF multipage"
+
+convert "$tempdir/normal.png" "$tempdir/inverse.png" -strip "$tempdir/multipage.tiff"
+
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/multipage.tiff[0]" | grep --quiet '^ tiff:photometric: RGB$'
+
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Mime type: image/tiff$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Geometry: 60x60+0+0$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Colorspace: sRGB$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Type: TrueColor$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Endianess: LSB$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Depth: 8-bit$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Page geometry: 60x60+0+0$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Compression: Zip$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ tiff:alpha: unspecified$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ tiff:endian: lsb$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ tiff:photometric: RGB$'
+identify -verbose "$tempdir/multipage.tiff[1]" | grep --quiet '^ Scene: 1$'
+
+img2pdf "$tempdir/multipage.tiff" "$tempdir/out.pdf"
+
+if [ "$(pdfinfo "$tempdir/out.pdf" | awk '/Pages:/ {print $2}')" != 2 ]; then
+ echo "pdf does not have 2 pages"
+ exit 1
+fi
+
+pdfseparate "$tempdir/out.pdf" "$tempdir/page-%d.pdf"
+rm "$tempdir/out.pdf"
+
+for page in 1 2; do
+ compare_rendered "$tempdir/page-$page.pdf" "$tempdir/multipage.tiff[$((page-1))]"
+
+ compare_pdfimages "$tempdir/page-$page.pdf" "$tempdir/multipage.tiff[$((page-1))]"
+
+ # We cannot grep the PDF metadata here, because the page was
+ # rewritten into a non-greppable format by pdfseparate. but that's
+ # okay, because we already grepped single pages before and multipage
+ # PDF should not be different.
+
+ rm "$tempdir/page-$page.pdf"
+done
+
+rm "$tempdir/multipage.tiff"
+j=$((j+1))
+
+###############################################################################
+for i in 1 2 4 8; do
+ echo "Test $j/$tests TIFF Palette$i"
+
+ convert "$tempdir/palette$i.png" "$tempdir/palette$i.tiff"
+
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Mime type: image/tiff$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Colorspace: sRGB$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Type: Palette$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Endianess: LSB$'
+ if [ "$i" -eq 8 ]; then
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet "^ Depth: 8-bit$"
+ else
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet "^ Depth: $i/8-bit$"
+ fi
+ case $i in
+ 1) identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Colormap entries: 2$';;
+ 2) identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Colormap entries: 4$';;
+ 4) identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Colormap entries: 16$';;
+ 8) identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Colormap entries: 256$';;
+ esac
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ Compression: Zip$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ tiff:endian: lsb$'
+ identify -verbose "$tempdir/palette$i.tiff" | grep --quiet '^ tiff:photometric: palette$'
+
+ img2pdf "$tempdir/palette$i.tiff" "$tempdir/out.pdf"
+
+ compare_rendered "$tempdir/out.pdf" "$tempdir/palette$i.png"
+
+ # pdfimages cannot export palette based images
+
+ grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /ColorSpace \[ /Indexed /DeviceRGB ' "$tempdir/out.pdf"
+ grep --quiet '^ /BitsPerComponent '"$i"'$' "$tempdir/out.pdf"
+ grep --quiet '^ /Colors 1$' "$tempdir/out.pdf"
+ grep --quiet '^ /Predictor 15$' "$tempdir/out.pdf"
+ grep --quiet '^ /Filter /FlateDecode$' "$tempdir/out.pdf"
+ grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+ grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+ rm "$tempdir/out.pdf"
+
+ rm "$tempdir/palette$i.tiff"
+ j=$((j+1))
+done
+
+###############################################################################
+for i in 12 14 16; do
+ echo "Test $j/$tests TIFF RGB$i"
+
+ convert "$tempdir/normal16.png" -depth "$i" "$tempdir/normal$i.tiff"
+
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Format: TIFF (Tagged Image File Format)$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Mime type: image/tiff$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Colorspace: sRGB$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Type: TrueColor$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Endianess: LSB$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet "^ Depth: $i-bit$"
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Page geometry: 60x60+0+0$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ Compression: Zip$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ tiff:alpha: unspecified$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ tiff:endian: lsb$'
+ identify -verbose "$tempdir/normal$i.tiff" | grep --quiet '^ tiff:photometric: RGB$'
+
+ img2pdf "$tempdir/normal$i.tiff" /dev/null && rc=$? || rc=$?
+ if [ "$rc" -eq 0 ]; then
+ echo needs to fail here
+ exit 1
+ fi
+
+ rm "$tempdir/normal$i.tiff"
+ j=$((j+1))
+done
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, little endian, msb-to-lsb, min-is-white"
+
+convert "$tempdir/gray1.png" -compress group4 -define tiff:endian=lsb -define tiff:fill-order=msb -define quantum:polarity=min-is-white "$tempdir/group4.tiff"
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-white'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: msb-to-lsb'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: LSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: lsb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-white'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 false$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, big endian, msb-to-lsb, min-is-white"
+
+convert "$tempdir/gray1.png" -compress group4 -define tiff:endian=msb -define tiff:fill-order=msb -define quantum:polarity=min-is-white "$tempdir/group4.tiff"
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-white'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: msb-to-lsb'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: MSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: msb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-white'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 false$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, big endian, lsb-to-msb, min-is-white"
+
+convert "$tempdir/gray1.png" -compress group4 -define tiff:endian=msb -define tiff:fill-order=lsb -define quantum:polarity=min-is-white "$tempdir/group4.tiff"
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-white'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: lsb-to-msb'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: MSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: msb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-white'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 false$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, little endian, msb-to-lsb, min-is-black"
+
+# We create a min-is-black group4 tiff with PIL because it creates these by
+# default (and without the option to do otherwise) whereas imagemagick only
+# became able to do it through commit 00730551f0a34328685c59d0dde87dd9e366103a
+# See https://www.imagemagick.org/discourse-server/viewtopic.php?f=1&t=34605
+python3 -c 'from PIL import Image;Image.open("'"$tempdir/gray1.png"'").save("'"$tempdir/group4.tiff"'",format="TIFF",compression="group4")'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-black'
+# PIL doesn't set those
+#tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: msb-to-lsb'
+#tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: LSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: lsb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-black'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 true$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, without fillorder, samples/pixel, bits/sample"
+
+convert "$tempdir/gray1.png" -compress group4 -define tiff:endian=lsb -define tiff:fill-order=msb -define quantum:polarity=min-is-white "$tempdir/group4.tiff"
+# remove BitsPerSample (258)
+tiffset -u 258 "$tempdir/group4.tiff"
+# remove FillOrder (266)
+tiffset -u 266 "$tempdir/group4.tiff"
+# remove SamplesPerPixel (277)
+tiffset -u 277 "$tempdir/group4.tiff"
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1' && exit 1
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-white'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: msb-to-lsb' && exit 1
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1' && exit 1
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: LSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: lsb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-white'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 false$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+###############################################################################
+echo "Test $j/$tests TIFF CCITT Group4, without rows-per-strip"
+
+convert "$tempdir/gray1.png" -compress group4 -define tiff:endian=lsb -define tiff:fill-order=msb -define quantum:polarity=min-is-white -define tiff:rows-per-strip=4294967295 "$tempdir/group4.tiff"
+# remove RowsPerStrip (278)
+tiffset -u 278 "$tempdir/group4.tiff"
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Bits/Sample: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Compression Scheme: CCITT Group 4'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Photometric Interpretation: min-is-white'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'FillOrder: msb-to-lsb'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Samples/Pixel: 1'
+tiffinfo "$tempdir/group4.tiff" | grep --quiet 'Rows/Strip:' && exit 1
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Type: Bilevel'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Endianess: LSB'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Depth: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'gray: 1-bit'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'Compression: Group4'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:endian: lsb'
+identify -verbose "$tempdir/group4.tiff" | grep --quiet 'tiff:photometric: min-is-white'
+
+img2pdf "$tempdir/group4.tiff" "$tempdir/out.pdf"
+
+compare_rendered "$tempdir/out.pdf" "$tempdir/group4.tiff" pnggray
+
+compare_pdfimages "$tempdir/out.pdf" "$tempdir/group4.tiff"
+
+grep --quiet '^45.0000 0 0 45.0000 0.0000 0.0000 cm$' "$tempdir/out.pdf"
+grep --quiet '^ /BitsPerComponent 1$' "$tempdir/out.pdf"
+grep --quiet '^ /ColorSpace /DeviceGray$' "$tempdir/out.pdf"
+grep --quiet '^ /BlackIs1 false$' "$tempdir/out.pdf"
+grep --quiet '^ /Columns 60$' "$tempdir/out.pdf"
+grep --quiet '^ /K -1$' "$tempdir/out.pdf"
+grep --quiet '^ /Rows 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Filter \[ /CCITTFaxDecode \]$' "$tempdir/out.pdf"
+grep --quiet '^ /Height 60$' "$tempdir/out.pdf"
+grep --quiet '^ /Width 60$' "$tempdir/out.pdf"
+
+rm "$tempdir/group4.tiff" "$tempdir/out.pdf"
+j=$((j+1))
+
+rm "$tempdir/alpha.png" "$tempdir/normal.png" "$tempdir/inverse.png" "$tempdir/palette1.png" "$tempdir/palette2.png" "$tempdir/palette4.png" "$tempdir/palette8.png" "$tempdir/gray8.png" "$tempdir/normal16.png" "$tempdir/gray16.png" "$tempdir/gray4.png" "$tempdir/gray2.png" "$tempdir/gray1.png"
+rmdir "$tempdir"
+
+trap - EXIT