Convert Excel to PDF using JavaScript

javascript, pdf

Solution

You're clobbering objExcel on line 15:

var objExcel = objExcel.Workbooks.Open(docPath);

Those lines of code need to use a different variable, e.g.:

var objWorkbook = objExcel.Workbooks.Open(docPath);

var wdFormatPdf = 57;
objWorkbook.SaveAs(pdfPath, wdFormatPdf);
objWorkbook.Close();

Problem

How can I convert Excel documents (files) to PDF in an automated fashion? I am trying to adapt the solution found here to Excel. So far I have this: ``` var fso = new ActiveXObject("Scripting.FileSystemObject"); var docPath = WScript.Arguments(0); docPath = fso.GetAbsolutePathName(docPath); var pdfPath = docPath.replace(/\.xls[^.]*$/, ".pdf"); var objExcel = null; try { WScript.Echo("Saving '" + docPath + "' as '" + pdfPath + "'..."); objExcel = new ActiveXObject("Excel.Application"); objExcel.Visible = false; var objExcel = objExcel.Workbooks.Open(docPath); var wdFormatPdf = 17; objExcel.SaveAs(pdfPath, wdFormatPdf); objExcel.Close(); WScript.Echo("Done."); } finally { if (objExcel != null) { objExcel.Quit(); } } ``` I get this output: ``` Saving 'somefile.xlsx' as 'somefile.pdf'... Done. ..\SaveXLSXAsPDF.js(27, 9) (null): The object invoked has disconnected from its clients. ``` A PDF file is created but it is invalid and won't open in a reader. I'm thinking that perhaps format 17 isn't the right one for Excel. Does anyone know the right number or how to get this working? Edit: I found mention of the correct number here (57) but now I get this error: ``` r:\Web\Roman\SaveXLSXAsPDF.js(27, 13) Microsoft JScript runtime error: Class doesn't support Automation ```

Original source