I’m currently using ReportLab in Python to generate PDF documents with two frames, where each frame should display two paragraphs. However, the output I’m getting looks like the following:
[![enter image description here][1]][1]
My code:
def generate_pdf(output_file, df):
doc = BaseDocTemplate(output_file, pagesize=A4, topMargin=90)
styles = getSampleStyleSheet()
story = []
# Create two frames for two columns
frame_width = ((doc.width / 2) - doc.leftMargin ) + 80 # Divide the width equally between two columns
left_frame = Frame(doc.leftMargin, doc.bottomMargin, frame_width, doc.height - doc.topMargin, id='left_frame')
right_frame = Frame(doc.leftMargin + frame_width, doc.bottomMargin, frame_width, doc.height - doc.topMargin, id='right_frame')
# Create disclaimer
disclaimer_frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - doc.topMargin, id='disclaimer_frame')
# Chart Frame
chart_frame = Frame(doc.leftMargin, doc.bottomMargin, doc.width, doc.height - doc.topMargin, id='chart_frame')
title_style = ParagraphStyle(name='Title', fontName='Helvetica-Bold', fontSize=12, leading=16)
content_style = ParagraphStyle(name='BodyText', fontName='Helvetica', fontSize=9, leading=14)
content_style.alignment = 0 # Justify alignment
for index, row in df.iterrows():
title = row['Title']
hyperlink = row['Hyperlink']
paragraph = row['Text']
# Create a hyperlink with the title
title_para = Paragraph(f'<a href="{hyperlink}">{title}</a>', title_style)
story.append(title_para)
# Add space between title and content
story.append(Spacer(1, 6)) # Adjust the height as needed
# Add paragraph content
p = Paragraph(paragraph, content_style)
story.append(p)
# Define page templates for both news content and disclaimer
news_template = PageTemplate(id='news_page', frames=[left_frame, right_frame], onPage=add_header_title)
# Build the news content first
doc.addPageTemplates([PageTemplate(id='news_page', frames=[left_frame, right_frame], onPage=add_header_title),
PageTemplate(id='charts_page', frames=[chart_frame], onPage=add_header),
PageTemplate(id='Disclaimer',frames=[disclaimer_frame],onPage=add_header),
])
doc.build(story)
The articles originated from CSV files, where I crafted the texts:
if __name__ == "__main__":
# Get today's date
today_date = datetime.date.today()
# Format the date as needed
formatted_date = today_date.strftime("%B %d, %Y")
# Generate the output file name
output_file = f"News- {formatted_date}.pdf"
df = pd.read_excel("./02. Data/Articles.xlsx", sheet_name="articles")
generate_pdf(output_file, df)