Use Microsoft Print to PDF to create a PDF file in C#

[PDF]

This example shows one way that you can make a C# program create a PDF file. It’s super easy. (I haven’t posted any easy examples for a while, so this one makes a refreshing change.)

Selecting the Printer

In a Windows Forms program, you use a PrintDocument object to generate printouts. To print to a specific printer, simply set that object’s PrinterSettings.PrinterName property to the name of the printer that you want to use. To create a PDF file, set the printer name to “Microsoft Print to PDF.”

Note that you can do this from other programs, too. For example, Excel, Word, WordPad, and others can print to Microsoft Print to PDF. Some of those applications also have their own ways to create PDFs. For example, Excel’s Save As command can save to a PDF.

The only catch is that this printer must be installed and activated on your system. Try printing from WordPad and see if this printer is available. If it is not, see this Microsoft article.

How to Add or Reinstall the Microsoft PDF Printer

Printing

Microsoft Print to PDF is a native Windows 10 print driver. When the PrintDocument object sends its output to this driver, the driver prompts the user for the name of the PDF file that it should create and then places its output in the file in PDF format.

When you click this program’s Print to PDF button, the following code executes.

private int NextPage = 0;

private void btnPrintToPdf_Click(object sender, EventArgs e)
{
    NextPage = 0;
    pdocShapes.PrinterSettings.PrinterName = "Microsoft Print to PDF";
    pdocShapes.Print();
}

The button’s Click event handler first sets the NextPage variable to zero to make printing start with the first page. The program uses this variable to keep track of the number of the next page that it should print. You’ll see how that works shortly.

(Tip: If your program prints more than one page, then you’ll need some sort of next page variable like this one. You should reset it to zero whenever you start a new printout. If you don’t, then the second time you try to print, the variable will point after the last page so you won’t see anything.)

Next the code sets the PrinterName property for the PrintDocument object named pdocShapes. It finishes by calling the PrintDocument object’s Print method.

The following code shows the PrintDocument object’s PrintPage method, which actually generates the printed results.

private void pdocShapes_PrintPage(object sender,
    System.Drawing.Printing.PrintPageEventArgs e)
{
    e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
    switch (NextPage)
    {
        case 0:
            using (Pen pen = new Pen(Color.Red,10))
            {
                e.Graphics.DrawEllipse(pen, e.MarginBounds);
            }
            break;

        case 1:
            using (Pen pen = new Pen(Color.Green, 10))
            {
                e.Graphics.DrawRectangle(pen, e.MarginBounds);
            }
            break;

        case 2:
            using (Pen pen = new Pen(Color.Blue, 10))
            {
                Point[] points =
                {
                    new Point(
                        e.MarginBounds.Left,
                        e.MarginBounds.Top + e.MarginBounds.Height / 2),
                    new Point(
                        e.MarginBounds.Left + e.MarginBounds.Width / 2,
                        e.MarginBounds.Top),
                    new Point(
                        e.MarginBounds.Right,
                        e.MarginBounds.Top + e.MarginBounds.Height / 2),
                    new Point(
                        e.MarginBounds.Left + e.MarginBounds.Width / 2,
                        e.MarginBounds.Bottom),
                };
                e.Graphics.DrawPolygon(pen, points);
            }
            break;
    }
    NextPage++;
    e.HasMorePages = (NextPage <= 2);
}

This code sets the Graphics object’s SmoothingMode and then uses a switch statement to figure out which page it is printing. It then draws either an ellipse, rectangle, or diamond on the page. Notice how the code uses e.MarginBounds to make the shape fill the printed page’s area inside its margins.

After it has drawn the current page, the code increments the NextPage variable. If NextPage is now greater than 2, then there are not more pages to print, so the code sets e.HasMorePages to false to tell the PrintDocument object that is is done.

The PrintDocument object raises its PrintPage event until e.HasMorePages is false and then it stops.

That’s all there is to it. Download the example to see additional details.


Download Example   Follow me on Twitter   RSS feed   Donate




About RodStephens

Rod Stephens is a software consultant and author who has written more than 30 books and 250 magazine articles covering C#, Visual Basic, Visual Basic for Applications, Delphi, and Java.
This entry was posted in drawing, graphics, printing and tagged , , , , , , , , . Bookmark the permalink.

2 Responses to Use Microsoft Print to PDF to create a PDF file in C#

  1. thom lask says:

    What if I want to print a pdf from a pdf or another type of file? Can I use something other than System.Drawing.Printing.PrintPageEventArgs like System.Drawing.Printing.PrintDocument? I want to try and read in a non text file and then print to pdf.

    • RodStephens says:

      The PrintDocument object is just an object that manages the printing process. It raises the PrintPage event and the event handler needs to produce the output.

      You can make a file print to the MicrosoftPrint to PDF printer like this:

      ProcessStartInfo pi = new ProcessStartInfo(input_file);
      pi.UseShellExecute = true;
      pi.Arguments = "Microsoft Print to PDF";
      pi.Verb = "PrintTo";
      System.Diagnostics.Process.Start(pi);

      But I don’t know how to tell the printer the output file name so it prompts the user.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.