Fill PDF Form

This demo illustrates how to use the PDF Document API to programmatically fill out an interactive PDF form. Use the Options pane to specify form field values and click Submit to view the result.

Options
First Name
Last Name
Gender
Date of Birth
Passport No
Nationality
Address
Visa No
Flight No
@model AspNetCoreDemos.OfficeFileAPI.PdfFormFillingModel
@using DevExtreme.AspNet.Mvc

<script type="text/javascript">
    function FillForm() {
        const options = { year: 'numeric', month: '2-digit', day: '2-digit' };
        const dateFormat = new Intl.DateTimeFormat('en-US', options).format;
        $.ajax({
            type: "POST",
            url: '@Url.Action("FillForm", "PdfForms")',
            data: {
                firstName: $("#FirstName").dxTextBox('instance').option('value'),
                lastName: $("#LastName").dxTextBox('instance').option('value'),
                gender: $("#Gender").dxSelectBox('instance').option('value'),
                date: dateFormat(new Date($("#Date").dxDateBox('instance').option('value'))),
                passport: $("#Passport").dxTextBox('instance').option('value'),
                nationality: $("#Nationality").dxSelectBox('instance').option('value'),
                address: $("#Address").dxTextBox('instance').option('value'),
                visa: $("#Visa").dxTextBox('instance').option('value'),
                flight: $("#Flight").dxTextBox('instance').option('value'),
            },
            success: function () { PdfPreview.Update(); }
        });
    }
</script>

<div class="demo-view-container demo-preview-border">
    @(Html.DevExtreme().ScrollView()
                .ID("scrollview")
                .ScrollByContent(true)
                .ScrollByThumb(true)
                .ShowScrollbar(ShowScrollbarMode.OnHover)
                .Direction(ScrollDirection.Both)
                .Height("700px")
                .Content(@<text>
                    <div id="scrollview-content">
                        @await Html.PartialAsync("PdfFileView", Model.PreviewModel)
                    </div>
                </text>)
    )
</div>

<div class="options">
    <div class="caption">Options</div>
    <div class="option">
        <div class="label">First Name</div>
        @(Html.DevExtreme().TextBoxFor(m => m.FirstName).ID("FirstName"))
    </div>
    <div class="option">
        <div class="label">Last Name</div>
        @(Html.DevExtreme().TextBoxFor(m => m.LastName).ID("LastName"))
    </div>
    <div class="option">
        <div class="label">Gender</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.Gender)
                           .ID("Gender")
                           .DataSource(Html.GetEnumSelectList<AspNetCoreDemos.OfficeFileAPI.Gender>()
                           .Select(i => new { Value = int.Parse(i.Value), Text = i.Text }))
                           .ValueExpr("Value")
                           .DisplayExpr("Text")
        )
    </div>
    <div class="option">
        <div class="label">Date of Birth</div>
        @(Html.DevExtreme().DateBoxFor(m => m.Date)
                           .ID("Date")
                           .Type(DateBoxType.Date)
                           .Width("100%")
                           .DateSerializationFormat("MM/dd/yyyy")
        )
    </div>
    <div class="option">
        <div class="label">Passport No</div>
        @(Html.DevExtreme().TextBoxFor(m => m.Passport).ID("Passport"))
    </div>
    <div class="option">
        <div class="label">Nationality</div>
        @(Html.DevExtreme().SelectBoxFor(m => m.Nationality)
                           .ID("Nationality")
                           .DataSource(Model.NationalityList)
        )
    </div>
    <div class="option">
        <div class="label">Address</div>
        @(Html.DevExtreme().TextBoxFor(m => m.Address).ID("Address"))
    </div>
    <div class="option">
        <div class="label">Visa No</div>
        @(Html.DevExtreme().TextBoxFor(m => m.Visa).ID("Visa"))
    </div>
    <div class="option">
        <div class="label">Flight No</div>
        @(Html.DevExtreme().TextBoxFor(m => m.Flight).ID("Flight"))
    </div>
    <div class="option-buttons">
        @(Html.DevExtreme().Button()
                           .ID("submitButton")
                           .Text("Submit")
                           .Type(ButtonType.Default)
                           .StylingMode(ButtonStylingMode.Contained)
                           .OnClick("FillForm")
       )
    </div>
</div>
@model AspNetCoreDemos.OfficeFileAPI.PdfPreviewModel

<img id="previewImage" src="@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)" class="preview-image-bordered @(Model.IsViewWithoutSidePanel ? "preview-image-without-side-panel" : "preview-image-with-side-panel")" />

<script type="text/javascript">
    PdfPreview = {
        basePath: '@Url.Action(Model.PreviewDocumentAction, Model.ControllerName)',
        Update: function (param) {
            var iframeElement = document.getElementById("previewImage");
            if (!iframeElement)
                return;
            var additionalParams = "&" + new Date().valueOf();
            if (param)
                additionalParams = param;
            iframeElement.src = this.basePath + "?" + additionalParams;
        }
    };
</script>
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Logging;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class PdfFormsController : DocumentProcessingController {
        protected const string formDefaultFile = "/Documents/Pdf/FormDemo.pdf";

        public PdfFormsController(ILogger<PdfFormsController> logger, IWebHostEnvironment hostingEnvironment)
            : base(logger, hostingEnvironment) {
        }

        protected override string SessionKey => "PdfFormsKey";
    }
}
using System;
using System.IO;
using System.Collections.Generic;
using DevExpress.Pdf;

namespace AspNetCoreDemos.OfficeFileAPI {
    public enum Gender {
        Female,
        Male
    }

    public class PdfFormFillingModel : PdfModelBase {
        public PdfFormFillingModel() {
            PreviewModel.PreviewDocumentAction = "DocumentViewPartial";
            PreviewModel.ControllerName = "PdfForms";

            Nationality = "United States";
            FirstName = "Janet";
            LastName = "Leverling";
            Gender = Gender.Female;
            Date = new DateTime(1985, 8, 30);
            Passport = "31195855";
            Address = "98033, 722 Moss Bay Blvd., Kirkland, WA, USA";
            Visa = "73203393";
            Flight = "(KL) KLM 876";
        }

        public IList<string> NationalityList { get; private set; }
        internal override string SessionKey { get { return "PdfFormsKey"; } }

        public string FirstName { get; set; }
        public string LastName { get; set; }
        public Gender Gender { get; set; }
        public DateTime Date { get; set; }
        public string Passport { get; set; }
        public string Nationality { get; set; }
        public string Address { get; set; }
        public string Visa { get; set; }
        public string Flight { get; set; }

        public override void LoadDocument(byte[] data) {
            base.LoadDocument(data);
            PdfDocumentProcessor processor = Processor;
            processor.ResetFormData();
            NationalityList = new List<string>();
            foreach (PdfInteractiveFormField field in processor.Document.AcroForm.Fields) {
                if (field.Name == "Nationality") {
                    PdfChoiceFormField choiceField = field as PdfChoiceFormField;
                    if (choiceField != null)
                        foreach (PdfOptionsFormFieldOption option in choiceField.Options)
                            NationalityList.Add(option.ExportText);
                }
            }
        }

        internal byte[] FillForm(string firstName, string lastName, Gender gender, string date, string passport, string nationality, string address, string visa, string flight) {
            if (Processor.Document.Pages.Count > 0) {
                PdfFormData formData = new PdfFormData();
                formData["LastName"].Value = lastName;
                formData["FirstName"].Value = firstName;
                formData["Gender"].Value = gender == Gender.Female ? "Female" : "Male";
                string[] dateValues = date.Split('/');
                formData["MM"].Value = dateValues[0];
                formData["DD"].Value = dateValues[1];
                formData["YYYY"].Value = dateValues[2];
                formData["PassportNo"].Value = passport;
                formData["Nationality"].Value = nationality;
                formData["Address"].Value = address;
                formData["VisaNo"].Value = visa;
                formData["FlightNo"].Value = flight;
                Processor.ApplyFormData(formData);
            }
            using (MemoryStream stream = new MemoryStream()) {
                Processor.SaveDocument(stream);
                stream.Position = 0;
                Items.Clear();
                LoadDocument(stream);
                return stream.GetBuffer();
            }
        }
    }
}
using Microsoft.AspNetCore.Mvc;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class PdfFormsController {
        public IActionResult FormFilling() {
            return GetDemoView<PdfFormFillingModel>("FormFilling", SessionKey, HostingEnvironment.ContentRootPath + formDefaultFile);
        }

        public IActionResult DocumentViewPartial(PdfFormFillingModel flatteningModel) {
            return base.DocumentViewPartial(flatteningModel);
        }

        public IActionResult FillForm(string firstName, string lastName, Gender gender, string date, string passport, string nationality, string address, string visa, string flight) {
            using(PdfFormFillingModel model = new PdfFormFillingModel()) {
                byte[] data;
                if(HttpContext.Session.TryGetValue(SessionKey, out data)) {
                    model.LoadDocument(data);
                    HttpContext.Session.Set(SessionKey, model.FillForm(firstName, lastName, gender, date, passport, nationality, address, visa, flight));
                }
                return new EmptyResult();
            }
        }
    }
}
using System;
using System.Collections.Generic;
using System.IO;
using DevExpress.Pdf;

namespace AspNetCoreDemos.OfficeFileAPI {
    public class PdfModelBase : IDisposable {
        readonly PdfDocumentProcessor processor;
        MemoryStream stream;
        List<PdfPageModel> items = new List<PdfPageModel>();

        public MemoryStream Stream { get { return stream; } }
        protected PdfDocumentProcessor Processor { get { return processor; } }
        protected PdfDocument Document { get { return processor.Document; } }
        public List<PdfPageModel> Items { get { return items; } }

        public string DocumentUrl { get; set; }
        public int PageIndex { get; set; }
        internal virtual string SessionKey { get; }
        public PdfPreviewModel PreviewModel { get; internal set; }

        public PdfModelBase() {
            processor = new PdfDocumentProcessor();
            PreviewModel = new PdfPreviewModel();
        }

        protected void CreateEmptyDocument() {
            stream = new MemoryStream();
            Processor.CreateEmptyDocument(stream);
            Document.Creator = "PDF Document Processor Demo";
            Document.Producer = "Developer Express Inc., " + AssemblyInfo.Version;
            Document.Author = "DevExpress Inc.";
        }

        public virtual void LoadDocument(byte[] data) {
            using(MemoryStream stream = new MemoryStream(data))
                LoadDocument(stream);
        }

        protected void LoadDocument(Stream stream) {
            processor.LoadDocument(stream, true);
            for(int pageNumber = 1; pageNumber <= processor.Document.Pages.Count; pageNumber++)
                Items.Add(new PdfPageModel(processor, pageNumber));
        }

        public void Dispose() {
            if(processor != null)
                processor.Dispose();
            GC.SuppressFinalize(this);
        }
    }
}