Home > front end >  Specify the number of pages in "save as pdf" in win32.client excel through python
Specify the number of pages in "save as pdf" in win32.client excel through python

Time:10-17

I am trying to change an excel file, save it and then save it as a PDF, the problem is when I save manually in excel PDF fits on 3 pages perfectly (this is mandatory) but when I do it through code it spills over to the 4th page.

I am using openpyxl to alter the xlsx and win32com.client to save it as PDF

openpyxl part:

for i in range(2, files_to_make   1):
    wb = load_workbook(file_path)
    ws = wb.active

    ws['I8'].value = i

    new_file_name = f"{prefix}{i}{suffix}"
    new_file_path = os.path.join(folder, new_file_name)
    wb.save(new_file_path)

win32com.client part:

app = win32.DispatchEx("Excel.Application")
app.Visible = False

for i in range(2, files_to_make   1):
    xlsx_path = os.path.join(folder, f"{prefix}{i}{suffix}")
    pdf_path = os.path.join(folder, f"{pdf_prefix}{i}{pdf_suffix}").replace("/", "\\")

    wb = app.Workbooks.open(xlsx_path)
    # wb.WorkSheets([1]).Select()  # redundant?
    wb.ActiveSheet.ExportAsFixedFormat(0, pdf_path)
    wb.Close(False)

app.Quit()

My question is where here can I impact the number of PDF pages the excel file is saved to and can I do that through code at all?

Reminder that default excel behavior for "Microsoft print to PDF" is to save it on 3 pages, that is what I am trying to do through this code.

Any pointers appreciated because I can't find anything in ExportAsFixedFormat documentation or any forums

CodePudding user response:

Found some documentation

Added this now it works as imagined, I wasn't aware that FitToPagesTall wasn't a boolean

ws.PageSetup.Zoom = False
ws.PageSetup.FitToPagesTall = 3
  • Related