我可以使用reportlab从txt文件创建pdf文件。这很容易,但我想做一些大胆的文字,有些是正常的,有些是斜体。我怎么能这样做?
答案 0 :(得分:1)
their documentation有一些很好的见解。粗略地说,任何字体的粗体和斜体版本实际上都是不同的字体。因此,您只需在要更改字体时设置字体。 这可能会收紧,但对我有用:
import reportlab
import os
from reportlab.pdfgen import canvas
from reportlab.pdfbase import pdfmetrics
from reportlab.pdfbase.ttfonts import TTFont
canv = canvas.Canvas("fonts_demo.pdf")
font_variants = ("DejaVuSans","DejaVuSans-Oblique","DejaVuSans-Bold")
folder = '/usr/share/fonts/truetype/dejavu/'
for variant in font_variants:
pdfmetrics.registerFont(TTFont(variant, os.path.join(folder, variant+'.ttf')))
""" I could have registered each font with a line like this...
pdfmetrics.registerFont(TTFont(DejaVuSans, os.path.join(folder,'DejaVuSans.ttf')))
but I like just making a list of my fonts and then iterating through it. """
## 0,0 is the bottom left corner of the page
## and there are 72 dots per inch, so on an 8.5 inch page
## the top left corner is at 8.5 * 72
## canvas actually generates an A4 sheet, but this is close enough.
x = 0; y = 8.5 * 72
canv.setFont('DejaVuSans-Bold', 30)
canv.drawString(x,y,"This is bold")
## Move down one inch to draw the next line:
y = y - 72
canv.setFont('DejaVuSans-Oblique', 30)
canv.drawString(x,y,"This is oblique, aka italic")
## Move down one inch again:
y = y - 72
canv.setFont('DejaVuSans', 30)
canv.drawString(x,y,"This is neither bold nor italic")
## Save your work
canv.save()