在reportlab中创建和修复带有边距和文本样式的PDF

问题描述 投票:0回答:1

我在使用 Python 中的 ReportLab 创建报告时遇到问题。

我正在使用 AWS S3 存储桶中的 JSON 文件。以下是信息示例:

from reportlab.lib.pagesizes import A1
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm

    
company_info = [
    {'title': 'What were Harley\'s total sales for Q3?', 
     'context': 'Harley\'s total sales for Q3 were /n **$15 million**, representing a **10% increase** compared to Q2.'},
    {'title': 'Which region showed the highest sales?', 
     'context': 'The **North American region** showed the highest sales, contributing **$8 million** to the total.'},
    {'title': 'What was the percentage increase in sales for the European market?', 
     'context': 'The **European market** experienced a /n **12% increase** in sales, totaling **$4 million** for Q3.'},
    {'title': 'Did Harley\'s introduce any new products in Q3?', 
     'context': ('In Q3, Harley\'s made a significant impact with the introduction of **two new products** that have been well-received by the market. '
                 'The **Harley Davidson X1** is a cutting-edge motorcycle designed with advanced technology and performance enhancements, catering to the evolving needs of enthusiasts. '
                 'Alongside, the **Harley Davidson Pro Series** offers a range of high-performance accessories aimed at enhancing the riding experience. '
                 'These new products have been introduced in response to customer feedback and market trends, reflecting Harley\'s commitment to innovation and quality. '
                 'The product launches have been supported by comprehensive marketing efforts, including promotional events and digital campaigns, which have effectively generated excitement and increased consumer interest.')},
    {'title': 'What was the impact of the new product launches on sales?', 
     'context': ('The recent product launches had a substantial impact on Harley\'s sales performance for Q3. The introduction of the **Harley Davidson X1** and the **Harley Davidson Pro Series** '
                 'contributed an additional **$2 million** in revenue, accounting for approximately **13%** of the total Q3 sales. '
                 'These new products not only boosted overall sales but also enhanced Harley\'s market position by attracting new customers and increasing repeat purchases. '
                 'The successful integration of these products into the company\'s existing lineup demonstrates Harley\'s ability to innovate and adapt to market demands. '
                 'Ongoing customer feedback and sales data will continue to inform product development and marketing strategies, ensuring that Harley\'s maintains its competitive edge and meets consumer expectations.')},
]

我正在使用此代码生成报告,并且我想包含背景图像。

def create_report(company_info, image_path, output_pdf_path):
    # Define margins
    top_margin = 12 * cm
    bottom_margin = 8 * cm
    left_margin = 2 * cm
    right_margin = 2 * cm
    
    # Create a canvas object
    c = canvas.Canvas(output_pdf_path, pagesize=A1)
    
    # Draw the background image
    c.drawImage(image_path, 0, 0, width=A1[0], height=A1[1])
    
    # Define text properties
    font_size = 18
    c.setFont("Helvetica-Bold", font_size)
    
    # Calculate y position
    y_position = A1[1] - top_margin
    
    # Write the content
    for i, item in enumerate(company_info):
        question = item.get('title', '')
        answer = item.get('context', '')
        
        # Write question number and question
        c.setFont("Helvetica-Bold", font_size)
        c.drawString(left_margin, y_position, f'{i + 1}. {question}')
        y_position -= font_size + 10  # Adjust for line spacing
        
        # Write answer
        c.setFont("Helvetica", font_size)
        c.drawString(left_margin, y_position, answer)
        y_position -= 2 * font_size + 30  # Adjust for space between question and answer
        
        # Check if y position is below the bottom margin
        if y_position < bottom_margin:
            c.showPage()
            c.drawImage(image_path, 0, 0, width=A1[0], height=A1[1])
            y_position = A1[1] - top_margin
            c.setFont("Helvetica-Bold", font_size)  # Reapply font settings for new page

    # Save the PDF
    c.save()


bg = 'bg_temp.jpg'  # Path to your background image
output_pdf_path = 'report_harleys.pdf'  # Path where the PDF will be saved

create_report(company_info, bg, output_pdf_path)

尽管我进行了多次尝试,但我尚未实现以下目标:

对齐文本(标题和上下文),使其不超出页面的右边缘。 确保由指定的新行 我的 JSON 中 ** 指示的粗体文本正确反映在 PDF 中。

这是我目前得到的:

enter image description here

我希望它看起来像这样: enter image description here

注意如何使用 我们有一个新行,**之间的文本是粗体吗?参考公司资料第一项

如果您能指出我的代码中需要修复的任何行或我可能缺少的任何内容,我将非常感激。我尝试了很多教程,但没有达到预期的结果。非常感谢!

python pdf reportlab
1个回答
0
投票

我已经尽力了

我从 ChatGPT 得到了巨大的帮助。

我试图使每个**文本**粗体,但问题是我无法每次想要粗体时更改字体,所以ChatGPT为每个需要粗体的单词添加了新行,


from reportlab.lib.pagesizes import A1
from reportlab.pdfgen import canvas
from reportlab.lib.units import cm



def draw_wrapped_text(c, text, x, y, max_width):
    is_bold = False  # To track whether the text should be bold
    start_pos = 0
    y_offset = 1.2 * cm

    while start_pos < len(text):
        # Find the next bold markers
        if '**' in text[start_pos:]:
            bold_start = text.find('**', start_pos)
            bold_end = text.find('**', bold_start + 2)

            if bold_start > start_pos:
                # Draw text before the bold marker
                normal_text = text[start_pos:bold_start].replace('\n', ' ')
                y = draw_text_segment(c, normal_text, x, y, max_width, is_bold=False)

            # Draw the bold text
            bold_text = text[bold_start + 2:bold_end].replace('\n', ' ')
            y = draw_text_segment(c, bold_text, x, y, max_width, is_bold=True)

            # Update the position after the bold text
            start_pos = bold_end + 2
        else:
            # Draw the remaining text as normal
            normal_text = text[start_pos:].replace('\n', ' ')
            y = draw_text_segment(c, normal_text, x, y, max_width, is_bold=False)
            break

    return y  # Return the updated y position after the text is drawn


def draw_text_segment(c, text, x, y, max_width, is_bold):
    lines = []
    current_line = ""
    
    font = "Helvetica-Bold" if is_bold else "Helvetica"
    c.setFont(font, 12)

    for word in text.split():
        if c.stringWidth(current_line + " " + word, font, 12) <= max_width:
            current_line += " " + word
        else:
            lines.append(current_line.strip())
            current_line = word
    
    lines.append(current_line.strip())

    for line in lines:
        c.drawString(x, y, line)
        y -= 1.2 * cm

    return y

# Create the canvas object
c = canvas.Canvas("company_report.pdf", pagesize=A1)
width, height = A1

company_info = [
    {'title': "What were Harley's total sales for Q3?", 
     'context': "Harley's total sales for Q3 were \n **$15 million**, representing a **10% increase** compared to Q2."},
    
    {'title': "Which region showed the highest sales?", 
     'context': "The **North American region** showed the highest sales, contributing **$8 million** to the total."},
    
    {'title': "What was the percentage increase in sales for the European market?", 
     'context': "The **European market** experienced a \n **12% increase** in sales, totaling **$4 million** for Q3."},
    
    {'title': "Did Harley's introduce any new products in Q3?", 
     'context': ("In Q3, Harley's made a significant impact with the introduction of **two new products** that have been well-received by the market. "
                 "The **Harley Davidson X1** is a cutting-edge motorcycle designed with advanced technology and performance enhancements, catering to the evolving needs of enthusiasts. "
                 "Alongside, the **Harley Davidson Pro Series** offers a range of high-performance accessories aimed at enhancing the riding experience. "
                 "These new products have been introduced in response to customer feedback and market trends, reflecting Harley's commitment to innovation and quality. "
                 "The product launches have been supported by comprehensive marketing efforts, including promotional events and digital campaigns, which have effectively generated excitement and increased consumer interest.")},
    
    {'title': "What was the impact of the new product launches on sales?", 
     'context': ("The recent product launches had a substantial impact on Harley's sales performance for Q3. The introduction of the **Harley Davidson X1** and the **Harley Davidson Pro Series** "
                 "contributed an additional **$2 million** in revenue, accounting for approximately **13%** of the total Q3 sales. "
                 "These new products not only boosted overall sales but also enhanced Harley's market position by attracting new customers and increasing repeat purchases. "
                 "The successful integration of these products into the company's existing lineup demonstrates Harley's ability to innovate and adapt to market demands. "
                 "Ongoing customer feedback and sales data will continue to inform product development and marketing strategies, ensuring that Harley's maintains its competitive edge and meets consumer expectations.")}
]

# Start writing the content
y = height - 2 * cm  # Initial y position

for item in company_info:
    title = item['title']
    context = item['context']
    
    # Draw the title in bold
    c.setFont("Helvetica-Bold", 16)
    c.drawString(2 * cm, y, title)
    y -= 1.5 * cm  # Space between title and context
    
    # Draw the context with wrapped text
    y = draw_wrapped_text(c, context, 2 * cm, y, width - 4 * cm)
    y -= 2 * cm  # Space between entries

# Save the PDF
c.save()

我希望你使用另一个库,比如FPDF2,它比这个库更好,除非你只想要这个库中的功能,但我在这里没有看到特殊功能。

© www.soinside.com 2019 - 2024. All rights reserved.