【问题标题】:Reportlab mix static text and paragraphsReportlab 混合静态文本和段落
【发布时间】:2016-07-27 15:59:35
【问题描述】:

我正在尝试开始使用 reportlab。我知道如何添加字符串、线条等。现在我希望能够将静态文本与段落结合起来,并且静态文本需要位于特定位置。很抱歉出现缩进错误。

from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from reportlab.platypus import Image, SimpleDocTemplate, Paragraph, Spacer,    
from reportlab.rl_config import defaultPageSize
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_JUSTIFY


PAGE_HEIGHT=defaultPageSize[1]; PAGE_WIDTH=defaultPageSize[0]

Story = []

p = "This is a paragraph"



last_name = "John"
first_name = "Doe"
dosuren = "02-03-2016"



def generate_report(last_name, first_name, dosuren):
    pdf_file_name = last_name + first_name + "_" + dosuren + ".pdf"

    c= canvas.Canvas(pdf_file_name, pagesize=letter)

    c.setFont('Times-Bold', 12,leading=None )
    c.drawCentredString(PAGE_WIDTH/2.0, PAGE_HEIGHT-108,  "REPORT")

##### Static Text ############


c.setFont('Times-Bold', 12, leading=None)
c.drawString(30, 320, "Subject INfo:")

c.setFont('Times-Roman', 12, leading=None)
c.drawString(30, 380, "Subject info2:")

##Paragraph###
styles = getSampleStyleSheet()
styles.add(ParagraphStyle(name='Justify', alignment=TA_JUSTIFY))
Story.append(Paragraph(p, styles["Justify"]))


c.showPage()
c.save()

【问题讨论】:

    标签: python-3.x reportlab


    【解决方案1】:

    从你的需求来看,很明显你在找PageTemplate,它允许你先在页面上画一些固定的元素,然后再添加Paragraph和其他Flowable

    一个简单的例子如下所示:

    from reportlab.lib.styles import getSampleStyleSheet
    from reportlab.platypus import BaseDocTemplate, PageTemplate, Frame, Paragraph
    
    def draw_static(canvas, doc):
        # Save the current settings
        canvas.saveState()
    
        # Draw the static stuff
        canvas.setFont('Times-Bold', 12, leading=None)
        canvas.drawCentredString(200, 200, "Static element")
    
        # Restore setting to before function call
        canvas.restoreState()
    
    # Set up a basic template
    doc = BaseDocTemplate('test.pdf')
    
    # Create a Frame for the Flowables (Paragraphs and such)
    frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height, id='normal')
    
    # Add the Frame to the template and tell the template to call draw_static for each page
    template = PageTemplate(id='test', frames=[frame], onPage=draw_static)
    
    # Add the template to the doc
    doc.addPageTemplates([template])
    
    # All the default stuff for generating a document
    styles = getSampleStyleSheet()
    story = []
    
    P = Paragraph('This is a paragraph', styles["Normal"])
    
    story.append(P)
    doc.build(story)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-01-12
      相关资源
      最近更新 更多