Skip to main content
 首页 » 编程设计

c#之无法让打印机在 C# Windows 窗体项目中打印自定义尺寸的纸张

2024年02月23日15zhoujg

我最近一直在尝试在 C# 应用程序中打印表单。拍摄表单图片很容易,但我被困在打印部分。我已经阅读了很多文章和很多解决方案来打印自定义尺寸的纸张(我的意思是我的表格要打印在我为打印机指定的纸张上),但遗憾的是没有一个奏效。

到目前为止,这是我的项目中的内容:

//my method for taking a picture form the form , and then printing it . 
void PrintImage(object o, PrintPageEventArgs e) 
{ 
    int x = SystemInformation.WorkingArea.X; 
    int y = SystemInformation.WorkingArea.Y; 
    int width = this.Width; 
    int height = this.Height; 
 
    Rectangle bounds = new Rectangle(x, y, width, height); 
    Bitmap img = new Bitmap(width, height); 
 
   // e.PageSettings.PaperSize = new PaperSize("62mm", 244, (int)Size.Width) { RawKind = 259 }; 
 
    this.DrawToBitmap(img, bounds); 
    Point p = new Point(0, 0); 
    e.Graphics.DrawImage(img, p); 
} 
 
//getting the list of installed printers .   
private void comboBox1_Click(object sender, EventArgs e) 
{ 
    comboBox1.Items.Clear(); 
    foreach (string printer in PrinterSettings.InstalledPrinters) 
    { 
        comboBox1.Items.Add(printer); 
    } 
} 
 
 
 
 
   //Print Button Click event declaration  
    private void btnPrint_Click(object sender, EventArgs e) 
    { 
        PrintDocument pd = new PrintDocument(); 
        if (comboBox1.SelectedIndex !=-1) 
        { 
            pd.PrinterSettings.PrinterName = comboBox1.SelectedItem.ToString(); 
        } 
        pd.DefaultPageSettings.PaperSize = new PaperSize("CardSize", 50, 50); 
        pd.PrintPage += new PrintPageEventHandler(PrintImage); 
        pd.Print(); 
 
    } 

请您参考如下方法:

好的,我发现了: 要制作自定义纸张尺寸,只需简单地执行以下操作:

          PrintDocument pd = new PrintDocument(); 
          PaperSize paperSize = new PaperSize("MyCustomSize", 200, 200 ); //numbers are optional 
 
           paperSize.RawKind = (int)PaperKind.Custom; 
 
           pd.DefaultPageSettings.PaperSize = paperSize;