Step 1: Install Required Libraries
Before we begin, you’ll need to install the following libraries if you don’t already have them:
pip install reportlab
pip install openpyxl
app.py
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 |
import openpyxl from reportlab.lib.pagesizes import letter from reportlab.lib import colors from reportlab.pdfgen import canvas def excel_to_pdf(excel_file, pdf_file): # Load the Excel file using openpyxl wb = openpyxl.load_workbook(excel_file) sheet = wb.active # Assuming we want to work with the active sheet # Create a PDF canvas c = canvas.Canvas(pdf_file, pagesize=letter) width, height = letter # Get the size of the letter page # Set some starting position for text x_offset = 30 y_offset = height - 40 # Starting position from top of the page # Set font for the PDF c.setFont("Helvetica", 8) # Loop through each row and column in the Excel sheet for row in sheet.iter_rows(min_row=1, max_row=sheet.max_row, min_col=1, max_col=sheet.max_column): for idx, cell in enumerate(row): # Add the cell data to the PDF c.drawString(x_offset + idx * 100, y_offset, str(cell.value)) # Move to the next row (down by 12 points) y_offset -= 12 # If the content exceeds the page height, add a new page if y_offset < 40: c.showPage() # Start a new page c.setFont("Helvetica", 8) y_offset = height - 40 # Reset y offset to the top # Save the PDF document c.save() # Example usage excel_file = 'sample.xlsx' # Replace with your Excel file path pdf_file = 'output.pdf' # Replace with the desired PDF output file path excel_to_pdf(excel_file, pdf_file) |