Home > Mobile >  Python: Creating PDF from PNG images and CSV tables using reportlab
Python: Creating PDF from PNG images and CSV tables using reportlab

Time:01-10

I am trying to create a PDF document using a series of PDF images and a series of CSV tables using the python package reportlab. The tables are giving me a little bit of grief.

This is my code so far:

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()

The tables are not working. When I use .drawString it ends up looking like this:

Image on Imgur

Does anyone know how I can get the table to be properly inserted into the PDF?

CodePudding user response:

According to the reportlab docs, page 14, "The draw string methods draw single lines of text on the canvas.". You might want to have a look at "The text object methods" on the same page.

CodePudding user response:

You might want to consider using PyMuPDF with Stories it allows for more flexibility of layout from a data input. For an example of something very similar to what you are trying to achieve see: https://pymupdf.readthedocs.io/en/latest/recipes-stories.html#how-to-display-a-list-from-json-data

  • Related