aboutsummaryrefslogtreecommitdiff
path: root/annotation-summary.py
blob: 42ddd7cb419ad3677b19f80553180d1c083ff89b (plain)
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
#!/usr/bin/env python3

import argparse
import os
import pdfkit
import popplerqt5

def collect_annotations(source):
    doc = popplerqt5.Poppler.Document.load(source)
    annotations = {}
    for i in range(doc.numPages()):
        annotations[i] = []
        for annot in doc.page(i).annotations():
            annotations[i].append(annot)
    return annotations

def generate_pdf(annotations, destination="annotations.pdf", pagesize="A4"):
    options = {
        'page-size': pagesize,
        'encoding': "utf-8",
        'margin-top': '0.75in',
        'margin-right': '0.75in',
        'margin-bottom': '0.75in',
        'margin-left': '0.75in',
        }

    blocks = """
        <!DOCTYPE html>
        <html>
        <head>
            <meta charset="utf-8">
            <style>
            <!--
            .annotation {
                border: 1px solid #300;
                padding: 10px;
                display: block !important;
                page-break-inside: avoid !important;
            }
            .content {
                white-space: pre-wrap;
            }
            -->
            </style>
        </head>
        <body>
    """

    pages = list(annotations.keys())
    pages.sort()
    for page in pages:
        for annotation in annotations[page]:
            content = annotation.contents()
            if not content:
                continue
            author = annotation.author()
            if author != "":
                header = f"<span>Page: {page + 1}</span> | <span>Author: {author}</span>"
            else:
                header = f"<span>Page: {page + 1}</span>"
            blocks += f"""
                <div class="annotation">
                    {header}<br/>
                    <hr/>
                    <div class="content">{content}</div>
                </div>
                <br/>
            """

    blocks += """
            </body>
        </html>
    """
    if os.path.exists(destination):
        print(f"Error: {destination} already exists. Quitting.")
    else:
        pdfkit.from_string(blocks, destination, options=options)

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument('source')
    args = parser.parse_args()
    annotation_list = collect_annotations(args.source)
    generate_pdf(annotation_list)