如何更改 reportlab.pdfgen 中的文本/字体颜色 [英] How to change text/font color in reportlab.pdfgen
问题描述
我想在自动生成的 PDF 中使用不同颜色的文本.
I want to use a different color of text in my auto-generated PDF.
根据 reportlab 文档,我所有需要做的是:
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.
推荐答案
如果您复制并粘贴用户指南第 2 部分中的代码.您将得到一个带有彩色文本的彩色矩形.用户指南中的方法可能不是那么清楚,我花了一些时间玩它,我终于知道它是如何工作的.
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()
这篇关于如何更改 reportlab.pdfgen 中的文本/字体颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!