0

I am trying to print pdf files using C# code. When I run the code, I get print dialog that says "printing" but no usable pdf or xps output. I am doing this from a console application not gui. Here is my current code:

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;

public class PrintFile {

    public static void printFilePath(String filePath, String printer) {
        try {
            var streamToPrint = new StreamReader(filePath);
            try {
                PrintDocument pd = new PrintDocument();
                pd.PrinterSettings.PrinterName = printer;
                // set landscape to false
                pd.DefaultPageSettings.Landscape = false;
                // set margins to zero
                Margins margins = new Margins(0,0,0,0);
                pd.DefaultPageSettings.Margins = margins;
                // print
                pd.Print();
            } catch (Exception ex) {
            Console.WriteLine(ex);
            }
            finally {
                Console.WriteLine("closing");
                streamToPrint.Close();
            }
        } catch (Exception ex) {
            Console.WriteLine(ex);
        }
    }

    public static void Main(string[] args) {
        String filePath = "C:\\Projects\\C\\girl.pdf";
        String printer = "Microsoft Print to PDF";
        printFilePath(filePath, printer);
    }

}

Any help is appreciated. I would also like to set number of copies, paper size (A4,e.t.c) and black and white/color also. Thanks.

UPDATE:

Based on comments below, I updated my code. Still cannot get it to print the exact document but at least it seems to print something. Would really appreciate any further constructive feedback

using System;
using System.Drawing;
using System.Drawing.Printing;
using System.IO;

public class PrintFile {

    private static Font printFont;
    private static StreamReader streamToPrint;

    // The PrintPage event is raised for each page to be printed.
    private static void pd_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;
    }

    public static void printFilePath(String filePath, String printer) {
        try {
            streamToPrint = new StreamReader(filePath);
            try {
                printFont = new Font("Arial", 10);
                PrintDocument pd = new PrintDocument();
                pd.PrinterSettings.PrinterName = printer;
                pd.PrintPage += new PrintPageEventHandler(pd_PrintPage);
                // set landscape to false
                pd.DefaultPageSettings.Landscape = false;
                // set margins to zero
                Margins margins = new Margins(0,0,0,0);
                pd.DefaultPageSettings.Margins = margins;
                // print
                pd.Print();
            } catch (Exception ex) {
            Console.WriteLine(ex);
            }
            finally {
                Console.WriteLine("closing");
                streamToPrint.Close();
            }
        } catch (Exception ex) {
            Console.WriteLine(ex);
        }
    }

    public static void Main(string[] args) {
        String filePath = "C:\\Projects\\C\\nnkl.pdf";
        String printer = "Microsoft Print to PDF";
        printFilePath(filePath, printer);
    }

}
daibatzu
  • 507
  • 4
  • 16
  • 2
    Um, shouldn't there be a PrintPage event where you put the printing code – TaW Jul 29 '19 at 20:22
  • 2
    You aren't doing anything with `streamToPrint` –  Jul 29 '19 at 20:24
  • 2
    Please get a book or [follow a tutorial](https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.printdocument), Windows printing is simply too complicated to learn through trial and error. – Dour High Arch Jul 29 '19 at 20:25
  • Possible duplicate of https://stackoverflow.com/questions/20692697/how-to-print-a-document-using-c-sharp-code –  Jul 29 '19 at 20:28
  • Hint: Make the stream public (or internal) so that the PrintPage event can read from it and do DrawString from its content..! - Also note, that while reding via a stream is often recommended for efficiency reasons it is not the best choice if one wnat to know how many line or pages are there to print..! – TaW Jul 29 '19 at 20:31
  • You are `trying to print pdf` but you were select the printer as `Save As PDF` which means you are not printing but saving like pdf file. So, you should set correct printer name for `pd.PrinterSettings.PrinterName` variable OR remove that variable and change your computer's default printer option then try again. **note:** PrintDocument always use default printer settings if you not change it. – Mustafa Salih ASLIM Jul 29 '19 at 20:34
  • Example came from here: https://learn.microsoft.com/en-us/dotnet/api/system.drawing.printing.pagesettings.landscape?view=netframework-4.8 – daibatzu Jul 29 '19 at 20:36
  • 2
    Well, he does expect pdf output, so that is not the issue. But he seems to have no printing code at all. The Print command only triggers a PrintPage event if there is one..! – TaW Jul 29 '19 at 20:36
  • 1
    _Example_ : Did you understand all three prerequisites, namely the 2nd one : _a method named pd_PrintPage, which handles the PrintPage event, has been defined._ ?? – TaW Jul 29 '19 at 20:38
  • 2
    @daibatzu The example code doesn't work because it isn't complete. Read that page above the example first. `a method named pd_PrintPage, which handles the PrintPage event, has been defined.` –  Jul 29 '19 at 20:44
  • Thanks. I looked at the document and it at least prints something, even though it seems to be gibberish. I updated my question with my current code – daibatzu Jul 30 '19 at 00:08
  • The printpage looks not so bad. - More hints: Do use console.Writeline(line) to test the lines you are printing! Are they ok? - Also: using a StringFormat is a good idea but you need to set it before using it. - Also You may want to print line by line or try to fill rectanlges. - What does the gibberish look like? – TaW Jul 30 '19 at 06:19
  • 1
    It's gibberish because you're trying to read a PDF file as text. –  Jul 30 '19 at 13:04
  • Interesting. Looks like this will only work with text files then – daibatzu Jul 30 '19 at 13:18

0 Answers0