Paragraph

Adding Paragraph text to PDF by Python ReportLab with style properties, layout and formats


We can import Paragraph and ParagraphStyle
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
Paragraph
We can declare a set of style properties
my_Style=ParagraphStyle('My Para style',
fontName='Times-Roman',
backColor='#F1F1F1',
fontSize=16,
borderColor='#FFFF00',
borderWidth=2,
borderPadding=(20,20,20),
leading=20,
alignment=0
)
Alignment of Paragraph text
Connect this style properties to our paragraph like this.
p1=Paragraph(''' my text here ''', my_Style)

Layout

Layout of Paragraph on Canvas

We have delcared a Canvas like this .
my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf' 
c = canvas.Canvas(my_path, pagesize=A4)
Place our Paragraph on the canvas like this.
p1.wrapOn(c,300,50)
p1.drawOn(c,width-450,height-350)

c.save()
Full code is here
from reportlab.pdfgen import canvas
from reportlab.lib.styles import ParagraphStyle
from reportlab.platypus import Paragraph
from reportlab.lib.pagesizes import  A4

my_Style=ParagraphStyle('My Para style',
fontName='Times-Roman',
backColor='#F1F1F1',
fontSize=16,
borderColor='#FFFF00',
borderWidth=2,
borderPadding=(20,20,20),
leading=20,
alignment=0
)

width,height=A4
my_path='G:\\My drive\\testing\\pypdf2\\my_pdf.pdf' 
c = canvas.Canvas(my_path, pagesize=A4)

p1=Paragraph('''<b>About this online classes </b><BR/>\
     Welcome to our online classes.<BR/> \
	 You can learn Python, PHP, database like MySQL \
SQLite and many more \
<font face="times" color="blue">We are creating \
PDF by using ReportLab</font> \
<i>This is part of our Final report.</i>''',my_Style)

p1.wrapOn(c,300,50)
p1.drawOn(c,width-450,height-350)
c.save()

Handling Long Text with Automatic Page Breaks in ReportLab



We can easily manage content across multiple pages by using the SimpleDocTemplate along with flowables like Paragraph and Spacer.

Here we are adding automatically page breaks in a PDF document when dealing with extensive ( long ) text.

Steps to Create the PDF

  1. Import Libraries: Import necessary modules from ReportLab.
  2. Create PDF Document: Define the path and create a SimpleDocTemplate object.
    The SimpleDocTemplate class is a part of the reportlab.platypus module, which stands for "Page Layout and Typography Using Scripts." It provides a high-level interface for creating PDF documents with a variety of layout features, including text, images, tables, and other elements.
  3. Define Styles: Use getSampleStyleSheet to get a default style sheet.
  4. Prepare Long Text: Define the long text content to be added to the PDF.
  5. Create Flowables: Split the long text into paragraphs and create flowable elements like Paragraph and Spacer.
  6. Build the Document: Use the build method of SimpleDocTemplate to generate the PDF with the flowable elements.



Creating PDF Files with Automatic Page Breaks for Long Text Using ReportLab on Colab Part -1

Example 1 : using SimpleDocTemplate

from reportlab.lib.pagesizes import letter
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer

# Create a PDF document
my_path='D:\\testing\\my_pdf\\my_pdf.pdf'  # Change this path 

doc = SimpleDocTemplate(my_path, pagesize=letter)

# Get a sample style sheet
styles = getSampleStyleSheet()
style = styles["Normal"]

# Long text for the paragraphs
long_text = """
plus2net.com is an invaluable resource for programmers and students looking to enhance their skills 
in various web programming languages. 

The site offers a comprehensive Python section that covers a wide range of topics, 
from basic syntax and data types to advanced concepts like decorators, generators, and context managers. 

Detailed tutorials, practical examples, and clear explanations make it easy for learners at all levels 
to understand and apply Python programming in real-world scenarios. 

Whether you are just starting out or looking to refine your skills, plus2net.com's Python section 
is designed to provide the knowledge and tools you need to succeed.
...
""" * 5  # Repeated to ensure long text

# Create a list of flowables
elements = []

# Split the long text into paragraphs and add to the elements list
for paragraph in long_text.split("\n"):
    elements.append(Paragraph(paragraph, style))
    elements.append(Spacer(1, 12))  # Add space between paragraphs

# Build the PDF document with the flowables
doc.build(elements)

Example 2 : using canvas

Creating PDF Files with Automatic Page Breaks for Long Text Using ReportLab Canvas on Colab Part-2


Here by using canvas and Paragraph objects we will ensure that the text is neatly divided across pages, maintaining readability and structure.
from reportlab.lib.pagesizes import letter
from reportlab.pdfgen import canvas
from reportlab.lib.styles import getSampleStyleSheet
from reportlab.platypus import Paragraph

# Create a canvas
my_path='D:\\testing\\my_pdf\\my_pdf.pdf' 
c = canvas.Canvas(my_path, pagesize=letter)

# Get a sample style sheet
styles = getSampleStyleSheet()
style = styles["Normal"]

# Long text for the paragraphs
long_text = """
plus2net.com is an invaluable resource for programmers and students looking to enhance their skills 
in various web programming languages. 

The site offers a comprehensive Python section that covers a wide range of topics, 
from basic syntax and data types to advanced concepts like decorators, generators, and context managers. 

Detailed tutorials, practical examples, and clear explanations make it easy for learners at all levels 
to understand and apply Python programming in real-world scenarios. 

Whether you are just starting out or looking to refine your skills, plus2net.com's Python section 
is designed to provide the knowledge and tools you need to succeed.
...
""" * 5  # Repeated to ensure long text

# Define the page dimensions and margins
page_width, page_height = letter
left_margin = 50
right_margin = 50
top_margin = 50
bottom_margin = 50
usable_width = page_width - left_margin - right_margin
usable_height = page_height - top_margin - bottom_margin

# Initial position for the first paragraph
x = left_margin
y = page_height - top_margin

# Split the long text into paragraphs
paragraphs = long_text.split("\n")

for paragraph_text in paragraphs:
    paragraph = Paragraph(paragraph_text, style)
    
    # Wrap the paragraph to fit within the usable width
    width, height = paragraph.wrap(usable_width, usable_height)
    
    # Check if the paragraph fits on the current page
    if y - height < bottom_margin:
        # If not, start a new page
        c.showPage()
        y = page_height - top_margin  # Reset y position
    
    # Draw the paragraph on the canvas
    paragraph.drawOn(c, x, y - height)
    y -= height + 12  # Update y position for the next paragraph (12 is the space between paragraphs)

# Save the canvas
c.save()


PDF Mark sheet by using data from SQLite database
PDF

Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com



    26-11-2023

    how can you continue your paragraph on next page if it doesnt end on that page of A4 size

    Post your comments , suggestion , error , requirements etc here





    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer