2016-07-27 115 views
1

我想在reportlab中开始。我知道如何添加字符串,行等。现在我想能够将静态文本与段落结合起来,并且静态文本需要位于特定位置。对于缩进错误感到抱歉。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() 

回答

0

从你的要求很清楚,你正在寻找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)