-
Notifications
You must be signed in to change notification settings - Fork 11
/
Copy pathpdfsetinfo.py
135 lines (125 loc) · 3.75 KB
/
pdfsetinfo.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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
#!/usr/bin/env python
# file: pdfsetinfo.py
# vim:fileencoding=utf-8:ft=python
#
# Copyright © 2021 R.F. Smith <[email protected]>
# Created: 2021-02-28T13:49:42+0100
# Last modified: 2021-02-28T16:13:37+0100
"""Update the DOCINFO directory in a PDF file using ghostscript."""
from datetime import datetime as dt
import argparse
import os
import shutil
import subprocess as sp
import sys
import tempfile
__version__ = "2021.02.28"
def main():
"""Entry point for pdfsetinfo."""
args = setup()
# print(f"DEBUG: args = {args}")
rv = 0
if len([j for j in args.__dict__.values() if j is None]) > 4:
print("Nothing to do. Exiting.")
return 0
with tempfile.TemporaryDirectory() as path:
docinfo = mkdocinfo(args, path)
# print(f"DEBUG: docinfo = {docinfo}")
try:
cp = sp.run(
[
"gs",
"-q",
"-dBATCH",
"-dNOPAUSE",
"-sDEVICE=pdfwrite",
f"-sOutputFile={path+os.sep}output.pdf",
args.file,
docinfo,
],
stdout=sp.DEVNULL,
stderr=sp.DEVNULL,
)
rv = cp.returncode
except FileNotFoundError:
print("ERROR: ghostscript not found.")
rv = 1
else:
# print("DEBUG: copy")
if args.output:
shutil.copy(f"{path+os.sep}output.pdf", args.output)
else:
shutil.copy(f"{path+os.sep}output.pdf", args.file)
return rv
def setup():
"""Process command line arguments."""
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument(
"-t",
"--title",
type=str,
help="document title",
)
parser.add_argument(
"-a",
"--author",
type=str,
help="name of the person that authored the document",
)
parser.add_argument(
"-s",
"--subject",
type=str,
help="what is the document about",
)
parser.add_argument(
"-k",
"--keywords",
type=str,
help="comma separated list of keywords",
)
parser.add_argument(
"-o",
"--output",
type=str,
default=None,
help="output file path (defaults to input file path)",
)
parser.add_argument(
"-p",
"--producer",
type=str,
default="pdfsetinfo " + __version__,
help="producer of the modified file (defaults to pdfsetinfo)",
)
parser.add_argument("-v", "--version", action="version", version=__version__)
parser.add_argument("file", type=str, help="input file path")
args = parser.parse_args(sys.argv[1:])
return args
def mkdocinfo(args, directory):
"""Create a file “pdfmarks.txt” in the given directory, with the info from args."""
data = []
post = "/DOCINFO pdfmark"
if args.title:
data.append(f"/Title ({args.title})")
if args.author:
data.append(f"/Author ({args.author})")
# elif os.name == "posix":
# import pwd
# name = pwd.getpwuid(os.getuid()).pw_gecos
# data.append(f"/Author ({name})")
if args.subject:
data.append(f"/Subject ({args.subject})")
if args.keywords:
data.append(f"/Keywords ({args.keywords})")
if args.producer:
data.append(f"/producer ({args.producer})")
data.append(dt.strftime(dt.now().astimezone(), "/ModDate (D:%Y%m%d%H%M%S%z)"))
data.append(post)
data[0] = "[ " + data[0]
rv = directory + os.sep + "pdfmarks.txt"
with open(rv, "w") as pdfmarks:
pdfmarks.write(os.linesep.join(data))
return rv
if __name__ == "__main__":
sys.exit(main())