You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C# Web服务中使用PrintDocument读取打印机默认设置失败

C# Web服务中PrintDocument读取打印机默认设置失败问题

问题详情

  • 在C# Web服务中使用PrintDocument组件时,无法正确读取打印机默认设置:即使已在控制面板中将打印机的PageSettings.Landscape设为true,调用PrinterSettings()时始终返回false。
  • 需要读取打印机的特殊功能(如制卡打印功能),而非手动设置常规打印参数。
  • 此前用Delphi编写的TPrinter控制台程序可正常读取打印机设置,但通过Web服务调用该EXE时同样失败。

示例代码

public string print_card(string strServer, string strPort, string strFileName, string strFileNameBack, int iDoubleFace)
{
    string iResult = "";
    try
    {
        PrinterSettings mySet = new PrinterSettings();  
        strFileToPrint_Front = "http://" + strServer + ":" + strPort + "/" + strFileName;
        strFileToPrint_Back = "http://" + strServer + ":" + strPort + "/" + strFileNameBack;
        iPrintIndex = 0;
        _iDoubleFace = iDoubleFace;
        PrintDocument pd = new PrintDocument();
        //pd.PrinterSettings = mySet;
        pd.DefaultPageSettings.PrinterSettings = mySet;
        //pd.DefaultPageSettings.PaperSize= new PaperSize("card",  1063, 650);
        //pd.DefaultPageSettings.Landscape= true;
        //pd.PrinterSettings.Duplex = System.Drawing.Printing.Duplex.Horizontal;
        pd.PrintPage += PrintPage;
        pd.Print();
        iResult = mySet.PrinterName;
    }catch (Exception ex)
    {
        iResult = ex.Message;
    }

    return iResult + strResult;
}

private void PrintPage(object o, PrintPageEventArgs e)
{
    WebClient wc = new WebClient();

    string strToPrint;
    if (iPrintIndex == 0)
        strToPrint = strFileToPrint_Front;
    else
        strToPrint = strFileToPrint_Back;

    byte[] bytes = wc.DownloadData(strToPrint);
    MemoryStream ms = new MemoryStream(bytes);
    System.Drawing.Image img = System.Drawing.Image.FromStream(ms);

    Rectangle m = e.PageBounds;
    if ((double) img.Width / (double) img.Height > (double) img.Width / (double) img.Height)
    {
       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); 
    }
    var size = img.Size;
    var width = size.Width;   

    //System.Drawing.Image img = System.Drawing.Image.FromFile("http://localhost:8022/medical_card/311/medimgs/cards/card_8_246.jpg");
    Point loc = new Point(0, 0);
    e.Graphics.PageUnit = GraphicsUnit.Pixel;
    e.Graphics.DrawImage(img, 0, 0, 1063, 635);
    strResult = strResult + "," + width.ToString(); 
    if (_iDoubleFace == 2)
    {
        if (iPrintIndex == 0)
            e.HasMorePages = true;
        else
            e.HasMorePages = false;

        iPrintIndex++;
    }
}

内容的提问来源于stack exchange,提问作者Joseph Asaad

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.04 04:21:02