I have recently learned about File.WriteAllText and File.AppendAllText methods in C#. As I understand it, File.WriteAllText creates txt files and writes text to them without any problem.
But I tried this code in a console app:
It generates a "MyTest.pdf" file, but any PDF reader/viewer cannot open this file, as if it is corrupted. Seems like System.IO can only generate txt files, and assigns them whatever the extension that we specify.
So my question is how can I generate valid pdf files directly from C# code? If I need any exterior library for that purpose could you suggest any free ones?
A text files is a text file, no matter what file extension you give it. I'm not really familiar with C#, but I think you need to use a PDF library, just like you'd need to do in Java. Searching for "crate pdf c# library" yields lots of results; maybe the list at https://csharp-source.net/open-source/pdf-libraries is helpful.
Stephan van Hulst wrote:As far as C# libraries go, I'm aware of iText and PDFsharp. I don't have experience with them so I can't give a recommendation.
I used to use iText with Java, and, to a lesser extend, with C#. It's a very good library, well documented, honestly a bit low level - you have to directly deal with Chunks, Phrases, Paragraph and so on.
I added it to my console app through NuGet Package Manager, it generates PDF files pretty easily, without much code.
I don't even need to use any System.IO methods. The library provides its own methods, that are named pretty straightforward, like this:
After running the console app, I get a legit PDF file inside Debug folder that can be opened in any viewer.
I RELEASE YOU! (for now .... ) Feel free to peruse this tiny ad:
SKIP - a book about connecting industrious people with elderly land owners