Coverage for bookbuilderpy/pdf.py: 30%
20 statements
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-17 23:15 +0000
« prev ^ index » next coverage.py v7.2.7, created at 2023-07-17 23:15 +0000
1"""Post-process PDF files."""
3from os.path import dirname, exists
5from bookbuilderpy.logger import logger
6from bookbuilderpy.path import Path
7from bookbuilderpy.shell import shell
8from bookbuilderpy.versions import TOOL_GHOSTSCRIPT, has_tool
11def pdf_postprocess(in_file: str,
12 out_file: str,
13 overwrite: bool = False) -> Path:
14 """
15 Post-process a pdf file.
17 :param in_file: the input file
18 :param out_file: the output file
19 :param overwrite: should the output file be overwritten if it exists?
20 :return: the output file
21 """
22 source = Path.file(in_file)
23 output = Path.path(out_file)
24 if (not overwrite) and exists(output):
25 raise ValueError(f"Output file '{output}' already exists.")
26 if source == output:
27 raise ValueError(f"Input and output file is the same: '{source}'.")
29 if has_tool(TOOL_GHOSTSCRIPT):
30 logger(f"Post-processing pdf file '{source}' to '{output}' "
31 f"by applying '{TOOL_GHOSTSCRIPT}'.")
33 cmd = [TOOL_GHOSTSCRIPT,
34 "-q",
35 "-dPrinted=false",
36 "-dEmbedAllFonts=true",
37 "-dSubsetFonts=true",
38 "-dCompressFonts=true",
39 "-dCompressStreams=true",
40 "-dOptimize=true",
41 "-dUNROLLFORMS",
42 "-dCompatibilityLevel=1.7",
43 "-dLZWEncodePages=true",
44 "-dCompressPages=true",
45 "-dPassThroughJPEGImages=true",
46 "-dPassThroughJPXImages=true",
47 "-dCannotEmbedFontPolicy=/Error",
48 "-dPreserveCopyPage=false",
49 "-dPreserveEPSInfo=false",
50 "-dPreserveHalftoneInfo=false",
51 "-dPreserveOPIComments=false",
52 "-dPreserveOverprintSettings=false",
53 "-dPreserveSeparation=false",
54 "-dPreserveDeviceN=false",
55 "-dMaxBitmap=2147483647",
56 "-dDownsampleMonoImages=false",
57 "-dDownsampleGrayImages=false",
58 "-dDownsampleColorImages=false",
59 "-dDetectDuplicateImages=true",
60 "-dHaveTransparency=true",
61 "-dAutoFilterColorImages=false",
62 "-dAutoFilterGrayImages=false",
63 "-dColorImageFilter=/FlateEncode",
64 "-dGrayImageFilter=/FlateEncode",
65 "-dColorConversionStrategy=/LeaveColorUnchanged",
66 "-dFastWebView=false",
67 "-dNOPAUSE",
68 "-dQUIET",
69 "-dBATCH",
70 "-dSAFER",
71 "-sDEVICE=pdfwrite",
72 "-dAutoRotatePages=/PageByPage",
73 f'-sOutputFile="{output}"',
74 source,
75 '-c "<</NeverEmbed [ ]>> setdistillerparams"']
76 shell(cmd, timeout=600, cwd=dirname(source))
77 else:
78 logger(f"'{TOOL_GHOSTSCRIPT}' not installed, copying files directly.")
79 Path.copy_file(source, output)
81 output.enforce_file()
83 return output