почему эти текстовые данные не распечатывались через принтер? - PullRequest
1 голос
/ 29 октября 2011

когда я пытаюсь сделать printdocument1.print (); система показала маленькую всплывающую модель, когда имя файла и система молчали, не выдавая ни одной ошибки enter image description here

вот мой код c # позади кода:

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Drawing.Printing;
using System.IO;
using System.Management;
using System.Diagnostics;

 namespace csvform
{
public partial class Form3 : Form
{

      private PrintDocument printDocument1 = new PrintDocument();
    private string stringToPrint;
    public Form3()
    {
        InitializeComponent();


        printDocument1.PrintPage +=
           new PrintPageEventHandler(printDocument1_PrintPage);

    }


     private void ReadFile()
   {
       string docName = "testPage.txt";
       string docPath = @"c:\";
       printDocument1.DocumentName  = docName;
       using (FileStream stream = new FileStream(docPath +
       docName, FileMode.Open))
       using (StreamReader reader = new StreamReader(stream))
       {
           stringToPrint = reader.ReadToEnd();
       }
   }

   private void printDocument1_PrintPage(object sender,
    PrintPageEventArgs e)
   {
       int charactersOnPage = 0;
       int linesPerPage = 0;
       Font nf = new Font(new FontFamily("Arial"), 10,
       System.Drawing.FontStyle.Bold);
       // Sets the value of charactersOnPage to the number of characters
       // of stringToPrint that will fit within the bounds of the page.
       e.Graphics.MeasureString(stringToPrint,nf,
           e.MarginBounds.Size, StringFormat.GenericTypographic,
           out charactersOnPage, out linesPerPage);

       // Draws the string within the bounds of the page
       e.Graphics.DrawString(stringToPrint,nf, Brushes.Black,
           e.MarginBounds, StringFormat.GenericTypographic);

       // Remove the portion of the string that has been printed.
       stringToPrint = stringToPrint.Substring(charactersOnPage);

       // Check to see if more pages are to be printed.
       e.HasMorePages = (stringToPrint.Length > 0);
   }

    private void button1_Click(object sender, EventArgs e)
    {


        ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT *           FROM Win32_Printer");
        string printerName = "";
        foreach (ManagementObject printer in searcher.Get())
        {
            printerName = printer["Name"].ToString().ToLower();
            if (printerName.Equals(@"\\chenraqdc2.raqmiyat.local\hp color laserjet cp1510"))
            {                                            
                   // printDocument1.Print();
                    try
                    {
                        // Assumes the default printer.
                        ReadFile();
                        printDocument1.Print();
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show("An error occurred while printing", ex.ToString());
                    }                      

            }
        }       
    }
 }
}

1 Ответ

1 голос
/ 18 января 2012

Для исторических целей :

// namespace declaration
using System.Management;

// code sample for setting default printer

ManagementObjectCollection objManagementColl;
// class used to invoke the query for specified management collection
ManagementObjectSearcher objManagementSearch = new ManagementObjectSearcher("SELECT * FROM Win32_Printer");

// invokes the specified query and returns the resulting collection
objManagementColl = objManagementSearch.Get();

foreach(ManagementObject objManage in objManagementColl)
    {
       if (objManage["Name"].ToString() == "RequiredPrinterName")  // compares the name of printers
          {
             objManage.InvokeMethod("SetDefaultPrinter", null); // invoke [SetDefaultPrinter] method 
             break;
           }
      }
...