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:
using System.Drawing;
using System.Drawing.Printing;
void PrintPDF()
{
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)
{
Font fnt = new Font("Courier New", 12);
e.Graphics.DrawString
("When nothing goes right, go left", fnt, System.Drawing.Brushes.Black, 0, 0);
}