-
Notifications
You must be signed in to change notification settings - Fork 84
/
Copy pathcompress.py
53 lines (43 loc) · 1.33 KB
/
compress.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
import os
import sys
import subprocess
import tempfile
def compress(source: str, target: str, power: int = 0):
"""
Compress a given PDF file
:param str source: source PDF file
:param str target: target location to save the compressed PDF
:param int power: power of the compression. Default value is 0. This can be 0: default, 1: prepress, 2: printer, 3: ebook, 4: screen
"""
quality = {
0: "/default",
1: "/prepress",
2: "/printer",
3: "/ebook",
4: "/screen",
}
if not os.path.isfile(source):
print("Error: invalid path for input PDF file")
sys.exit(1)
if source.split(".")[-1].lower() != "pdf":
print("Error: input file is not a PDF")
sys.exit(1)
subprocess.call(
[
"gs",
"-sDEVICE=pdfwrite",
"-dCompatibilityLevel=1.4",
"-dPDFSETTINGS={}".format(quality[power]),
"-dNOPAUSE",
"-dQUIET",
"-dBATCH",
"-sOutputFile={}".format(target),
source,
],
)
def __compress(result, target: str, power: int):
with tempfile.TemporaryDirectory() as tmp_dir:
tmp_file = f"{tmp_dir}/tmp.pdf"
with open(tmp_file, "wb") as file:
file.write(result)
compress(tmp_file, target, power)