Certainly! You can create a PDF in Python without using FPDF by leveraging the ReportLab library, which is a powerful and flexible library for generating PDFs. Below is the rewritten version of your code using ReportLab.
Installation
First, ensure you have ReportLab installed. You can install it using pip:
pip install reportlab
Complete Code Using ReportLab
from reportlab.lib.pagesizes import A4
from reportlab.lib.styles import getSampleStyleSheet, ParagraphStyle
from reportlab.lib.enums import TA_CENTER, TA_LEFT
from reportlab.platypus import SimpleDocTemplate, Paragraph, Spacer
from reportlab.lib.units import cm
def criar_pdf():
# Define the PDF file name and page size
pdf = SimpleDocTemplate(
"O_Pequeno_Príncipe.pdf",
pagesize=A4,
rightMargin=2*cm,
leftMargin=2*cm,
topMargin=2*cm,
bottomMargin=2*cm
)
# Initialize styles
styles = getSampleStyleSheet()
# Custom style for the header/title
title_style = ParagraphStyle(
'TitleStyle',
parent=styles['Heading1'],
fontName='Helvetica-Bold', # Arial equivalent
fontSize=16,
alignment=TA_CENTER,
spaceAfter=10
)
# Custom style for chapter titles
chapter_title_style = ParagraphStyle(
'ChapterTitleStyle',
parent=styles['Heading2'],
fontName='Helvetica-Bold',
fontSize=12,
alignment=TA_LEFT,
spaceAfter=5
)
# Custom style for the body text
body_style = ParagraphStyle(
'BodyStyle',
parent=styles['BodyText'],
fontName='Helvetica',
fontSize=12,
leading=14,
alignment=TA_LEFT
)
# Custom style for indented body text
body_indent_style = ParagraphStyle(
'BodyIndentStyle',
parent=styles['BodyText'],
fontName='Helvetica',
fontSize=12,
leading=14,
leftIndent=20, # Adjust indentation as needed
alignment=TA_LEFT
)
# Create a list to hold the PDF elements
story = []
# Add the header/title
title = 'O Pequeno Príncipe'
story.append(Paragraph(title, title_style))
# Add "Ficha Técnica" section
story.append(Paragraph('Ficha Técnica:', chapter_title_style))
ficha_tecnica = (
'Autor: Antoine de Saint-Exupéry<br/>'
'Ano de Publicação: 1943<br/>'
'Gênero: Literatura Infantil, Fábula'
)
story.append(Paragraph(ficha_tecnica, body_indent_style))
story.append(Spacer(1, 12)) # Add space after this section
# Add "Sinopse" section
story.append(Paragraph('Sinopse:', chapter_title_style))
sinopse = (
'"O Pequeno Príncipe" conta a história de um piloto que cai no deserto e encontra um garotinho vindo de '
'outro planeta. Eles conversam sobre amizade, amor e o sentido da vida. Através dessas conversas, o autor '
'mostra lições importantes sobre ser humano e valorizar as relações com os outros. O livro é simples, bonito '
'e ensina coisas que todos podem entender.'
)
story.append(Paragraph(sinopse, body_style))
story.append(Spacer(1, 12)) # Add space after this section
# Add "Feito por" section
story.append(Paragraph('Feito por:', chapter_title_style))
assinaturas = 'CARLOS EDUARDO, LORENZO, LUCAS, OITAVO ANO A'
story.append(Paragraph(assinaturas, body_style))
# Build the PDF
pdf.build(story)
if __name__ == '__main__':
criar_pdf()
Explanation of the Code
-
Imports:
reportlab.lib.pagesizes.A4: Defines the page size.
reportlab.lib.styles: Used to create and manage text styles.
reportlab.platypus: Provides high-level classes for building documents (SimpleDocTemplate, Paragraph, Spacer).
reportlab.lib.units.cm: Allows you to define margins and spacing in centimeters.
-
Document Setup:
SimpleDocTemplate is used to create the PDF document, specifying the filename, page size, and margins.
-
Styles:
- Title Style: Centered, bold, 16pt font for the main title.
- Chapter Title Style: Left-aligned, bold, 12pt font for section headers.
- Body Style: Left-aligned, regular, 12pt font for the main content.
- Indented Body Style: Similar to the body style but with a left indent for specific sections like "Ficha Técnica".
-
Building the Content (story):
- Title: Added using the
title_style.
- Ficha Técnica: Section title followed by indented body text.
- Sinopse: Section title followed by regular body text.
- Feito por: Section title followed by names.
-
Spacing:
Spacer is used to add vertical space between sections for better readability.
-
Building the PDF:
pdf.build(story) compiles all the elements into the final PDF document.
Running the Code
Save the above script to a Python file, for example, create_pdf.py. Then run the script using Python:
python create_pdf.py
This will generate a PDF named O_Pequeno_Príncipe.pdf in the same directory as your script.
Customization
-
Fonts: ReportLab uses Helvetica by default, which is a close equivalent to Arial. If you need to use different fonts, you can register them using reportlab.pdfbase.ttfonts and reportlab.pdfbase.pdfmetrics.
-
Indentation: Adjust the leftIndent value in body_indent_style to increase or decrease the indentation for the "Ficha Técnica" section.
-
Additional Styling: You can further customize styles by modifying attributes like spaceBefore, spaceAfter, leading, etc.
Conclusion
Using ReportLab provides a robust and flexible way to generate PDFs in Python without relying on FPDF. It offers extensive customization options, making it suitable for a wide range of PDF generation tasks.