1
Answer

C# Printing Documents Issue

Paul

Paul

17y
2.3k
1

So the goal is to be able to print a given document type (word, pdf, excel, etc.) with same formatting as the document would appear in it's respective application.  The problem is that I get garbage text when sent to the printer... I have tried various (a lot we'll leave it at) usages of PrintDocument structures so below is my current structure with the two main methods.

      private void PrintTest_1(string fullFilePath)
      {
         _streamToPrint = new StreamReader(fullFilePath);
         _printFont = new Font("Courier New", 10);
         PrintDocument pd = new PrintDocument();

         pd.PrintPage += OnPrintPage;

         try
         {
            try
            {
               pd.Print();
            }
            finally
            {
               _streamToPrint.Close();
               _streamToPrint.Dispose();
            }
         }
         catch (Exception ex)
         {
            throw new ApplicationException(ex.ToString());
         }
      }

      private void OnPrintPage(object sender, PrintPageEventArgs ev)
      {
         float linesPerPage = 0;
         float yPos = 0;
         int count = 0;
         float leftMargin = ev.MarginBounds.Left;
         float topMargin = ev.MarginBounds.Top;
         string line = null;

         // Calculate the number of lines per page.
         linesPerPage = ev.MarginBounds.Height / _printFont.GetHeight(ev.Graphics);

         // Print each line of the file.
         while (count < linesPerPage && ((line = _streamToPrint.ReadLine()) != null))
         {
            yPos = topMargin + (count * _printFont.GetHeight(ev.Graphics));
            ev.Graphics.DrawString(line, _printFont, Brushes.Black, leftMargin, yPos, new StringFormat());
            count++;
         }

         // If more lines exist, print another page.
         if (line != null)
            ev.HasMorePages = true;
         else
            ev.HasMorePages = false;
      }

Assistance and references would be greatly appreciated!

Paul R.

 

Answers (1)
Next Recommended Forum