SelectPdf for .NET - Pdf Page Settings - C# / ASP.NET MVC Sample

This sample shows how to create a new PDF document using SelectPdf and how to specify the page size, margins and orientation.

The sample create a first page with no margins, size A4 and Portrait orientation and a second page with 20pt for all margins, Letter size and Landscape orientation.


Sample Code C#



using System.Web.Mvc;
using SelectPdf.Samples.Models;

namespace SelectPdf.Samples.Controllers
{
    public class PageSettingsController : Controller
    {
        // GET: PageSettings
        public ActionResult Index()
        {
            return View();
        }

        [HttpPost]
        public ActionResult SubmitAction(FormCollection collection)
        {

            // create a new pdf document
            PdfDocument doc = new PdfDocument();

            // create a new pdf font
            PdfFont font = doc.AddFont(PdfStandardFont.Helvetica);
            font.Size = 18;

            // add a new page to the document 
            // (with specific page size, margins and orientation)
            PdfPage page = doc.AddPage(PdfCustomPageSize.A4,
                new PdfMargins(0f), PdfPageOrientation.Portrait);

            // create a new text element and add it to the page
            PdfTextElement text = new PdfTextElement(0, 0, Helper.SomeText(), font);
            page.Add(text);

            // add a new page to the document
            // (with specific page size, margins and orientation)
            PdfPage page2 = doc.AddPage(PdfCustomPageSize.Letter,
                new PdfMargins(20f), PdfPageOrientation.Landscape);

            // create a new text element and add it to the page
            PdfTextElement text2 = new PdfTextElement(0, 0, Helper.SomeText(), font);
            page2.Add(text2);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");
            fileResult.FileDownloadName = "Document.pdf";
            return fileResult;
        }
    }
}