The Python Oracle

Print chosen worksheets in excel files to pdf in python

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Drifting Through My Dreams

--

Chapters
00:00 Print Chosen Worksheets In Excel Files To Pdf In Python
01:41 Accepted Answer Score 37
02:30 Answer 2 Score 0
02:42 Thank you

--

Full question
https://stackoverflow.com/questions/1668...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #excel #pdf #printing #export

#avk47



ACCEPTED ANSWER

Score 37


This seems like the place to put this answer.

In the simplest form:

import win32com.client

o = win32com.client.Dispatch("Excel.Application")

o.Visible = False

wb_path = r'c:\user\desktop\sample.xls'

wb = o.Workbooks.Open(wb_path)



ws_index_list = [1,4,5] #say you want to print these sheets

path_to_pdf = r'C:\user\desktop\sample.pdf'



wb.WorkSheets(ws_index_list).Select()

wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)

Including a little formatting magic that scales to fit to a single page and sets the print area:

import win32com.client

o = win32com.client.Dispatch("Excel.Application")

o.Visible = False

wb_path = r'c:\user\desktop\sample.xls'

wb = o.Workbooks.Open(wb_path)



ws_index_list = [1,4,5] #say you want to print these sheets

path_to_pdf = r'C:\user\desktop\sample.pdf'

print_area = 'A1:G50'



for index in ws_index_list:

    #off-by-one so the user can start numbering the worksheets at 1

    ws = wb.Worksheets[index - 1]

    ws.PageSetup.Zoom = False

    ws.PageSetup.FitToPagesTall = 1

    ws.PageSetup.FitToPagesWide = 1

    ws.PageSetup.PrintArea = print_area



wb.WorkSheets(ws_index_list).Select()

wb.ActiveSheet.ExportAsFixedFormat(0, path_to_pdf)

I have also started a module over a github if you want to look at that: https://github.com/spottedzebra/excel/blob/master/excel_to_pdf.py




ANSWER 2

Score 0


Yes Kashyap, I concluded that in python, it is not possible basically. SO I went into the realm of JVM languages instead.