Print PDF from excel using Dynamo

So I’m using Dynamo to fill in a ready prepared, formatted, Excel sheet.

I’d love to be able to get a PDF of the Excel sheet without having to open Excel and click, “print PDF”…

Now it seems pretty easy in Python 3… But sadly I only have Revit 2021 so am in IronPython.

I’ve tried several different ways but none work. I can’t even import win32com.Client so have had to work around that too.

Anyone help or is what I’m asking not possible and do I have to dream of the day I get a Revit upgrade?

Here’s some of the mess I’ve already tried:

Hi,
here an example using interrop

xls_to_pdf

import clr
import sys
import System
from System import Array
from System.Collections.Generic import *

clr.AddReference('System.Windows.Forms')
import System.Windows.Forms
from System.Windows.Forms import SaveFileDialog, DialogResult

clr.AddReferenceByName('Microsoft.Office.Interop.Excel, Version=11.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c' )
from Microsoft.Office.Interop import Excel
from System.Runtime.InteropServices import Marshal

xlTypePDF = Excel.XlFixedFormatType.xlTypePDF

class Xls_Utils():
	def __init__(self, path ,nameSheet = 1):
		self._path = path
		self._nameSheet = nameSheet
		
	def ExportPdf(self):
		ex = Excel.ApplicationClass()
		ex.Visible = False
		lst_xls = []
		workbook = ex.Workbooks.Open(Filename=self._path, ReadOnly=True)
		ws = workbook.Worksheets[self._nameSheet]
		ws.Activate()
		pages = ws.PageSetup.Pages.Count
		print(pages)
		saveXlsxFileDialog = SaveFileDialog()
		saveXlsxFileDialog.Title = 'Name of PDF'
		saveXlsxFileDialog.FileName = "{}_{}".format(System.IO.Path.GetFileNameWithoutExtension(self._path), str(self._nameSheet))
		saveXlsxFileDialog.DefaultExt = "pdf"
		saveXlsxFileDialog.Filter = "pdf files (*.pdf)|*.pdf|All files (*.*)|*.*"
		saveXlsxFileDialog.RestoreDirectory = True
		saveXlsxFileDialog.InitialDirectory = System.IO.Path.GetDirectoryName(self._path)
		resultSaveAs = saveXlsxFileDialog.ShowDialog()
		if resultSaveAs == DialogResult.OK:
			fullpath = saveXlsxFileDialog.FileName 
			workbook.ExportAsFixedFormat(Type=xlTypePDF, FileName=fullpath, From=1, To=pages)
		ex.Workbooks.Close()
		ex.Quit()
		#other proper way to make sure that you really closed and released all COM objects 
		Marshal.ReleaseComObject(workbook)
		Marshal.ReleaseComObject(ex)


input = IN[0]
xls_sheetName = IN[1]
obj_xls = Xls_Utils(input, xls_sheetName)
obj_xls.ExportPdf()

which python3 package would you have used ?

3 Likes

Thanks! I’ll see if I can get that to work - watch this space :slight_smile:

I’ve not actually tried it in Python 3 but everything I read made it look really easy. The bit of code above was for Py3. Everything else said install win32com.Client

1 Like