Home » excel » c# – Excel to PDF export – page number limit

c# – Excel to PDF export – page number limit

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am converting Excel files to PDF using C#.
Here’s the code I’ve got so far:

Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Open(infile, 0, false, 5, "", "", true, Microsoft.Office.Interop.Excel.XlPlatform.xlWindows, "\t", false, false, 0, true, 1, 0);
excelApp.ActiveWorkbook.ExportAsFixedFormat(Excel.XlFixedFormatType.xlTypePDF, outfile);
excelApp.DisplayAlerts = false;
excelApp.SaveWorkspace();
excelApp.Quit();

That part works but sometimes I have a file with more than let’s say 20 columns, and the output “breaks” into multiple pages on the PDF.

Is there any way to control how many “breaks” I want to allow?

eg.
let’s say the sheet has 25 column
I put in a number eg. 3
first 5 columns print on the 1st page
next 5 columns print on the 2st page
next 5 columns print on the 3st page
and the execution stops (or continues to the next sheet)

I think the answer is somewhere in this (but I’m not quite sure):

((Microsoft.Office.Interop.Excel._Worksheet)excelApp.ActiveSheet).PageSetup.Pages
How to&Answers:

You should be able to accomplish this via the PageSetup class and select the appropriate PrintArea. For PDF conversion we use the ‘FitToPages’ feature to zoom the view so that each worksheet occupies only a single page wide.

_Workbook document = application.Workbooks.Open(FileName,
                     oFalse, oTrue, oMissing, oMissing, oMissing, oMissing,
                     oMissing, oMissing, oFalse, oFalse, oMissing, oFalse,
                     oFalse, oFalse);

foreach (Worksheet ws in document.Worksheets.OfType<Worksheet>())
{
    ws.PageSetup.Orientation = XlPageOrientation.xlLandscape;
    ws.PageSetup.Zoom = false;
    ws.PageSetup.FitToPagesWide = 1;
    ws.PageSetup.FitToPagesTall = false;
}

document.ExportAsFixedFormat(fxFormat, fileName,
                             oMissing, oMissing, oFalse, oMissing,
                             oMissing, oFalse, oMissing);

Or you can set the print area instead of zooming:

    // Specified in the same range format as the UI
    ws.PageSetup.PrintArea = "a1-e50";

You may need to obtain the used columns and rows from the ws.UsedRange property to supply the correct print area. Make sure when you call ‘ExportAsFixedFormat’ you provide false for the IgnorePrintAreas parameter.