Click here to Skip to main content
15,881,033 members
Articles / Programming Languages / C#
Tip/Trick

How to Programmatically Convert a String to PDF using C#

Rate me:
Please Sign up or sign in to vote.
4.90/5 (27 votes)
5 Jan 2019CPOL2 min read 41.9K   37   18
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)


Written By
Chief Technology Officer
United States United States
Senior dish washing consultant for over 25 years!

Comments and Discussions

 
GeneralMy vote of 5 Pin
Ender Yemenicioglu7-Jan-19 20:45
professionalEnder Yemenicioglu7-Jan-19 20:45 
QuestionDoes "Print to PDF" come with Windows 10 Pin
Peter R. Fletcher3-Jan-19 11:33
Peter R. Fletcher3-Jan-19 11:33 
AnswerRe: Does "Print to PDF" come with Windows 10 Pin
Audi Nugraha3-Jan-19 14:48
Audi Nugraha3-Jan-19 14:48 
GeneralRe: Does "Print to PDF" come with Windows 10 Pin
Peter R. Fletcher4-Jan-19 10:38
Peter R. Fletcher4-Jan-19 10:38 
BugPrintdocument should be PrintDocument Pin
Member 118991673-Jan-19 2:46
Member 118991673-Jan-19 2:46 
GeneralRe: Printdocument should be PrintDocument Pin
Joezer BH5-Jan-19 22:29
professionalJoezer BH5-Jan-19 22:29 
SuggestionAlternatives? Pin
Gary Palmer2-Jan-19 5:01
Gary Palmer2-Jan-19 5:01 
QuestionNote that it is doing the PDF text as a graphic, not as a description of the text Pin
gogbatch2-Jan-19 3:55
gogbatch2-Jan-19 3:55 
GeneralMy vote of 5 Pin
amiSett2-Jan-19 1:59
amiSett2-Jan-19 1:59 
Wow - brilliant. Are you able to extend this to print images etc? Ideally pass html?
Questiontypo... Pin
Luuk V2-Jan-19 1:31
Luuk V2-Jan-19 1:31 
AnswerRe: typo... Pin
Joezer BH5-Jan-19 22:33
professionalJoezer BH5-Jan-19 22:33 
PraisePretty neat trick Pin
base2-codeproject2-Jan-19 1:31
base2-codeproject2-Jan-19 1:31 
QuestionSadly there is no solution for C++ without Dot Net. Pin
Pankaj Singh Thapa1-Jan-19 23:34
Pankaj Singh Thapa1-Jan-19 23:34 
AnswerRe: Sadly there is no solution for C++ without Dot Net. Pin
LightTempler2-Jan-19 7:08
LightTempler2-Jan-19 7:08 
GeneralRe: Sadly there is no solution for C++ without Dot Net. Pin
Pankaj Singh Thapa7-May-19 20:09
Pankaj Singh Thapa7-May-19 20:09 
QuestionSome would call this ... Pin
LightTempler1-Jan-19 4:57
LightTempler1-Jan-19 4:57 
AnswerRe: Some would call this ... Pin
Audi Nugraha1-Jan-19 6:35
Audi Nugraha1-Jan-19 6:35 
GeneralRe: Some would call this ... Pin
LightTempler2-Jan-19 6:37
LightTempler2-Jan-19 6:37 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.