#!/usr/bin/python # -* coding: utf-8 -*- """Hello-world for generating PDFs in Python with ReportLab. You can cut it down from these 14 lines of code a little, but this is close to the practical minimum. See hireportlab.py for a 4-line version, or hellotextobject.py for a version that does word wrap. My remaining big questions are: - Where can I get glyphs for ⁑ and similar characters? Font loading and weird page sizes are in hellofont.py, based on ch2a_fonts.py in the Reportlab distribution. Chinese is in hellochinese.py, although sans-serif only. Links (both internal and external) are in hellopdflinks.py. An attempt at font cascades with a fallback is in hellocascadepdf.py. """ import reportlab.pdfgen.canvas from reportlab.lib.units import inch # 72.0 (PostScript points) from reportlab.lib.pagesizes import A4 # (w, h) in PostScript points def main(): # invariant=True eliminates /CreationDate (D:20191225233431+03'00'). # default ``pagesize`` is A4; default pageCompression is True c = reportlab.pdfgen.canvas.Canvas('hello.pdf', invariant=True) c.setFont('Times-Roman', 36) # PostScript font names and point sizes # Not sure how to load other fonts than the standard ones: #print(c.getAvailableFonts()) # c.translate, c.rotate, c.scale, and c.transform also exist. c.setFillColorRGB(0.9, 0.3, 0.2) # defaults to black, applies to text. # c.setFillAlpha, c.setStrokeColorRGB, etc., also exist, and alpha # is an optional argument to setFillColorRGB. # Note, Chinese is not in the font, so we get black squares; worse, # it doesn't copy and paste correctly (though the rest does): c.drawCentredString(0.5 * A4[0], 0.5 * inch, "hélló, wórld° :) 你好 κοσμος") # c.drawString, c.drawRightString, and c.drawAlignedString also exist. c.bookmarkPage('hellopage') # define a link destination for this page c.addOutlineEntry('Hello.', 'hellopage', level=0) # add it to hierarchy # XXX doesn't work: c.linkRect('foo', 'hellopage', (0, 0, 1 * inch, 8 * inch)) c.showPage() # There's a c.beginText(x, y) which returns a text object you can .textLine, # and a c.beginPath() which returns a path object. Text objects # (reportlab.pdfgen.textobject) can also .setFont, .setLeading, # .setCharSpace, .setWordSpace, etc., and .textLines, and then you can # c.drawText them. Path objects (reportlab.pdfgen.pathobject) # can be c.drawPath()ed; they support .moveTo, .lineTo, .curveTo, etc. # Simpler drawing can be done with c.rect, c.circle, and c.roundRect, # and c.drawImage can embed an image file. # c.stringWidth() gets the width of a string for paragraph filling. # Finish PDF file and die if any missing bookmarks: c.save() if __name__ == '__main__': main()