Python:使用reportlab从PNG图像和CSV表创建PDF

jfewjypa  于 2023-01-10  发布在  Python
关注(0)|答案(2)|浏览(166)

我正在尝试使用一系列PDF图像和一系列CSV表格创建一个PDF文档,这些表格给了我一点悲伤。
这是我的代码:

import os
import pandas as pd
import matplotlib.pyplot as plt
import numpy as np

from reportlab.lib.pagesizes import letter
from reportlab.platypus import SimpleDocTemplate
from reportlab.pdfgen.canvas import Canvas
from reportlab.platypus import *
from reportlab.platypus.tables import Table
from PIL import Image
from matplotlib.backends.backend_pdf import PdfPages

# Set the path to the folder containing the images and tables
folder_path = 'Files'

# Create a new PDF document
pdf_filename = 'testassessment.pdf'
canvas = Canvas(pdf_filename)

# Iterate through the files in the folder
for file in os.listdir(folder_path):
  file_path = os.path.join(folder_path, file)
  
  # If the file is an image, draw it on the PDF
  if file.endswith('.png'):
    canvas.drawImage(file_path, 105, 148.5, width=450, height=400) 
    canvas.showPage() #ends page
    
  # If the file is a table, draw it on the PDF
  elif file.endswith('.csv'):
    df = pd.read_csv(file_path)
    table = df.to_html()
    canvas.drawString(10, 10, table)
    canvas.showPage() 
    
# Save the PDF
canvas.save()

表不工作。当我使用. drawString时,它最终看起来像这样:

有人知道我如何才能把表格正确地插入到PDF中吗?

0wi1tuuw

0wi1tuuw1#

根据reportlab docs,第14页,“draw string方法在画布上绘制单行文本。"您可能想看看同一页上的“text对象方法”。

wpx232ag

wpx232ag2#

你可能会考虑使用PyMuPDF和Stories,它允许数据输入的布局更加灵活。关于与你尝试实现的非常相似的示例,请参见:https://pymupdf.readthedocs.io/en/latest/recipes-stories.html#how-to-display-a-list-from-json-data

相关问题