-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpdfWriter.py
executable file
·177 lines (144 loc) · 6.15 KB
/
pdfWriter.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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
from comicGetter import comicGetter
from generateHeader import generateHeader
import os
import shutil
import subprocess
from imageProcessing.split import splitFile
from imageProcessing.shrinkImage import shrinkImage, getImageDims, getResizedDims
def escapeString(toEscape):
return toEscape.translate(
str.maketrans({
"\\": "\\\\",
"^": "\\^",
"$": "\\$",
"*": "\\*",
"%": "\\%",
"{": "\\{",
"}": "\\}",
"#": "",
"&": "\\&",
"_": "\\_",
"|": "\\|"
}))
MARGIN = 20
INDEX_FILENAME = ".index"
BODY_FILE = "body.txt"
HEADER_FILE = "header.txt"
MAX_WIDTH = 1.3
class pdfWriter:
def __init__(self, name, author, pageColor, textColor, optionalHeight, optionalWidth, jpgQuality):
self.title = name
self.pageHeight = int(optionalHeight) if optionalHeight else 1200
self.pageWidth = int(optionalWidth) if optionalWidth else 800
self.workWidth = self.pageWidth - (2 * MARGIN)
self.workHeight = self.pageHeight - (2 * MARGIN)
self.jpgQuality = jpgQuality if jpgQuality else 95
self.pageColor = pageColor
self.lastChapterName = ""
self.comicNumber = 0
self._restoreState()
generateHeader(name, author, pageColor, textColor,
self.pageWidth, self.pageHeight, MARGIN)
if not os.path.exists('images'):
os.makedirs('images')
# PUBLIC
def addComic(self, comic):
print("adding comic", self.comicNumber + 1, "to pdf")
for image in comic.imageFiles:
print("adding image", image, "to pdf")
self._addComic(comic, image)
def save(self):
indexFile = open(INDEX_FILENAME, 'w')
indexFile.write(str(self.comicNumber) + "\n")
indexFile.write(self.lastChapterName)
indexFile.close()
def finish(self):
escapedName = self.title.replace(' ', '')
finalFilename = escapedName + '.latex'
with open(finalFilename, 'w') as finalFile:
for f in [HEADER_FILE, BODY_FILE]:
with open(f, 'r') as currentFile:
shutil.copyfileobj(currentFile, finalFile)
finalFile.write("\\end{document}")
subprocess.run(["rubber", "-d", finalFilename])
os.remove(finalFilename)
try:
os.remove(escapedName + ".aux")
os.remove(escapedName + ".log")
os.remove(escapedName + ".rubbercache")
except OSError:
pass
if self.lastChapterName != "":
os.remove(escapedName + ".toc")
# PRIVATE
def _restoreState(self):
if (os.path.isfile(INDEX_FILENAME)):
print("restoring state of pdf")
indexFile = open(INDEX_FILENAME, 'r')
self.comicNumber = int(indexFile.readline())
self.lastChapterName = indexFile.readline()
print("set comic number to", self.comicNumber)
if (self.lastChapterName):
print("set chapter name to", self.lastChapterName)
indexFile.close()
def _stripUnicode(self, string):
return escapeString(string.encode('ascii', "replace").decode('ascii'))
def _getTitle(self, comic):
return self._stripUnicode(comic.title) if comic.title else ""
def _getMouseover(self, comic):
return self._stripUnicode(comic.titleText) if comic.titleText else ""
def _addComic(self, comic, image):
self.comicNumber += 1
width, height = getImageDims(image)
self._addChapterName(comic)
if width >= self.workWidth * MAX_WIDTH and height < self.workHeight:
print("image", image, "is too wide; splitting...")
images = splitFile(image, self.workWidth, axis=1)
for i in range(len(images)):
self._addComicFullWidth(comic, images[i], "h" + str(i))
else:
self._addComicFullWidth(comic, image)
def _addComicFullWidth(self, comic, image, suffix=""):
height = getResizedDims(self.workWidth, image)[1]
title = self._getTitle(comic)
mouseover = self._getMouseover(comic)
if height < self.workHeight + MARGIN:
image = self._getComicImage(image, suffix)
self._addComicInfo(title, image, mouseover)
else:
print("image", image, "is too tall (", height, "px on a ", self.workHeight ,"px page); splitting")
shrinkFactor = min(1, height / self.workWidth)
splitHeight = shrinkFactor * (self.workHeight + MARGIN)
images = splitFile(image, splitHeight)
self._addSplitImages(images, title, mouseover, suffix)
def _addSplitImages(self, images, title, mouseover, suffix=""):
for i in range(len(images)):
_suffix = suffix + "p" + str(i)
image = self._getComicImage(images[i], _suffix)
_title = title if i == 0 else ""
_mouseover = mouseover if i is len(images) - 1 else ""
self._addComicInfo(_title, image, _mouseover)
os.remove(images[i])
def _addChapterName(self, comic):
name = escapeString(comic.chapterName)
if name != "" and name != self.lastChapterName:
with open(BODY_FILE, 'a') as comics:
if self.comicNumber == 1:
comics.write(
"\t\\begingroup\\let\\cleardoublepage\\clearpage\\tableofcontents\\endgroup\n")
comics.write("""\t\\newpage
\\begin{{center}}
\\vspace*{{\\fill}}
\\section{{{0}}}
\\vspace*{{\\fill}}
\\end{{center}}
\\newpage\n""".format(name))
self.lastChapterName = name
def _getComicImage(self, comic, suffix=""):
title = ''.join(e for e in self.title if e.isalnum())
return shrinkImage(comic, self.workWidth, title, self.comicNumber, self.pageColor, self.jpgQuality, suffix)
def _addComicInfo(self, title, image, mouseover):
print("adding comic info", title, "-", image, "-", mouseover)
with open(BODY_FILE, 'a') as comics:
comics.write("\t\\comic{{{0}}}{{{1}}}{{{2}}}\n".format(
title, image, mouseover))