Graphics created from PrintPreview are Portrait instead of Landscape?

3.2k Views Asked by At

I am printing custom pages in C#. When actually printing the document it works correctly, as does displaying it to a dialog (via the same code). When the code is used for PrintPreview the dialog shows the page in landscape mode but the Graphics created has dimensions of a portrait document and, as such, the preview does not show correctly. Here is a cut down version of the code I am using

using (PrintDocument pd = new PrintDocument())
{
    pd.PrinterSettings.PrintToFile = false;
    pd.DefaultPageSettings.Landscape = true;
    pd.PrinterSettings.DefaultPageSettings.Landscape = true;
    pd.DefaultPageSettings.PrinterSettings.DefaultPageSettings.Landscape = true;

    PrintDialog pDialog = new PrintDialog();
    pDialog.Document = pd;
    pDialog.PrinterSettings.DefaultPageSettings.Landscape = true;
    pDialog.PrinterSettings.PrintToFile = false;
    pDialog.Document.DefaultPageSettings.Landscape = true;

    PrintPreviewDialog printPreview = new PrintPreviewDialog();

    printPreview.Document = pd;
    printPreview.ShowDialog();
}

Then a Print_Me function is called when the PrintPreview dialog requests printing:

private void Print_Me(object sender, PrintPageEventArgs e)
{
    using (Graphics g = e.Graphics)
    {    
        DrawToDC(g);
        e.HasMorePages = hasMorePages;
    }
}

Within DrawToDC I use the following to get the dimensions which, as I mentioned, works fine for real printing and displaying to a dialog:

dc.VisibleClipBounds.Width
dc.VisibleClipBounds.Height
3

There are 3 best solutions below

0
On

I had exactly the same issue and eventually found this. Add an OnQueryPageSettings delegate handler.

void OnQueryPageSettings(object obj,QueryPageSettingsEventArgs e)
{
    if (e.PageSettings.PrinterSettings.LandscapeAngle != 0)
        e.PageSettings.Landscape = true;            
}

and to your PrintDocument

prnDoc.QueryPageSettings += new QueryPageSettingsEventHandler(OnQueryPageSettings);

That fixed it for me.

0
On

I couldn't find out where to hook up David Bolton's solution, but found another way.

http://wieser-software.blogspot.co.uk/2012/07/landscape-printing-and-preview-in-wpf.html

Fundamentally, you need to set the PageSize on each DocumentPage returned by your DocumentPaginator's GetPage method.

0
On

I had the exact same problem. However everything worked fine if I drew the page contents with the correct width and height (i.e. swap them).

int width = dc.VisibleClipBounds.Width;
int height = dc.VisibleClipBounds.Height;
if(width < height)
{
    int temp = width;
    width = height;
    height = temp;
}

Then draw the page content based off width and height.

Not the nicest solution but ensures we're always drawing to a landscape page.