Print PDF file using Printdocument

Asked

Viewed 4,024 times

3

I am developing an application, Console Application in Visual Studio 2015, that its function is to print documents.

I can print TXT and DOC without problems using the class PrintDocument but I can’t print PDF files. Is there any way to print a PDF with the PrintDocument?

     public void Imprimir(string caminhoImpressora)
    {
        streamToPrint = new StreamReader(@"C:\Users\3013\Desktop\teste.txt");


        printFont = new Font("Arial", 10);
        var documento = new PrintDocument();
        documento.PrinterSettings.PrintFileName = LocalizarImpressora(caminhoImpressora).ToString();
        documento.PrintPage += new PrintPageEventHandler(PrintPage);
        documento.Print();

    }

This is the method that defines the printer path that will be used and creates the Streamreader object of the txt file. And the code below is the event that reads the lines of the file and formats the text:

   private void PrintPage(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;
    }

However, when trying to use the same methods to print a pdf, I can even print it, but they are unreadable code, as if it could not read the content of the pdf itself.

  • 1

    What happens when you try to print a PDF? By the way, enter the code you are using. It doesn’t seem to be a problem to print PDF files with the PrintDocument

  • So I use a method that I found on the internet, where it mounts a Streamreader of the file, and kind of it goes reading line by line of the file, format (changes font, position on the screen, etc.) and then print. I’ll put the code down.

  • I put the code in the post.

1 answer

3


It will not be possible to print Pdfs using this routine. In it you are reading, line by line, a text file and "drawing" in hand, using the DrawString() the content of the line in a graphical context provided by PrintDocument. A PDF document is not a collection of lines in text, but rather a complex document, binary (nontextual), and packed with control constructs. It is practically a program in itself that defines the diagram of what will be extracted on the screen.

Therefore, even if your PDF is very simple, still, if it is not completely standardized, it will not be simple to extract the text from within it.

The ideal is to use some PDF display already installed to open the document and the user then prints it, or views it on the screen as he pleases. It is also possible to request the direct printing of the document, which may be more interesting in your case. The code below performs this in a very simple way:

private static void ImprimeDocumento(string caminho) {
    Process process = new Process {
        StartInfo = new ProcessStartInfo {
            CreateNoWindow = true,
            Verb = "print",
            FileName = caminho,
        },
    };
    process.Start();
}

However, in newer versions of Windows, such as 8 or 10, this method no longer works, so we would have to change the verb to "open":

private static void AbreVisualizadorPadrao(string caminho) {
    Process process = new Process {
        StartInfo = new ProcessStartInfo {
            Verb = "open",
            FileName = caminho,
        },
    };
    process.Start();
}

This will open the standard PDF windows reader and allow it to be printed there.

If you want generate the PDF manually and then print (using the above method), you will need a PDF generation library. I strongly suggest the open source library iTextSharp

If you really need to display the PDF in your application and print it directly, the way is to appeal to some ready-made library (most of them are not cheap):

  • 1

    This does not work on newer versions of Windows.

  • @jbueno if you switch to "open" the verb it will open the embedded PDF reader. In newer versions of Windows, like the 10, opens the Internet Explorer itself, and from there can be printed. I will modify the code with this information.

  • 1

    Perfect, that’s exactly what I needed. Thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.