-
Notifications
You must be signed in to change notification settings - Fork 12
/
Copy pathrenderPdf.sc
263 lines (235 loc) · 9.33 KB
/
renderPdf.sc
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
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
import mill._
import org.apache.pdfbox.pdmodel.PDDocument
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.destination.{PDNamedDestination, PDPageXYZDestination}
import org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline.{PDDocumentOutline, PDOutlineItem, PDOutlineNode}
import org.apache.pdfbox.util.Matrix
case class RenderedOutput(pdf: PathRef,
outline: Seq[Seq[(String, String)]])
implicit val renderedOutputRW: upickle.default.ReadWriter[RenderedOutput] = upickle.default.macroRW
def getPdfOutline(src: os.Path) = {
import collection.JavaConverters._
val doc = org.apache.pdfbox.pdmodel.PDDocument.load(src.toIO)
try doc.getPages.asScala.map(p =>
p.getAnnotations.asScala.collect{
case a: org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink =>
a.getAction match {
case ac: org.apache.pdfbox.pdmodel.interactive.action.PDActionURI =>
ac.getURI match {
case s"https://localhost/section-header/$rest" =>
val Array(numbering, title) = rest.replace("%20", " ").split(" ", 2)
Some((numbering, title))
case _ => None
}
case _ => None
}
}.flatten.toSeq
) finally doc.close()
}
def foreachOutlineChild(item: PDOutlineNode)(f: PDOutlineItem => Unit) = {
var child = item.getFirstChild
while (child != null) {
val next = child.getNextSibling
f(child)
child = next
}
}
def updatePdfPageOffsets(inputs: Seq[os.Path]) = {
var currentPageOffset: Int = 0
for (input <- inputs) {
val pdf: PDDocument = PDDocument.load(os.read.bytes(input))
val catalog = pdf.getDocumentCatalog
val outline: PDDocumentOutline = catalog.getDocumentOutline
def rec(item: PDOutlineItem): Unit = {
val dest = item.getDestination match {
case named: PDNamedDestination =>
catalog
.getDests
.getDestination(named.getNamedDestination)
.asInstanceOf[PDPageXYZDestination]
case dest: PDPageXYZDestination => dest
}
dest.setPageNumber(dest.getPageNumber + currentPageOffset + 1)
item.setDestination(dest)
foreachOutlineChild(item)(rec)
}
if (outline != null) foreachOutlineChild(outline)(rec)
currentPageOffset += pdf.getNumberOfPages
pdf.save(input.toIO)
}
}
def mergePdfs(inputs: Seq[os.Path], outPath: os.Path)
(implicit ctx: mill.api.Ctx.Dest): PathRef = {
val merger = new org.apache.pdfbox.multipdf.PDFMergerUtility
for (input <- inputs) merger.addSource(input.toIO)
val out = os.write.outputStream(outPath)
try {
merger.setDestinationStream(out)
merger.mergeDocuments()
} finally out.close()
PathRef(outPath)
}
def checkExternalLinks(source: os.Path) = {
val doc = org.apache.pdfbox.pdmodel.PDDocument.load(os.read.bytes(source))
import collection.JavaConverters._
val optFuturesIter =
for {
(page, i) <- doc.getPages.iterator().asScala.zipWithIndex
annot <- page.getAnnotations.asScala
} yield {
val l = annot.asInstanceOf[org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink]
val a = l.getAction.asInstanceOf[org.apache.pdfbox.pdmodel.interactive.action.PDActionURI]
if (a == null) None
else {
a.getURI match{
case s"page-link://$rest" => None
case s"https://localhost/$rest" => None
case s"mailto:$rest" => None
case url =>
println(s"checking URI page $i $url")
def getSleep(sleep: Int) = {
if (sleep != 0) println(s"Retrying after $sleep ms")
Thread.sleep(sleep)
requests.get(url, check = false)
}
val resp = getSleep(0)
val resp2 = if (resp.is2xx) resp else getSleep(5000)
val resp3 = if (resp2.is2xx) resp2 else getSleep(10000)
val resp4 = if (resp3.is2xx) resp2 else getSleep(20000)
println(resp4.statusCode)
Some((i, url, resp4))
}
}
}
val responses = optFuturesIter.flatten.toList
val failures = responses.filter(!_._3.is2xx)
assert(failures.isEmpty, failures.map{ case (i, url, resp) => (i, url, resp.statusCode)}.mkString("\n"))
}
def checkPdfOutline(source: os.Path,
headerPages: Seq[(String, String, Int)]) = {
import org.apache.pdfbox.text.PDFTextStripper
val stripper = new PDFTextStripper()
val pdf: PDDocument = PDDocument.load(os.read.bytes(source))
createPdfOutline(pdf, headerPages)
val catalog = pdf.getDocumentCatalog
val outline: PDDocumentOutline = catalog.getDocumentOutline
val missing = collection.mutable.ArrayDeque.empty[(String, Int)]
def rec(item: PDOutlineItem): Unit = {
val pageNum = item.getDestination.asInstanceOf[PDPageXYZDestination].getPageNumber
stripper.setStartPage(pageNum + 1)
stripper.setEndPage(pageNum + 1)
val txt = stripper.getText(pdf).replace("\n", " ")
if (!txt.contains(item.getTitle)){
missing.append(item.getTitle -> pageNum)
}
foreachOutlineChild(item)(rec)
}
foreachOutlineChild(outline)(rec)
assert(missing.isEmpty, missing.mkString("\n"))
}
def createPdfOutline(doc: PDDocument,
headerPages: Seq[(String, String, Int)]) = {
val chapterSubsectionPages = headerPages.map{ case (nums, name, v) => (nums, v)}.toMap
import collection.JavaConverters._
for (page <- doc.getPages.iterator().asScala; annot <- page.getAnnotations.asScala) {
val l = annot.asInstanceOf[org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationLink]
val a = l.getAction.asInstanceOf[org.apache.pdfbox.pdmodel.interactive.action.PDActionURI]
if (a != null) {
def mangleLinkOpt(handler: PartialFunction[String, Int]) = {
handler.lift(a.getURI).map{ linkPageNumber =>
l.setAction(null)
val dest = new PDPageXYZDestination()
dest.setPageNumber(linkPageNumber)
l.setDestination(dest)
}
}
mangleLinkOpt{case s"page-link://$rest" => rest.toInt}
mangleLinkOpt{case s"https://localhost/section-link/$rest" => chapterSubsectionPages(rest)}
}
}
val outline = new PDDocumentOutline()
outline.openNode()
val outlineItemStack = collection.mutable.ArrayDeque.empty[PDOutlineItem]
for((num, name, page) <- headerPages){
val depth = if (num == "") 0 else num.split('.').length
val outlineItem = new PDOutlineItem()
val dest = new PDPageXYZDestination()
dest.setPageNumber(page)
outlineItem.setDestination(dest)
outlineItem.setTitle(if (num == "") name else num + " " + name)
if (depth == 0) outline.addLast(outlineItem)
else {
while (depth <= outlineItemStack.length) outlineItemStack.removeLast()
outlineItemStack.lastOption match{
case None => outline.addLast(outlineItem)
case Some(last) => last.addLast(outlineItem)
}
outlineItemStack.append(outlineItem)
}
}
doc.getDocumentCatalog.setDocumentOutline(outline)
doc
}
def createPdfFooter(doc: PDDocument,
headerPages: Seq[(String, String, Int)],
marginMM: Float,
spineOffsetMM: Option[Float]) = {
import org.apache.pdfbox.pdmodel.PDPageContentStream
import org.apache.pdfbox.pdmodel.font.PDType0Font
val flatHeaderPages = headerPages.filter(!_._1.contains('.'))
val pointsPerMM = 72 / 25.4F
val marginUnits = marginMM * pointsPerMM
for (pageNum <- Range(0, doc.getNumberOfPages)) {
val page = doc.getPage(pageNum)
for((headerNum, headerName, headerPage) <- flatHeaderPages.findLast(_._3 <= pageNum)) {
val contentStream = new PDPageContentStream(
doc,
page,
PDPageContentStream.AppendMode.APPEND,
true,
true
)
val font = PDType0Font.load(doc, os.read.inputStream(os.pwd / "resources" / "times-it.ttf"))
val fontSize = 10
contentStream.setFont(font, fontSize)
if (headerPage != pageNum && headerNum != "") {
contentStream.beginText()
contentStream.newLineAtOffset(marginUnits, marginUnits)
contentStream.showText(s"Chapter $headerNum $headerName")
contentStream.endText()
}
if (headerName != "Table of Contents") {
contentStream.beginText()
val pageNumString = (pageNum + 1).toString
val textWidth = (font.getStringWidth(pageNumString) / 1000.0f) * fontSize
contentStream.newLineAtOffset(page.getMediaBox.getUpperRightX - textWidth - marginUnits, marginUnits)
contentStream.showText(pageNumString)
contentStream.endText()
}
contentStream.close()
}
for(offset <- spineOffsetMM) {
val contentStream = new PDPageContentStream(
doc,
page,
PDPageContentStream.AppendMode.PREPEND,
false // compress
);
contentStream.transform(
Matrix.getTranslateInstance((if (pageNum % 2 == 0) 1 else -1) * offset * pointsPerMM, 0)
)
contentStream.close()
}
}
}
def finalizePdf(source: os.Path,
dest: os.Path,
headerPages: Seq[(String, String, Int)],
marginMM: Float,
spineOffsetMM: Option[Float]) = {
val doc = org.apache.pdfbox.pdmodel.PDDocument.load(os.read.bytes(source))
try{
createPdfOutline(doc, headerPages)
createPdfFooter(doc, headerPages, marginMM, spineOffsetMM)
doc.save(dest.toIO)
}finally doc.close()
}