在打印期间使图像高度和宽度适合页面

时间:2018-03-28 00:25:08

标签: c# wpf winforms

我正在尝试打开打印预览对话框并打印所有图像。我的问题是当我打印图像时,宽度似乎与打印纸对齐并且图像被切割。如何在不切割纸张的情况下在纸张上打印图像。请帮忙。

请参阅Pdoc_PrintPage事件方法。我正在使用e.Graphics.DrawImageUnscaled它是我正在使用的正确重载。我调试我的代码放入值。

private void PrintAllCharts(Dictionary<LightningChartUserControl, string> charts)
{
    try
    {
        if (PrinterSettings.InstalledPrinters.Count == 0)
        {
            Xceed.Wpf.Toolkit.MessageBox.Show(System.Windows.Application.Current.TryFindResource("SetUpPrinter").ToString(),
                    "Default printer not found", MessageBoxButton.OK, MessageBoxImage.Error);
            return;
        }
        string FilePathWithoutFileName = string.Empty;
        DirectoryInfo info = Directory.CreateDirectory(@"C:\TempCharts");
        for (int i = 0; i < charts.Count; i++)
        {
            KeyValuePair<LightningChartUserControl, string> kp = charts.ElementAt(i);
            FilePathWithoutFileName = info.FullName;
            string FullPath = string.Format("{0}/Chart{1}.png", FilePathWithoutFileName, i.ToString());
            kp.Key.Chart.SaveToFile(FullPath);
        }
        var files = Directory.GetFiles(FilePathWithoutFileName);

        using(var pdoc=new PrintDocument())
        {
            using(var pdi=new System.Windows.Forms.PrintDialog { Document = pdoc, UseEXDialog = true })
            {
                if (pdi.ShowDialog() == System.Windows.Forms.DialogResult.OK)
                {
                    pdoc.PrinterSettings = pdi.PrinterSettings;
                    pdoc.PrintPage += Pdoc_PrintPage;

                    foreach(var file in files)
                    {
                        pdoc.DocumentName = file;
                        pdoc.Print();
                    }
                }
            }
        }
        PrinterSettings settings = new PrinterSettings();
        Xceed.Wpf.Toolkit.MessageBox.Show(string.Format(System.Windows.Application.Current.TryFindResource("PrintSuccessful").ToString(),settings.PrinterName),
                "Print Successful", MessageBoxButton.OK);

        foreach(FileInfo file in info.GetFiles())
        {
            file.Delete();
        }
        foreach (DirectoryInfo dir in info.GetDirectories())
        {
            dir.Delete(true);
        }
    }
    catch (Exception ex)
    {
        SystemDebugLogLogger.LogError(ex);
    }
}

private void Pdoc_PrintPage(object sender, PrintPageEventArgs e)
{
    string file = ((PrintDocument)sender).DocumentName;
    System.Drawing.Image img = System.Drawing.Image.FromFile(file);
    //e.Graphics.DrawImage(img, e.MarginBounds);
    //e.Graphics.DrawImageUnscaled(img, e.MarginBounds);
    var hei = img.Height; //509
    var wid = img.Width; //1671
    int x1 = e.MarginBounds.Left;//100
    int y1 = e.MarginBounds.Top;//100
    int w = e.MarginBounds.Width;//650
    int h = e.MarginBounds.Height;//900
    e.Graphics.DrawImageUnscaled(img, x1, y1, w, h);
}

0 个答案:

没有答案