Genere, muestre e imprima documentos simples en .NET

I want to do very common task in C# but I cannot figure how: My application will generate document with a lot of text and some pictures, let user preview the result and then let him print it. What is the easiest way to do it? I take the text that I put to the document from database.

observaciones:

preguntado el 08 de enero de 11 a las 17:01

It seems to me that I schould use DocumentViewer control (WPF) or PrintPreviewControl (windows forms) or ReportViewer (Windows forms). But I have no idea on how to create documents for them. -

Just Googled it and found this example. nbdtech.com/Blog/archive/2009/04/20/… but it doesn't look like it has preview. I guess you should needs PrintPreviewDialog or PrintPreviewControl to do preview. See this MSDN article msdn.microsoft.com/en-us/magazine/cc188767.aspx. -

3 Respuestas

Maybe this example will help you. This is actually based on WindowsForms and comes partially from MSDN. Use the below code like:

       using (Printer p = new Printer(this.richTextBox.Text, 1)) { }

Here it takes text from the richTextBox, but you can put any string there.

Create a new Form in your application and add the following code:

using System;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Drawing.Printing;

namespace PrinterExample
{
    public partial class Printer : Form
    {
        private string textToDisplay;
        private Font printFont;
        private StreamReader streamToPrint;
        private int mode;
       //mode 1 - Preview, 2 - Print
        public Printer(string textToDisplay,int mode)
        {
            this.textToDisplay = textToDisplay;
            this.mode = mode;
            InitializeComponent();
            PreviewPage();

        }

        internal void PreviewPage()
        {
            try
            {
                streamToPrint = new StreamReader(new MemoryStream(Encoding.ASCII.GetBytes(textToDisplay)));
                printFont = DefaultFont;
                PrintDocument pd = new PrintDocument();
                pd.PrintPage += new PrintPageEventHandler
                   (this.pd_PrintPage);

                var ppd = new PrintPreviewDialog();
                ppd.Document = pd;

                if (mode == 1) ppd.Show();
                if (mode == 2) pd.Print();
            }
            catch
            {
                MessageBox.Show("Exception occured", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        private void pd_PrintPage(object sender, PrintPageEventArgs ev)
        {
            float linesPerPage = 0;
            float yPos = 0;
            int count = 0;
            float leftMargin = ev.MarginBounds.Left;
            float rightMargin = ev.MarginBounds.Right;
            float topMargin = ev.MarginBounds.Top;
            string line = null;

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

            float charsPerLine = (rightMargin - leftMargin) / (printFont.GetHeight(ev.Graphics)*0.65f);

            // Print each line of the file.
            while (count < linesPerPage &&
               ((line = streamToPrint.ReadLine()) != null))
            {
                string newLine = null;
                int newLineCounter = 0;
                for (int i = 0; i < line.Length; i++)
                {
                    if (i % (int)charsPerLine == 0)
                    {
                        newLine = line.Substring((int)charsPerLine * newLineCounter, (int)charsPerLine > (line.Length - (int)charsPerLine * newLineCounter) ? (line.Length - (int)charsPerLine * newLineCounter) : (int)charsPerLine); 


                        yPos = topMargin + (count *
                           printFont.GetHeight(ev.Graphics));
                        ev.Graphics.DrawString(newLine, printFont, Brushes.Black,
                           leftMargin, yPos, new StringFormat());

                        count++;
                        newLineCounter++;
                    }

                }
                newLineCounter = 0;
            }

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

        private void Printer_FormClosing(object sender, FormClosingEventArgs e)
        {
            this.streamToPrint.Close();
        }

    }

Be aware that for proffesional printing most people use external tools like Crystal Reports. I am not sure if you can modify this example to print images.

Respondido el 08 de enero de 11 a las 20:01

I would second that you don't want to be using this for any kind of data driven reporting or documentation. It's so much simpler and better to do it through something else. - msarchet

I need also pictures and cannot thing about any way how to modify this to render them. So there is no simple way of creating Document with text and some pictures in C# ?! What about that Crystal Reports? Is there any tutorial or documentation ? - Rasto

To msarchet: then please tell me what is that something else. I cannot find ANY solution. - Rasto

@msarchet Totally agree, this is jus an 'ad hoc' solution. @drasto There are lof of powerful components for printing, however most of them are not free. I am not totally sure but it seems to me that Crystal Reports plugin for Visual Studio is free. - nan

@drasto, Crystal Reports, Dev Express's Reports, Component One Reports, Telerik's Reports. Most any .NET component provider is going to have some kind of reporting solution built into it. I use Dev Express at work and I really love their reporting solutions - msarchet

One option is to use built-in .rdlc reports for you task

http://msdn.microsoft.com/en-us/library/ms252067(v=VS.90).aspx

Respondido el 08 de enero de 11 a las 22:01

Drasto,

I created a rather complex custom printing tool that might be useful.

PrintPage PrintPageEventHandler está imprimiendo demasiadas copias

Feel free to steal as much of that code of mine as you want.

contestado el 23 de mayo de 17 a las 15:05

No es la respuesta que estás buscando? Examinar otras preguntas etiquetadas or haz tu propia pregunta.