Coverage for documents/converters.py: 36%

20 statements  

« prev     ^ index     » next       coverage.py v7.15.2, created at 2026-10-10 09:07 +0000

1from pathlib import Path 

2 

3import img2pdf 

4from django.conf import settings 

5from PIL import Image 

6 

7from documents.utils import copy_basic_file_stats 

8from documents.utils import maybe_override_pixel_limit 

9from documents.utils import run_subprocess 

10 

11 

12def convert_from_tiff_to_pdf(tiff_path: Path, target_directory: Path) -> Path: 

13 """ 

14 Converts a TIFF file into a PDF file. 

15 

16 The PDF will be created in the given target_directory and share the name of 

17 the original TIFF file, as well as its stats (mtime etc.). 

18 

19 Returns the path of the PDF created. 

20 """ 

21 # override pixel setting if needed 

22 maybe_override_pixel_limit() 

23 

24 with Image.open(tiff_path) as im: 

25 has_alpha_layer = im.mode in ("RGBA", "LA") 

26 if has_alpha_layer: 

27 # Note the save into the temp folder, so as not to trigger a new 

28 # consume 

29 scratch_image = target_directory / tiff_path.name 

30 run_subprocess( 

31 [ 

32 settings.CONVERT_BINARY, 

33 "-alpha", 

34 "off", 

35 tiff_path, 

36 scratch_image, 

37 ], 

38 ) 

39 else: 

40 # Not modifying the original, safe to use in place 

41 scratch_image = tiff_path 

42 

43 pdf_path = (target_directory / tiff_path.name).with_suffix(".pdf") 

44 

45 with scratch_image.open("rb") as img_file, pdf_path.open("wb") as pdf_file: 

46 pdf_file.write(img2pdf.convert(img_file)) 

47 

48 # Copy what file stat is possible 

49 copy_basic_file_stats(tiff_path, pdf_path) 

50 return pdf_path