How to resize canvas of pdf without resizing its content using python?

Viewed 24

Microsoft Excel does not always scale the sheet contents properly to minimize the white space especially if the sheet is large. When extracted to pdf it contains various amounts of whitespace, and there is very little you can do to make sure that contents fit the whole width between the A4/Letter page margins.

So what I decided to do is this:

  1. export excel files to pdf
  2. trim all white space around content of pdf
  3. Scale the content of pdf to specified width in mm
  4. Place pdf scaled contents inside the A4/Letter size

I managed to do steps 1-3 but am stuck on step number 4 and not sure how I can implement it.

import io
import os
from win32com import client
from PyPDF2 import PdfFileReader, PdfFileWriter
from reportlab.pdfgen import canvas
from reportlab.lib.pagesizes import letter
from pdfCropMargins import crop


def delete_files(files):
    for file in files:
        if os.path.exists(file):
            os.remove(file)

delete_files(['resize.pdf', 'template-cropped.pdf'])

# Open Microsoft Excel
excel = client.Dispatch("Excel.Application")

# Read Excel File
sheets = excel.Workbooks.Open('C:\\Users\\asolo\\git\\excel-to-pdf\\template.xlsx')
work_sheets = sheets.Worksheets[0]

# Remove all footers and headers
work_sheets.PageSetup.LeftFooter = ""
work_sheets.PageSetup.CenterFooter = ""
work_sheets.PageSetup.RightFooter = ""
work_sheets.PageSetup.LeftHeader = ""
work_sheets.PageSetup.CenterHeader = ""
work_sheets.PageSetup.RightHeader = ""

# Convert into PDF File
work_sheets.ExportAsFixedFormat(0, 'C:\\Users\\asolo\\git\\excel-to-pdf\\template.pdf')

# close document without saving
sheets.Close(False)
excel.Application.Quit()

crop(["-p", "0", "-dl", "template.pdf"])

def resize_pdf(input_pdf, width):
    file = open(input_pdf, 'rb')
    pdf = PdfFileReader(file)
    page0 = pdf.getPage(0)
    content_width = page0.mediaBox.getWidth()
    content_height = page0.mediaBox.getHeight()

    # convert width to mm
    content_width_mm=float(content_width)/72.0*25.4

    # coluate sacle factor
    scale_factor = width/content_width_mm

    page0.scaleBy(scale_factor)  # float representing scale factor - this happens in-place
    # close the input file

    return page0

page = resize_pdf("template-cropped.pdf", 100)

# Place page into A4/Letter size pdf

I looked into canvas but not sure how to add page which is scaled into it. Nor I been able to find any example on how to implement that. Github Copilot suggest sollutions that don't work. So I kindly as for your help the almighty developers...

I also created a repo for reference. https://github.com/asolopovas/excel-to-pdf

0 Answers
Related