Category / Section
How to convert each worksheet with different ExcelToPdfConverterSettings while Excel to PDF conversion
1 min read
It is possible to convert Excel workbook to PDF with different converter settings for each worksheet. This can be achieved by carry forwarding the PdfDocument through TemplateDocument property available in ExcelToPdfConverterSettings.
The following code snippet explains this.
using (ExcelEngine excelEngine = new ExcelEngine()) { IApplication application = excelEngine.Excel; application.DefaultVersion = ExcelVersion.Excel2016; IWorkbook workbook = application.Workbooks.Open("../../Data/Sample.xlsx"); //Load first worksheet into ExcelToPdfConverter ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook.Worksheets[0]); //Have ExcelToPdfConverterSettings ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings(); settings.DisplayGridLines = GridLinesDisplayStyle.Visible; settings.LayoutOptions = LayoutOptions.FitAllColumnsOnOnePage; //Convert the first worksheet to PDF with converter settings PdfDocument document = converter.Convert(settings); //Now load second worksheet into ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook.Worksheets[1]); //Have ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings(); //Note: Assigning the document to TemplateDocument in converter settings is mandatory //This will carry over the already converted worksheets settings.TemplateDocument = document; settings.DisplayGridLines = GridLinesDisplayStyle.Visible; //Convert the second worksheet to PDF with converter settings document = converter.Convert(settings); //Now load third worksheet into ExcelToPdfConverter converter = new ExcelToPdfConverter(workbook.Worksheets[2]); //Have ExcelToPdfConverterSettings settings = new ExcelToPdfConverterSettings(); //Note: Assigning the document to TemplateDocument in converter settings is mandatory //This will carry over the already converted worksheets settings.TemplateDocument = document; settings.DisplayGridLines = GridLinesDisplayStyle.Invisible; settings.LayoutOptions = LayoutOptions.FitSheetOnOnePage; //Convert the third worksheet to PDF with converter settings document = converter.Convert(settings); //Save the PDF document.Save("Output.pdf"); System.Diagnostics.Process.Start("Output.pdf"); }
A complete working sample to convert each worksheet with different ExcelToPdfConverterSettings can be downloaded from ExcelToPDF.zip.