Create PDF document programmatically

Aspose.PDF for .NET API lets you create and read PDF files using C# and VB.NET. The API can be used in a variety of .NET applications including WinForms, ASP.NET, and several others. In this article, we are going to show how to use Aspose.PDF for .NET API to easily generate and read PDF files in .NET applications.

How to Create PDF File using C#

To create a PDF file using C#, the following steps can be used.

  1. Create an object of Document class.
  2. Add a Page object to the Pages collection of the Document object.
  3. Add TextFragment to Paragraphs collection of the page.
  4. Save the resultant PDF document.

The next code snippet also works with Aspose.Drawing library.

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void HelloWorld()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_QuickStart();

    // Create PDF document
    using (var document = new Aspose.Pdf.Document())
    {
        // Add page
        var page = document.Pages.Add();
        // Add text to new page
        page.Paragraphs.Add(new Aspose.Pdf.Text.TextFragment("Hello World!"));
        // Save PDF document
        document.Save(dataDir + "HelloWorld_out.pdf");
    }
}

In this case, we create a PDF one-page document with A4 page size, portrait orientation. Our page will contain a “Hello, World” in the upper left part of the page.