C#无法在预打印表格上设置自定义纸张尺寸

时间:2019-07-01 14:20:08

标签: c# .net printing

我已经用预打印的格式-System.Drawing.Printing.PrintDocument编写了一个C#打印测试项目。其目的是在自定义纸张尺寸上从文件中打印图像。在打印图像之前,请根据纸张尺寸缩小图像。

   public PrintDocument printDoc = new PrintDocument();
    .....
    private void PrintButton_Click(object sender, EventArgs e)
    {
        string FileName = "D:\\temp\\testprint.png";

        try
        {
            if (string.IsNullOrWhiteSpace(FileName)) return; // Prevents execution of below statements if filename is not selected.

            PrintDocument pd = new PrintDocument();
            PaperSize paperSize = new PaperSize("TEST PAPER SIZE", 50, 50);
            paperSize.RawKind = (int)PaperKind.Custom;

            //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 = paperSize;
            pd.DefaultPageSettings.PaperSize = paperSize;

            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);
                args.Graphics.PageUnit = System.Drawing.GraphicsUnit.Millimeter;

                //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)
        {
            MessageBox.Show(ex.Message);
        }
    }

图像缩放效果很好,但是纸张尺寸没有改变,始终保持为A4。我在Google上搜索了很多,并应用了一些选项,但仍然无法设置自定义纸张属性。谁能帮助我找出问题所在?或至少指出我在哪里继续学习?

谢谢!

0 个答案:

没有答案