Flatten PDF Form

The PDF Document API allows you to flatten interactive forms. Click Select File to load a PDF file with form fields. Click Flatten and Download to flatten the form and save the result to your computer.

Select a file
Maximum file size: 10Mb
Flatten and Download
@model AspNetCoreDemos.OfficeFileAPI.PdfFormFlatteningModel
@using DevExtreme.AspNet.Mvc

@using (Html.BeginForm("FlattenFormFields", "PdfForms", FormMethod.Post)) {
    @Html.HiddenFor(model => model.DocumentUrl)
    <div class="upload-proceed">
        <div class="upload-proceed-item">
            @(Html.DevExtreme().FileUploader()
                               .ID("file-uploader")
                               .Name("myFile")
                               .Multiple(false)
                               .ShowFileList(false)
                               .Accept(".pdf")
                               .AllowedFileExtensions(new List<string> { ".pdf" })
                               .MaxFileSize(10485760)
                               .LabelText("Maximum file size: 10Mb")
                               .UploadMode(FileUploadMode.Instantly)
                               .UploadUrl(Url.Action("DocumentUpload", "PdfForms"))
                               .OnValueChanged("fileUploader_valueChanged")
                               .OnUploaded("UpdatePreview")
            )
        </div>
        <div class="upload-proceed-item">
            @(Html.DevExtreme().Button()
                               .Text("Flatten and Download")
                               .Type(ButtonType.Default)
                               .StylingMode(ButtonStylingMode.Contained)
                               .UseSubmitBehavior(true)
            )
        </div>
    </div>

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

    <script>
        function fileUploader_valueChanged(e) {
            var files = e.value;
            if (files.length > 0) {
                $("#selected-files .selected-item").remove();

                $.each(files, function (i, file) {
                    var $selectedItem = $("<div />").addClass("selected-item");
                    $selectedItem.append(file.name);
                    $selectedItem.appendTo($("#selected-files"));
                });
                $("#selected-files").show();

                $('#DocumentUrl').val(files[0].name);
            }
            else
                $("#selected-files").hide();
        }

        function UpdatePreview() {
            var params = "DocumentUrl=" + $('#DocumentUrl').val();
            PdfPreview.Update(params);
        }
    </script>
}
@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";
    }
}
namespace AspNetCoreDemos.OfficeFileAPI {
    public class PdfFormFlatteningModel : PdfModelBase {
        public PdfFormFlatteningModel() {
            PreviewModel.PreviewDocumentAction = "DocumentViewPartial";
            PreviewModel.ControllerName = "PdfForms";
            PreviewModel.IsViewWithoutSidePanel = true;
        }

        internal override string SessionKey { get { return "PdfFormsKey"; } }
    }
}
using DevExpress.Pdf;
using Microsoft.AspNetCore.Mvc;
using System.IO;

namespace AspNetCoreDemos.OfficeFileAPI {
    public partial class PdfFormsController {
        public IActionResult FormFlattening() {
            return GetDemoView<PdfFormFlatteningModel>("FormFlattening", SessionKey, HostingEnvironment.ContentRootPath + formDefaultFile);
        }
        public IActionResult FlattenFormFields(PdfFormFlatteningModel model) {
            using(PdfDocumentProcessor processor = new PdfDocumentProcessor()) {
                byte[] fileData;
                if(!HttpContext.Session.TryGetValue(model.SessionKey, out fileData))
                    return new NotFoundObjectResult(fileData);
                using(Stream stream = new MemoryStream(fileData)) {
                    processor.LoadDocument(stream);
                    processor.FlattenForm();
                    Stream outStream = new MemoryStream();
                    processor.SaveDocument(outStream);
                    return CreateFileStreamResult(outStream, "application/pdf", "pdf", "Result");
                }
            }
        }
    }
}
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);
        }
    }
}