首页 文章

使用PrintDocument打印图像 . 如何调整图像以适合纸张尺寸

提问于
浏览
27

在C#中,我尝试使用PrintDocument类使用以下代码打印图像 . 图像宽度为1200像素,高度为1800像素 . 我正在尝试使用小型zeebra打印机在4 * 6纸张中打印此图像 . 但该程序只打印4 * 6的大图像 . 这意味着它没有根据纸张尺寸调整图像!

PrintDocument pd = new PrintDocument();
     pd.PrintPage += (sender, args) =>
     {
           Image i = Image.FromFile("C://tesimage.PNG");
           Point p = new Point(100, 100);
           args.Graphics.DrawImage(i, 10, 10, i.Width, i.Height);
     };
     pd.Print();

当我使用“窗口打印”打印相同的图像时(右键单击并选择打印,它会自动缩放到纸张大小并正确打印 . 这意味着所有内容都来自4 * 6纸张 . )我如何在C#程序中执行相同的操作?

6 回答

  • 23

    传递给DrawImage方法的参数应该是您希望纸张上的图像大小而不是图像本身的大小,DrawImage命令将为您处理缩放 . 可能最简单的方法是使用DrawImage命令的以下重写 .

    args.Graphics.DrawImage(i, args.MarginBounds);
    

    注意:如果图像的比例与矩形不同,则会使图像歪斜 . 对图像大小和纸张大小的一些简单数学运算将允许您创建一个适合纸张边界的新矩形,而不会使图像偏斜 .

  • 4

    不要践踏BBoy已经不错的答案,但我已经完成了保持宽高比的代码 . 我接受了他的建议,所以他应该得到部分功劳!

    PrintDocument pd = new PrintDocument();
    pd.DefaultPageSettings.PrinterSettings.PrinterName = "Printer Name";
    pd.DefaultPageSettings.Landscape = true; //or false!
    pd.PrintPage += (sender, args) =>
    {
        Image i = Image.FromFile(@"C:\...\...\image.jpg");
        Rectangle m = args.MarginBounds;
    
        if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
        {
            m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
        }
        else
        {
            m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
        }
        args.Graphics.DrawImage(i, m);
    };
    pd.Print();
    
  • 4

    BBoy提供的解决方案运行良好 . 但在我的情况下,我不得不使用

    e.Graphics.DrawImage(memoryImage, e.PageBounds);
    

    这将仅打印表单 . 当我使用MarginBounds时,即使表格小于显示器屏幕,它也会打印整个屏幕 . PageBounds解决了这个问题 . 感谢BBoy!

  • 4

    You can use my code here

    //Print Button Event Handeler
    private void btnPrint_Click(object sender, EventArgs e)
    {
        PrintDocument pd = new PrintDocument();
        pd.PrintPage += PrintPage;
        //here to select the printer attached to user PC
        PrintDialog printDialog1 = new PrintDialog();
        printDialog1.Document = pd;
        DialogResult result = printDialog1.ShowDialog();
        if (result == DialogResult.OK)
        {
            pd.Print();//this will trigger the Print Event handeler PrintPage
        }
    }
    
    //The Print Event handeler
    private void PrintPage(object o, PrintPageEventArgs e)
    {
        try
        {
            if (File.Exists(this.ImagePath))
            {
                //Load the image from the file
                System.Drawing.Image img = System.Drawing.Image.FromFile(@"C:\myimage.jpg");
    
                //Adjust the size of the image to the page to print the full image without loosing any part of it
                Rectangle m = e.MarginBounds;
    
                if ((double)img.Width / (double)img.Height > (double)m.Width / (double)m.Height) // image is wider
                {
                    m.Height = (int)((double)img.Height / (double)img.Width * (double)m.Width);
                }
                else
                {
                    m.Width = (int)((double)img.Width / (double)img.Height * (double)m.Height);
                }
                e.Graphics.DrawImage(img, m);
            }
        }
        catch (Exception)
        {
    
        }
    }
    
  • 33

    回答:

    public void Print(string FileName)
    {
        StringBuilder logMessage = new StringBuilder();
        logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ START - {0} - {1} -------------------]", MethodBase.GetCurrentMethod(), DateTime.Now.ToShortDateString()));
        logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "Parameter: 1: [Name - {0}, Value - {1}", "None]", Convert.ToString("")));
    
        try
        {
            if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.
    
            PrintDocument pd = new PrintDocument();
    
            //Disable the printing document pop-up dialog shown during printing.
            PrintController printController = new StandardPrintController();
            pd.PrintController = printController;
    
            //For testing only: Hardcoded set paper size to particular paper.
            //pd.PrinterSettings.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
            //pd.DefaultPageSettings.PaperSize = new PaperSize("Custom 6x4", 720, 478);
    
            pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
            pd.PrinterSettings.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
    
            pd.PrintPage += (sndr, args) =>
            {
                System.Drawing.Image i = System.Drawing.Image.FromFile(FileName);
    
                //Adjust the size of the image to the page to print the full image without loosing any part of the image.
                System.Drawing.Rectangle m = args.MarginBounds;
    
                //Logic below maintains Aspect Ratio.
                if ((double)i.Width / (double)i.Height > (double)m.Width / (double)m.Height) // image is wider
                {
                    m.Height = (int)((double)i.Height / (double)i.Width * (double)m.Width);
                }
                else
                {
                    m.Width = (int)((double)i.Width / (double)i.Height * (double)m.Height);
                }
                //Calculating optimal orientation.
                pd.DefaultPageSettings.Landscape = m.Width > m.Height;
                //Putting image in center of page.
                m.Y = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Height - m.Height) / 2);
                m.X = (int)((((System.Drawing.Printing.PrintDocument)(sndr)).DefaultPageSettings.PaperSize.Width - m.Width) / 2);
                args.Graphics.DrawImage(i, m);
            };
            pd.Print();
        }
        catch (Exception ex)
        {
            log.ErrorFormat("Error : {0}\n By : {1}-{2}", ex.ToString(), this.GetType(), MethodBase.GetCurrentMethod().Name);
        }
        finally
        {
            logMessage.AppendLine(string.Format(CultureInfo.InvariantCulture, "-------------------[ END  - {0} - {1} -------------------]", MethodBase.GetCurrentMethod().Name, DateTime.Now.ToShortDateString()));
            log.Info(logMessage.ToString());
        }
    }
    
  • 6

    同意TonyM和BBoy - 这是原始4 * 6标签打印的正确答案 . (args.PageBounds) . 这适用于我打印Endicia API服务运输标签 .

    private void SubmitResponseToPrinter(ILabelRequestResponse response)
        {
            PrintDocument pd = new PrintDocument();
            pd.PrintPage += (sender, args) =>
            {
                Image i = Image.FromFile(response.Labels[0].FullPathFileName.Trim());
                args.Graphics.DrawImage(i, args.PageBounds);
            };
            pd.Print();
        }
    

相关问题