Question

I'm using COM automation to open a xls file and print it to a virtual PDF printer.

Sheets sheets(m_Application.GetSheets());
sheets.PrintOut(CovOptional,CovOptional,CovOptional,CovOptional,COleVariant(_T("My PDF Printer")),CovOptional,CovOptional);

If the file has multiple worksheets, however, excel creates a separate print job for every sheet, so I get several PDF files instead of one.

How can I force it to print all the sheets in a single print job?

Was it helpful?

Solution

I found a very good explanation for why Excel has this behavior in this article. From the article

This happens because of the way Microsoft Excel sends the print job. Excel assumes that all your individual sheets have different page setups, so it sends them as multiple print-jobs.

In order to have all the individual sheets printed within a single PDF file (not multiple PDFs) you need to set the same page setup options for all of them (page setup in Excel modifies the print size of the resulting file, so for example if you set the page layout to landscape in Excel, the printed page will be landscape but your original Excel file will still maintain the same view).

I adapted code from an answer to a similar question. The code was originally in C# but I adapted it to C++.

Sheets sheets(m_Application.GetSheets());

for (int ii = 1; ii <= sheets.GetCount(); ii++)
{
    _Worksheet sheet(sheets.GetItem(COleVariant((long) ii)));
    PageSetup pagesetup(sheet.GetPageSetup());
    pagesetup.SetOrientation(2); // landscape
    pagesetup.SetOrder(1); // xlDownThenOver
    pagesetup.SetFitToPagesWide(COleVariant((long) 1));
    pagesetup.SetFitToPagesTall(COleVariant((long) 50));
    VARIANT variant;
    variant.vt = VT_BOOL;
    variant.boolVal = VARIANT_FALSE;
    pagesetup.SetZoom(variant);
}

sheets.PrintOut(CovOptional, CovOptional, CovOptional, CovOptional, COleVariant(_T(MyAppPrinterName)), CovOptional, CovOptional);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top