在打印Excel文档时设置打印机托盘

7

我看到很多关于在C#中为Word文档设置打印机托盘的帖子。 我需要一个适用于Excel的解决方案。

如果可能的话,最好是适用于任何文档的更好的解决方法。一种可以传递文件路径和托盘的方法。

编辑 到目前为止,我尝试了以下方法,但打印机设置没有发生可见变化。

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = @"\\localhost\HP-4515n";
var dps = ps.DefaultPageSettings;
dps.PaperSource.RawKind = 260;

或者

PrinterSettings ps = new PrinterSettings();
ps.PrinterName = @"\\localhost\HP-4515n";
PaperSource psrc = new PaperSource();
psrc.RawKind = 260;
psrc.SourceName = "unknown";
dps.PaperSource = psrc;

EDIT 2

由于托盘在纸张来源设定中未显示,我硬编码了RawKind。

目前,当我打印例如Excel文档时,我会显示打印机对话框,获取所选打印机的名称,并将其传递给Interop Excel活动打印机属性。但现在我需要大量打印文件,并且需要以编程方式设置所选打印机及其属性,特别是托盘。


相关链接:http://stackoverflow.com/questions/770230/excel-vba-print-to-specific-printer-tray - Mitch
3个回答

1
您可以使用以下代码获取可用的纸张来源:
PrintDocument printDoc1 = new PrintDocument();
List<PaperSource> psList = new List<PaperSource>();
PaperSource pkSource;
for (int i = 0; i < printDoc1.PrinterSettings.PaperSources.Count; i++)
{
    pkSource = printDoc1.PrinterSettings.PaperSources[i];
    psList.Add(pkSource);
}

现在将这些选项呈现给用户,并获取输入以确定使用哪个纸张来源,比如第一个,你可以这样做:
PrintDocument doc = new PrintDocument();
doc.DefaultPageSettings.PaperSource = psList[0];
doc.Print();

1

@sysboard,我从MSDN页面上的PrinterSettings类中看到DefaultPageSettings属性没有set方法,只有get方法。我不确定是否可以从外部类访问...您可以研究一下PageSettings类,因为它似乎有一个重载的构造函数,允许您传递指定的打印机,并且它在PaperSource上有一个set方法。


0
为什么你在硬编码 psrc.RawKind = 260; 来设置纸张来源的 RawKind?其实可以使用 PaperSourceKind 枚举类型来设置。请尝试以下代码:
PrintDocument doc = new PrintDocument();
PaperSource pSource = new PaperSource();
pSource.RawKind = (int)PaperSourceKind.Middle;
doc.DefaultPageSettings.PaperSource = pSource;

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接