[英]Python: Creating PDF from PNG images and CSV tables using reportlab
我正在嘗試使用一系列 PDF 圖像創建一個 PDF 文檔,並使用 python package 報告實驗室創建一系列 CSV 表格。 桌子讓我有點悲傷。
到目前為止,這是我的代碼:
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?
根據reportlab 文檔,第 14 頁,“繪制字符串方法在 canvas 上繪制單行文本。”。 您可能想看看同一頁上的“文本 object 方法”。
您可能想考慮將 PyMuPDF 與故事一起使用,它允許從數據輸入中更靈活地布局。 有關與您要實現的目標非常相似的示例,請參見: https://pymupdf.readthedocs.io/en/latest/recipes-stories.html#how-to-display-a-list-from-json-數據
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.