Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

How to Programmatically Convert a String to PDF using C#

4.90/5 (27 votes)
5 Jan 2019CPOL2 min read 44.7K  
Is there really no simple way to convert a C# string to PDF?

Introduction

The other day, I needed to save some text as a PDF in a C# app. I needed the PDF because it was a report so it should be closed for editing. Of course, PFD is in no manner closed for editing, but it is, let's say' fairly closed for the standard user, or at least fool proof so as to deny "mistakenly" editing it.

Background

So, I Googled a bit, trying hard to find just some code sample to copy paste into my project, without having to download a third-party library, and then checking it out, getting used to its pros and cons. But, my wish was not fulfilled.

If you want to use the third party solution, there are paid ones and free ones, many are good and mature products, among which are PFD Sharp, iTextSharp, PDF.NET, etc.

There's also a great CodeProject Article by Uzi Granot called PDF File Writer C# Class Library (Version 1.20.0), which won the CodeProject best overall, and best C# article in April 2013, and if you're looking into more than just creating a simple PDF file, go check it out.

But I said, hey, in new year's eve of 2019, no way such a trivial thing could not be accomplished without using any external help (of DLLs and other animals whose entry into my projects I try to minimize), in a couple of lines...

And came the idea (that worked and) that is why I'm writing this TIP. It turns out that in Windows 10, there's a default printer called Microsoft Print to PDF, so, here's how you create a PrintDocument and print it using that printer, then save it to a PDF file, all in the background.

VoilĂ !

Using the Code

This code is just a proof of concept and you can do a lot more, mainly due to the strength of the class PrintDocument that I used which allows quite a handful of design and graphical features.

So, here goes:

C#
// ----------------------------------------------------------------------------------------------
// If you run this on Windows 10 (having it's default printer "Microsoft Print to PDF" installed)
// This should print a PDF file named "CreatedByCSharp.PDF" in your "MyDocuments" folder
// containing the string "When nothing goes right, go left"
// ----------------------------------------------------------------------------------------------

// If not present, you will need to add a reference to System.Drawing in your project References
using System.Drawing;
using System.Drawing.Printing;


void PrintPDF()
{
    // Set the output dir and file name
    string directory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
    string file = "CreatedByCSharp.pdf";

    PrintDocument pDoc = new PrintDocument()
    {
        PrinterSettings = new PrinterSettings()
        {
             PrinterName = "Microsoft Print to PDF", 
             PrintToFile = true, 
             PrintFileName = System.IO.Path.Combine(directory, file),
        }
    };

    pDoc.PrintPage += new PrintPageEventHandler(Print_Page);
    pDoc.Print();
}

void Print_Page(object sender, PrintPageEventArgs e)
{    
    // Here you can play with the font style 
    // (and much much more, this is just an ultra-basic example)
    Font fnt = new Font("Courier New", 12);

    // Insert the desired text into the PDF file
    e.Graphics.DrawString
      ("When nothing goes right, go left", fnt, System.Drawing.Brushes.Black, 0, 0);
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)