From efb70042e8545e1e6d7195cb07ad4954908a6c5a Mon Sep 17 00:00:00 2001 From: Johannes 'josch' Schauer Date: Wed, 10 Jun 2020 00:09:11 +0200 Subject: [PATCH] if img2pdf is available, try opening input with it and convert to PDF if necessary (closes: #3) --- plakativ.py | 30 +++++++++++++++++++++++++++++- setup.py | 2 +- 2 files changed, 30 insertions(+), 2 deletions(-) diff --git a/plakativ.py b/plakativ.py index cf95497..633689c 100755 --- a/plakativ.py +++ b/plakativ.py @@ -21,6 +21,15 @@ import sys import argparse import os.path import platform +from enum import Enum +from io import BytesIO + +have_img2pdf = True +try: + import img2pdf +except ImportError: + have_img2pdf = False + VERSION = "0.2" @@ -245,7 +254,26 @@ def complex_cover(n, m, x, y): class Plakativ: def __init__(self, infile, pagenr=0): - self.doc = fitz.open(infile) + self.doc = None + if have_img2pdf: + # if we have img2pdf available we can encapsulate a raster image + # into a PDF container + try: + data = img2pdf.convert(infile) + except img2pdf.ImageOpenError: + # img2pdf cannot handle this + pass + else: + stream = BytesIO() + stream.write(data) + self.doc = fitz.open(stream=stream, filetype="application/pdf") + if self.doc is None: + # either we didn't have img2pdf or opening the input with img2pdf + # failed + if hasattr(infile, "read"): + self.doc = fitz.open(stream=infile, filetype="application/pdf") + else: + self.doc = fitz.open(filename=infile) self.pagenr = pagenr # set page number -- first page is 0 diff --git a/setup.py b/setup.py index 2de551b..806b4c2 100644 --- a/setup.py +++ b/setup.py @@ -35,7 +35,7 @@ setup( test_suite="tests.test_suite", zip_safe=True, include_package_data=True, - install_requires=["PyMuPDF"], + install_requires=["PyMuPDF", "img2pdf"], entry_points={ "setuptools.installation": ["eggsecutable = plakativ:main"], "console_scripts": ["plakativ = plakativ:main"],