Python reportlab 在第一页完全充满文本后动态创建新页面

标签 python pdf text reportlab

Python 3.8 x64 | Python 3.8 x64 | Python 3.8 x64 Windows 10 x64 | Windows 10 x64 reportlab v3.5.46(开源)

到处寻找这个问题的答案,但没有结果。我只想创建一个包含大量文本的 PDF 文档。当第一页完全充满文本后,剩余的文本应该流到第二页。当第二页完全充满文本后,剩余的文本应该流到第三页(依此类推)...

我通过互联网在世界各地搜索时找到的所有答案都表明使用 canvas.showPage() 方法。这不是一个很好的解决方案,因为在所有这些示例中,第一页都没有完全填充文本,因此它是添加新页面的手动方法。在我的示例中,我不知道第一页何时会填充文本,因此我不知道何时需要使用 canvas.showPage() 创建第二个或新页面。

我需要以某种方式检测第一页何时无法容纳更多文本,并在发生这种情况时创建一个新页面来容纳剩余的文本。

通过阅读reportlabs文档,我不确定如何在实际的Pythonic实现中实现这一点。还有 platypus.PageBreak()BaseDocTemplate.afterPage() 方法,但不确定它们的作用,因为这些方法的文档很少。

我认为我使用的代码对于我的问题没有多大值(value),但它包含在下面以供引用。函数参数my_text是多页文本量。

from reportlab.pdfgen.canvas import Canvas
from reportlab.lib.pagesizes import LETTER
from reportlab.lib.units import inch


def create_pdf_report_text_object(my_text):
    canvas = Canvas('Test.pdf', pagesize=LETTER)
    canvas.setFont('Helvetica', size=10)
    text_object = canvas.beginText(x=1 * inch, y=10 * inch)

    for line in my_text.splitlines(False):
        text_object.textLine(line.rstrip())

    canvas.drawText(text_object)
    canvas.save()

最佳答案

我相信解决您问题的一个方法是使用框架,这意味着框架会在每个页面上重新创建,直到文本用完。框架将检测何时已满。

请参阅下面的示例作为您自己的解决方案的开始(其完整,只需复制并粘贴并运行代码,应创建一个名为“Example_output.pdf”的 pdf)。

from reportlab.lib.pagesizes import letter
from reportlab.platypus import Paragraph
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.platypus import BaseDocTemplate, PageTemplate, Flowable, FrameBreak, KeepTogether, PageBreak, Spacer
from reportlab.platypus import Frame, PageTemplate, KeepInFrame
from reportlab.lib.units import cm
from reportlab.platypus import (Table, TableStyle, BaseDocTemplate)

styleSheet = getSampleStyleSheet()

########################################################################

def create_pdf():
    """
    Create a pdf
    """

    # Create a frame
    text_frame = Frame(
        x1=3.00 * cm,  # From left
        y1=1.5 * cm,  # From bottom
        height=19.60 * cm,
        width=15.90 * cm,
        leftPadding=0 * cm,
        bottomPadding=0 * cm,
        rightPadding=0 * cm,
        topPadding=0 * cm,
        showBoundary=1,
        id='text_frame')

    # Create text

    L = [Paragraph("""What concepts does PLATYPUS deal with?""", styleSheet['Heading2']),
                          Paragraph("""
                         The central concepts in PLATYPUS are Flowable Objects, Frames, Flow
                         Management, Styles and Style Sheets, Paragraphs and Tables.  This is
                         best explained in contrast to PDFgen, the layer underneath PLATYPUS.
                         PDFgen is a graphics library, and has primitive commans to draw lines
                         and strings.  There is nothing in it to manage the flow of text down
                         the page.  PLATYPUS works at the conceptual level fo a desktop publishing
                         package; you can write programs which deal intelligently with graphic
                         objects and fit them onto the page.
                         """, styleSheet['BodyText']),

                          Paragraph("""
                         How is this document organized?
                         """, styleSheet['Heading2']),

                          Paragraph("""
                         Since this is a test script, we'll just note how it is organized.
                         the top of each page contains commentary.  The bottom half contains
                         example drawings and graphic elements to whicht he commentary will
                         relate.  Down below, you can see the outline of a text frame, and
                         various bits and pieces within it.  We'll explain how they work
                         on the next page.
                         """, styleSheet['BodyText']),
                          ]






    # Building the story
    story = L * 20 # (alternative, story.add(L))
    story.append(KeepTogether([]))

    # Establish a document
    doc = BaseDocTemplate("Example_output.pdf", pagesize=letter)

    # Creating a page template
    frontpage = PageTemplate(id='FrontPage',
                             frames=[text_frame]
                             )
    # Adding the story to the template and template to the document
    doc.addPageTemplates(frontpage)

    # Building doc
    doc.build(story)


# ----------------------------------------------------------------------
if __name__ == "__main__":
    create_pdf() # Printing the pdf 

关于Python reportlab 在第一页完全充满文本后动态创建新页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63441401/

相关文章:

Python/selenium 网络抓取

java - 从 PDPage#getMediaBox() 获取 null

css - 文本不会填充列中的容器

python - Python 中的 readline() 错误

python - 使用协议(protocol)参数对包装函数进行类型检查

python - repr 和 str 在 Python 的内置数字类型上总是相同的吗?

c# - 将具有透明度的 PDF 转换为无光栅化的 EPS

ios - 如何同时更改 iOS 按钮的图像和文本?

python - 使用 QWebEngine 在同一窗口中打开任何链接(甚至_blank)

java - xfa.fillXfaForm 之后透明图像显示为黑框。 xfa 填充是否支持透明图像?