Click here to Skip to main content
13,900,571 members
Click here to Skip to main content
Add your own
alternative version

Tagged as

Stats

14.8K views
34 bookmarked
Posted 1 Jan 2019
Licenced CPOL

How to Programmatically Convert a String to PDF using C#

, 5 Jan 2019
Rate this:
Please Sign up or sign in to vote.
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:

// ----------------------------------------------------------------------------------------------
// 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)

Share

About the Author

Joezer BH
Chief Technology Officer
United States United States
Senior dish washing consultant for over 25 years!

You may also be interested in...

Pro

Comments and Discussions

 
AnswerMessage Closed Pin
13-Feb-19 19:48
memberLincoln Gray13-Feb-19 19:48 
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
memberPeter R. Fletcher3-Jan-19 11:33 
AnswerRe: Does "Print to PDF" come with Windows 10 Pin
Audi Nugraha3-Jan-19 14:48
memberAudi Nugraha3-Jan-19 14:48 
GeneralRe: Does "Print to PDF" come with Windows 10 Pin
Peter R. Fletcher4-Jan-19 10:38
memberPeter R. Fletcher4-Jan-19 10:38 
BugPrintdocument should be PrintDocument Pin
Member 118991673-Jan-19 2:46
memberMember 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
memberGary 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
membergogbatch2-Jan-19 3:55 
GeneralMy vote of 5 Pin
amiSett2-Jan-19 1:59
memberamiSett2-Jan-19 1:59 
Questiontypo... Pin
Luuk v2-Jan-19 1:31
memberLuuk 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
memberbase2-codeproject2-Jan-19 1:31 
QuestionSadly there is no solution for C++ without Dot Net. Pin
Pankaj Singh Thapa1-Jan-19 23:34
memberPankaj Singh Thapa1-Jan-19 23:34 
AnswerRe: Sadly there is no solution for C++ without Dot Net. Pin
LightTempler2-Jan-19 7:08
memberLightTempler2-Jan-19 7:08 
QuestionSome would call this ... Pin
LightTempler1-Jan-19 4:57
memberLightTempler1-Jan-19 4:57 
AnswerRe: Some would call this ... Pin
Audi Nugraha1-Jan-19 6:35
memberAudi Nugraha1-Jan-19 6:35 
GeneralRe: Some would call this ... Pin
LightTempler2-Jan-19 6:37
memberLightTempler2-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.

Permalink | Advertise | Privacy | Cookies | Terms of Use | Mobile
Web03 | 2.8.190306.1 | Last Updated 6 Jan 2019
Article Copyright 2019 by Joezer BH
Everything else Copyright © CodeProject, 1999-2019
Layout: fixed | fluid