Coverage for pyquickhelper/imghelper/img_export.py: 96%
25 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
« prev ^ index » next coverage.py v7.2.7, created at 2023-06-03 02:21 +0200
1"""
2@file
3@brief Tools to convert images.
4"""
5import glob
6import os
9def images2pdf(images, output, fLOG=None):
10 """
11 Merges multiples images into one single pdf.
12 Relies on :epkg:`img2pdf`. If an image name contains
13 ``'*'``, the function assumes it is a pattern and
14 uses :epkg:`*py:glob`.
16 :param images: images to merge, it can be a comma separated values
17 :param output: output filename or stream
18 :param fLOG: logging function
20 .. cmdref::
21 :title: Merge images into PDF
22 :cmd: -m pyquickhelper images2pdf --help
24 Merges one or several images into a single
25 PDF document.
26 """
27 from img2pdf import convert
29 if isinstance(images, str):
30 if ',' in images:
31 images = images.split(',')
32 else:
33 images = [images] # pragma: no cover
34 elif not isinstance(images, list):
35 raise TypeError("Images must be a list.") # pragma: no cover
37 all_images = []
38 for img in images:
39 if "*" in img:
40 names = glob.glob(img)
41 all_images.extend(names)
42 else:
43 all_images.append(img)
45 if fLOG is not None: # pragma: no cover
46 for i, img in enumerate(all_images):
47 fLOG(f"[images2pdf] {i + 1}/{len(all_images)} '{img}'")
49 if isinstance(output, str):
50 st = open(output, 'wb')
51 close = True
52 else: # pragma: no cover
53 close = False
54 st = output
56 for img in all_images:
57 if isinstance(img, str) and not os.path.exists(img):
58 raise FileNotFoundError( # pragma: no cover
59 f"Unable to find image {img!r}.")
61 try:
62 convert(all_images, outputstream=st, with_pdfrw=False)
63 except TypeError as e:
64 raise TypeError( # pragma: no cover
65 "Unable to process container type %r and type %r." % (
66 type(all_images), type(all_images[0]))) from e
68 if close:
69 st.close()
71 return all_images