SelectPdf for .NET 10 - Convert Word to Pdf - C# / .NET 10 Sample

This sample shows how to use the SelectPdf Word to pdf converter to convert a Word document (docx, doc, rtf and the other formats the converter reads) to pdf, setting a few properties. The conversion runs in-process; no engine is launched.

The sample converts the following Word document, or a document you upload:
Test Word document

Word document (optional, docx / doc / rtf):

Page Setup:

(Document keeps the page sizes of the Word document; Options reflows the text onto the page size, orientation and margins below.)

Pdf Page Size:


Pdf Page Orientation:


Margins:
pt

Add a header
Add page numbers in the footer

Outline (bookmarks):


Pdf Standard:


Accessibility (PDF/UA):


Document Title (required by PDF/UA):


Document Language:


Sample code · C#
using System;
using System.Collections.Generic;
using System.IO;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
using Microsoft.AspNetCore.Mvc.Rendering;
using SelectPdf.Universal;

namespace SelectPdf.Samples.Pages
{
    public class ConvertWordToPdfModel : PageModel
    {
        public void OnGet()
        {
            DdlPageSetup = "Document";
            DdlPageSize = "A4";
            DdlPageOrientation = "Portrait";
            DdlBookmarks = "Headings";
            DdlPdfStandard = "Full";
            DdlAccessibility = "None";
            TxtTitle = "SelectPdf - Word document";
            TxtLanguage = "en-US";
            TxtMargins = "0";
        }

        // An uploaded Word document, or nothing - the shipped files/document.docx is converted then.
        [BindProperty]
        public IFormFile FileWord { get; set; }

        [BindProperty]
        public string DdlPageSetup { get; set; }

        public List<SelectListItem> PageSetups { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Document", Text = "Document - keep the Word page sizes" },
            new SelectListItem { Value = "Options", Text = "Options - reflow onto the page set here" },
        };

        [BindProperty]
        public string DdlPageSize { get; set; }

        public List<SelectListItem> PageSizes { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "A3", Text = "A3" },
            new SelectListItem { Value = "A4", Text = "A4" },
            new SelectListItem { Value = "A5", Text = "A5" },
            new SelectListItem { Value = "Letter", Text = "Letter" },
            new SelectListItem { Value = "Legal", Text = "Legal" },
        };

        [BindProperty]
        public string DdlPageOrientation { get; set; }

        public List<SelectListItem> PageOrientations { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Portrait", Text = "Portrait" },
            new SelectListItem { Value = "Landscape", Text = "Landscape" },
        };

        [BindProperty]
        public string TxtMargins { get; set; }

        [BindProperty]
        public string DdlBookmarks { get; set; }

        public List<SelectListItem> Bookmarks { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Headings", Text = "From the headings" },
            new SelectListItem { Value = "Bookmarks", Text = "From the Word bookmarks" },
            new SelectListItem { Value = "None", Text = "None" },
        };

        [BindProperty]
        public string DdlPdfStandard { get; set; }

