gpt4 book ai didi

python - 我想在 pdf 中创建粗体和普通文本

转载 作者:太空宇宙 更新时间:2023-11-03 18:42:08 28 4
gpt4 key购买 nike

我可以使用reportlab从txt文件创建pdf文件。这很容易,但我想做一些文本是粗体,一些是正常的,一些是斜体。我怎样才能做到这一点?

最佳答案

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()

关于python - 我想在 pdf 中创建粗体和普通文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20303070/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com