ReportLab:如何自动调整文本大小以适应块大小

10

我需要生成一份带有动态文本的PDF,目前我正在使用ReportLab。由于文本是动态的,是否有方法可以将其调整大小以适应PDF中的特定区域?


你是否找到了一个好的解决方案并能够分享?我已经按照下面描述的文档进行了查看,但似乎没有找到一个。我一直在尝试递归地调整段落流对象的style.fontSize以适应动态文本的大小,但这并没有起作用。 - The Pied Pipes
2个回答

10

从报告实验室版本2.0开始,platypus有了KeepInFrame。来自CHANGES.txt:

KeepInFrame:
Sometimes the length of a piece of text you'd like to include in a 
fixed piece of page "real estate" is not guaranteed to be constrained to a 
fixed maximum length. In these cases, KeepInFrame allows you to specify an 
appropriate action to take when the text is too long for the space allocated 
for it. In particular, it can shrink the text to fit, mask (truncate) 
overflowing text, allow the text to overflow into the rest of the document, or 
raise an error.

我能找到的唯一使用它的示例在reportlab源代码中的tests/目录下。这是我最终想出来的工作样例:

from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import letter, landscape
from reportlab.platypus import Paragraph, Frame, KeepInFrame
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.lib.units import inch

c = Canvas('foo.pdf', pagesize=landscape(letter))
frame1 = Frame(0.25*inch, 0.25*inch, 4*inch, 4*inch, showBoundary=1)

styles = getSampleStyleSheet()
s = "foo bar " * 1000
story = [Paragraph(s, styles['Normal'])]
story_inframe = KeepInFrame(4*inch, 8*inch, story)
frame1.addFromList([story_inframe], c)
c.save()

为了完整起见,这是版本字符串:

>python -c "import reportlab;print reportlab.Version"
2.7

1

是的。看一下ReportLab手册。根据你对想要做什么的(简短)描述,听起来你需要在页面布局中使用框架(假设你使用Platypus,我强烈推荐)。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接