Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change text/font color in reportlab.pdfgen

I want to use a different color of text in my auto-generated PDF.

According to the reportlab docs all I need to do is:

self.canvas.setFillColorRGB(255,0,0) self.canvas.drawCentredString(...) 

But that doesn't do anything. The text is black no matter what.

like image 259
Goro Avatar asked Mar 24 '12 20:03

Goro


People also ask

How do I change Font color in Reportlab?

According to the reportlab docs all I need to do is: self. canvas. setFillColorRGB(255,0,0) self.

How do I change the color of my text color?

Go to Format > Font > Font. + D to open the Font dialog box. Select the arrow next to Font color, and then choose a color. Select Default and then select Yes to apply the change to all new documents based on the template.

Is Reportlab free?

ReportLab is a free open-source document creation engine for generating PDF documents and custom vector graphics.


2 Answers

If you copy and paste the code in User Guide Section 2. You'll get a fancy coloured rectangle with a coloured Text within it. Probably the approach is not that clear in the user guide, I'd spent some time playing with it and I finally know how it works.

You need to imagine yourself drawing a canvas. You need to do all the setup before you draw. Below is an example I prepared to show better how to style a text, draw a line, and draw a rectangle, all with the ability to put colour on them.

from reportlab.pdfgen import canvas  def hello(c):     from reportlab.lib.units import inch      #First Example     c.setFillColorRGB(1,0,0) #choose your font colour     c.setFont("Helvetica", 30) #choose your font type and font size     c.drawString(100,100,"Hello World") # write your text      #Second Example     c.setStrokeColorRGB(0,1,0.3) #choose your line color     c.line(2,2,2*inch,2*inch)      #Third Example     c.setFillColorRGB(1,1,0) #choose fill colour     c.rect(4*inch,4*inch,2*inch,3*inch, fill=1) #draw rectangle  c = canvas.Canvas("hello.pdf")  hello(c) c.showPage() c.save() 
like image 130
Nicholas TJ Avatar answered Sep 19 '22 18:09

Nicholas TJ


from reportlab.lib.colors import HexColor ...  # sets fill color like orange c.setFillColor(HexColor(0xff8100)) # or  c.setFillColor(HexColor('#ff8100'))  ... 
like image 25
SergO Avatar answered Sep 18 '22 18:09

SergO