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
I had exactly the same issue and eventually found this. Add an OnQueryPageSettings delegate handler.
and to your PrintDocument
prnDoc.QueryPageSettings += new QueryPageSettingsEventHandler(OnQueryPageSettings);
That fixed it for me.