从PrintPreview创建的图形是纵向的,而不是横向的

本文关键字:横向 PrintPreview 图形 创建 | 更新日期: 2023-09-27 18:12:29

我正在用c#打印自定义页面。当实际打印文档时,它可以正常工作,将其显示到对话框(通过相同的代码)也是如此。当代码用于PrintPreview时,对话框以横向模式显示页面,但创建的Graphics具有肖像文档的尺寸,因此,预览不能正确显示。以下是我使用的代码的精简版本

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();
}

PrintPreview对话框请求打印时,调用Print_Me函数:

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

DrawToDC中,我使用以下命令来获取尺寸,正如我提到的,对于真正的打印和显示到对话框中工作得很好:

dc.VisibleClipBounds.Width
dc.VisibleClipBounds.Height

从PrintPreview创建的图形是纵向的,而不是横向的

我有完全相同的问题,最终发现了这个。添加onquerypagessettings委托处理程序。

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

和PrintDocument

prnDoc。QueryPageSettings += new QueryPageSettingsEventHandler(OnQueryPageSettings);

我遇到了完全相同的问题。然而,如果我用正确的宽度和高度绘制页面内容(即交换它们),一切都工作得很好。

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

然后根据宽度和高度绘制页面内容。

不是最好的解决方案,但确保我们总是绘制到横向页面

我不知道在哪里连接David Bolton的解决方案,但找到了另一种方法。

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

基本上,您需要设置每个DocumentPaginator的GetPage方法返回的DocumentPage的PageSize。