Home ยป Create a pdf using PyCairo

Create a pdf using PyCairo

Spring Framework Basics Video Course
Oracle Java Certification
Java SE 11 Programmer II [1Z0-816] Practice Tests
1 Year Subscription
Java SE 11 Programmer I [1Z0-815] Practice Tests
Java SE 11 Developer (Upgrade) [1Z0-817]

In this example we show you how to create a pdf with text in it using PyCairo

Code

import cairo
       
    
def main():
    
    ps = cairo.PDFSurface("testfile.pdf", 504, 648)
    cr = cairo.Context(ps)
    
    cr.set_source_rgb(0, 0, 0)
    cr.select_font_face("Sans", cairo.FONT_SLANT_NORMAL,
        cairo.FONT_WEIGHT_NORMAL)
    cr.set_font_size(16)
    
    cr.move_to(10, 20)
    cr.show_text("This is sample text in the PDF.")
    cr.move_to(30, 40)
    cr.show_text("This is more sample text in the PDF.")
    cr.move_to(50, 60)
    cr.show_text("This is sample text in the PDF line 3.")
    cr.show_page()
        
        
if __name__ == "__main__":    
    main()

The code is similar to the image creation example

To render a PDF file, we must create a PDF surface using the cairo.PDFSurface object. The size of the PDF file is specified in points.

  • width_in_points โ€“ width of the surface, in points (1 point = 1/72.0 inch)
  • height_in_points โ€“ height of the surface, in points (1 point = 1/72.0 inch)
ps = cairo.PDFSurface("testfile.pdf", 600, 800)

The show_page() finishes rendering of the PDF file.

cr.show_page()

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More