如何为打印机设置自定义纸张来源?代码类型转换报错求助
解决C#设置PrintDocument自定义纸张来源的类型转换错误
问题场景
打印时想要选择自定义纸张来源,编写了如下C#代码:
PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = domainUpDown1.SelectedItem.ToString(); int i = 1; foreach (int x in consent) { pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); pd.PrinterSettings.Copies = Convert.ToInt16(x); pd.DefaultPageSettings.PaperSource = PaperSourceKind.Upper; // MessageBox.Show(pd.DefaultPageSettings.PaperSource.ToString()); if (x != 0) { pd.Print(); } i++; }
其中pd.DefaultPageSettings.PaperSource = PaperSourceKind.Upper;这行代码引发错误:
Error 1 Cannot implicitly convert type
'System.Drawing.Printing.PaperSourceKind' to
'System.Drawing.Printing.PaperSource'
解决方案
错误核心是PaperSource类型属性无法直接接收PaperSourceKind枚举值,需要从当前打印机支持的纸张来源集合中,找到对应枚举的实例对象进行赋值:
修改后的代码示例
PrintDocument pd = new PrintDocument(); pd.PrinterSettings.PrinterName = domainUpDown1.SelectedItem.ToString(); // 提前从打印机支持的纸张来源中匹配Upper纸盒实例 PaperSource upperPaperSource = null; foreach (PaperSource source in pd.PrinterSettings.PaperSources) { if (source.Kind == PaperSourceKind.Upper) { upperPaperSource = source; break; } } // 移除循环内重复绑定事件的代码,避免多次触发打印逻辑 pd.PrintPage += new PrintPageEventHandler(this.pd_PrintPage); int i = 1; foreach (int x in consent) { pd.PrinterSettings.Copies = Convert.ToInt16(x); if (upperPaperSource != null) { pd.DefaultPageSettings.PaperSource = upperPaperSource; } else { // 找不到指定纸盒时,回退到默认纸张来源 pd.DefaultPageSettings.PaperSource = pd.PrinterSettings.DefaultPageSettings.PaperSource; } if (x != 0) { pd.Print(); } i++; }
额外注意点
原代码在循环内重复绑定PrintPage事件,会导致每次打印时触发多次打印逻辑,建议将事件绑定移到循环外部执行。
内容的提问来源于stack exchange,提问作者MahdiKarami
相关产品推荐
相关产品推荐