        public List<SelectListItem> PdfStandards { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "Full", Text = "Full (no standard)" },
            new SelectListItem { Value = "PdfA", Text = "PDF/A-1b" },
            new SelectListItem { Value = "PdfA2B", Text = "PDF/A-2b" },
            new SelectListItem { Value = "PdfA3B", Text = "PDF/A-3b" },
            new SelectListItem { Value = "PdfA4", Text = "PDF/A-4" },
        };

        [BindProperty]
        public string DdlAccessibility { get; set; }

        public List<SelectListItem> Accessibility { get; } = new List<SelectListItem>
        {
            new SelectListItem { Value = "None", Text = "None" },
            new SelectListItem { Value = "UA1", Text = "PDF/UA-1" },
            new SelectListItem { Value = "UA2", Text = "PDF/UA-2 (PDF 2.0)" },
        };

        [BindProperty]
        public string TxtTitle { get; set; }

        [BindProperty]
        public string TxtLanguage { get; set; }

        [BindProperty]
        public bool ChkHeader { get; set; }

        [BindProperty]
        public bool ChkPageNumbers { get; set; }

        public IActionResult OnPost()
        {
            // read parameters from the webpage
            WordPageSetup pageSetup = SampleForm.ParseEnum(DdlPageSetup, WordPageSetup.Document);
            PdfPageSize pageSize = SampleForm.ParseEnum(DdlPageSize, PdfPageSize.A4);
            PdfPageOrientation pdfOrientation = SampleForm.ParseEnum(DdlPageOrientation, PdfPageOrientation.Portrait);
            WordBookmarks bookmarks = SampleForm.ParseEnum(DdlBookmarks, WordBookmarks.Headings);
            PdfStandard pdfStandard = SampleForm.ParseEnum(DdlPdfStandard, PdfStandard.Full);
            PdfUAStandard accessibility = SampleForm.ParseEnum(DdlAccessibility, PdfUAStandard.None);

            int margins = 0;
            try
            {
                margins = Convert.ToInt32(TxtMargins);
            }
            catch { }

            // instantiate a word to pdf converter object
            WordToPdf converter = new WordToPdf();

            // set converter options: the page setup policy decides whether the page size,
            // orientation and margins below are applied (Options) or the Word document's own
            // pages are kept (Document) - the margins and the bands apply either way
            converter.Options.PageSetup = pageSetup;
            converter.Options.PdfPageSize = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.MarginLeft = margins;
            converter.Options.MarginRight = margins;
            converter.Options.MarginTop = margins;
            converter.Options.MarginBottom = margins;
            converter.Options.Bookmarks = bookmarks;
            converter.Options.PdfStandard = pdfStandard;

            // accessibility: the Word document's headings, paragraphs, tables, pictures and links
            // become the logical structure of the pdf; a declared standard needs a title and a
            // language (PDF/UA-2 is written as PDF 2.0 and combines with PDF/A-4 only)
            converter.Options.AccessibilityStandard = accessibility;
            converter.Options.Title = TxtTitle;
            converter.Options.Language = TxtLanguage;

            // a text header band and a page-number footer; a PdfWordSection could carry a Word
            // document as the band instead, and a PdfHtmlSection an html one. A width of -1 spans the
            // whole band, so the centered texts stay centered whatever the page size and margins.
            if (ChkHeader)
            {
                converter.Options.DisplayHeader = true;
                converter.Header.Height = 40;
                PdfTextSection headerText = new PdfTextSection(0, 16, -1, "Converted with SelectPdf Word to Pdf",
                    PdfFont.CreateStandardFont(PdfStandardFont.HelveticaBold, 10), new PdfColor(44, 62, 80));
                headerText.HorizontalAlign = PdfTextHorizontalAlign.Center;
                converter.Header.Add(headerText);
            }
            if (ChkPageNumbers)
            {
                converter.Options.DisplayFooter = true;
                converter.Footer.Height = 30;
                PdfTextSection pageNumbers = new PdfTextSection(0, 8, -1, "Page {page_number} of {total_pages}",
                    PdfFont.CreateStandardFont(PdfStandardFont.Helvetica, 9), new PdfColor(80, 80, 80));
                pageNumbers.HorizontalAlign = PdfTextHorizontalAlign.Center;
                converter.Footer.Add(pageNumbers);
            }

            // convert the uploaded document, or the sample one shipped with the application
            PdfDocument doc;
            if (FileWord != null && FileWord.Length > 0)
            {
                using (MemoryStream uploaded = new MemoryStream())
                {
                    FileWord.CopyTo(uploaded);
                    uploaded.Position = 0;
                    // the format is taken from the uploaded file's name, since a stream carries none
                    WordFormat format = WordFormatFromFileName(FileWord.FileName);
                    doc = converter.ConvertStream(uploaded, format);
                }
            }
            else
            {
                string wordFile = Path.Combine(Startup.ServerPath, "wwwroot", "files", "document.docx");
                doc = converter.ConvertFile(wordFile);
            }

            // 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;
        }

        private static WordFormat WordFormatFromFileName(string fileName)
        {
            switch ((Path.GetExtension(fileName) ?? string.Empty).ToLowerInvariant())
            {
                case ".docx": return WordFormat.Docx;
                case ".docm": return WordFormat.Docm;
                case ".dotx": return WordFormat.Dotx;
                case ".dotm": return WordFormat.Dotm;
                case ".doc": return WordFormat.Doc;
                case ".dot": return WordFormat.Dot;
                case ".rtf": return WordFormat.Rtf;
                case ".txt": return WordFormat.Txt;
                default: return WordFormat.Automatic;
            }
        }
    }
}