#!/usr/bin/python # -*- coding: utf-8 -*- """Hello-world generating internal and external links in a PDF in Reportlab. This goes a bit beyond "hello world" I guess, in that it explores different options for bookmark types and link formatting. """ from reportlab.pdfgen.canvas import Canvas from reportlab.lib.colors import toColor def main(): x1, y1, x2, y2 = (72, 36, 144, 108) c = Canvas('hilinks.pdf', pagesize=(72*3, 72*2)) c.bookmarkPage('hellopage') c.drawCentredString(72*1.5, 66, "hello") c.addOutlineEntry('greetings', 'hellopage', closed=True) # Without a unique bookmark for each outline entry, the names for # earlier outline entries get lost, so we create a second bookmark: c.bookmarkPage('hellopage2') c.addOutlineEntry('(hi)', 'hellopage2', level=1) # c.linkAbsolute also exists, using absolute coordinates rather # than transformed coordinates; since we haven't changed our # coordinate system these are equivalent. # Though other viewers ignore it, pdf.js displays the first # argument in a popup. c.linkRect('some contents', 'goodbyepage', (x1, y1, x2, y2)) c.showPage() c.bookmarkPage('goodbyepage', fit='XYZ') # default `fit` is full page zoom c.drawCentredString(72*1.5, 66, "goodbye") # `thickness` makes the link box visible, but it doesn't print. Default # is invisible. c.linkRect('what are these', 'hellopage', (x1, y1, x2, y2), thickness=0.2) c.addOutlineEntry('(bye)', 'goodbyepage', level=1) c.showPage() c.bookmarkPage('neither') c.drawCentredString(72*1.5, 66, 'neither hai nor bai') c.linkURL('http://canonical.org/', (x1-36, y1, x2+36, y2), thickness=0.1, color=toColor('#9999ff')) # toColor fails with three-digit #99f c.addOutlineEntry('(neither)', 'neither') c.showPage() c.save() if __name__ == '__main__': main()