File: merge-annotations.py

package info (click to toggle)
python-poppler-qt5 21.3.0-3
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 280 kB
  • sloc: python: 424; makefile: 11
file content (61 lines) | stat: -rw-r--r-- 1,789 bytes parent folder | download | duplicates (3)
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
#!/usr/bin/env python2.7
import popplerqt5
import PyQt5.QtXml
import argparse
import tempfile
import shutil

def merge(target, src):
    dom=PyQt5.QtXml.QDomDocument()
    for pg_index in range(min(target.numPages(),src.numPages())):
        p_tgt = target.page(pg_index)
        p_src = src.page(pg_index)
        for a in p_src.annotations():
            if not has_annotation(p_tgt,a):
                a_el = dom.createElement("annotation")
                popplerqt5.Poppler.AnnotationUtils.storeAnnotation(a,a_el,dom)
                a_tgt = popplerqt5.Poppler.AnnotationUtils.createAnnotation(a_el)
                p_tgt.addAnnotation(a_tgt)

def has_annotation(page,a):
    for pa in page.annotations():
        if pa.uniqueName() == a.uniqueName():
            return True
    return False
            
def save_pdf(pdf_doc,filename):
    c = pdf_doc.pdfConverter()
    c.setOutputFileName(filename)
    c.setPDFOptions(c.WithChanges)
    c.convert()
    
def load_pdf(filename):
    return popplerqt5.Poppler.Document.load(filename)


if __name__ == "__main__":
    parser = argparse.ArgumentParser(description='A simple utility for merging pdf annotations')
    parser.add_argument('file', help='the files to merge annotations from', nargs="+")
    parser.add_argument('--output', help='the file to save annotations to (if not present, will save into the first file)')
    args = parser.parse_args()
    tgt = load_pdf(args.file[0])
    for f in args.file[1:]:
        src = load_pdf(f)
        merge(tgt,src)
    if args.output:
        save_pdf(tgt,args.output)
    else:
        tmp_h,tmp_path = tempfile.mkstemp("pdf")
        save_pdf(tgt,tmp_path)
        del tgt
        shutil.move(tmp_path,args.file[0])