Create PDF Forms from HTML Forms

HiQPdf HTML to PDF Converter can be configured to automatically convert HTML form controls to interactive PDF form fields by setting the PdfDocumentControlGeneratePdfFormFields property to true. An object of type PdfDocumentControl is exposed by the HtmlToPdfDocument property

You can also use the object of type PdfFormOptions, exposed by the PdfDocumentControlPdfFormOptions property, to control field naming, button actions, submit behavior, validation mapping and diagnostics for HTML to PDF form conversion.

Form Options

The PdfFormOptions object of PdfFormOptions controls how the HTML form controls become PDF fields. FieldNamingMode selects the names of the fields: the HTML names when they are unique, the HTML names as they are, or names qualified with the form and the position of the control. ApplyRequiredAsPdfRequiredFlag marks the HTML required fields as required in the PDF form, IncludeIFrameFields converts the controls of the iframes of the page, ExcludedFieldsSelector gives a CSS selector of the controls that stay as the page renders them instead of becoming fields and ValidationBehavior generates a basic validation script from the HTML validation attributes. FormFieldFont and its bold, italic and bold italic variants give the font of the text displayed in the fields; a standard font is used when they are not set.

The HTML submit and reset buttons receive PDF actions when EnableButtonActions, MapHtmlSubmitButtonsToPdfActions and MapHtmlResetButtonsToPdfActions are true. SubmitBehavior selects a native PDF submit action or a script that submits the form like a browser does and SubmitFormat the format of the submitted data. SubmitOnlyFieldsFromButtonForm and ResetOnlyFieldsFromButtonForm limit the actions to the fields of the HTML form of the button, ExcludeDisabledFieldsFromSubmit and IncludeReadOnlyFieldsInSubmit select the disabled and read-only fields submitted.

Set the Form Options
PdfFormOptions formOptions = htmlToPdfConverter.Document.PdfFormOptions;
formOptions.FieldNamingMode = PdfFieldNamingMode.PreserveHtmlNamesWhenSafe;
formOptions.ApplyRequiredAsPdfRequiredFlag = true;
formOptions.SubmitBehavior = PdfSubmitBehavior.NativePdfAction;
formOptions.SubmitFormat = PdfSubmitFormat.Html;
formOptions.ValidationBehavior = PdfValidationBehavior.AcrobatJavaScriptBasic;
formOptions.FormFieldFont = PdfFontManager.CreateBaseFont(fontFilePath);

Code Sample - Auto Create PDF Forms from HTML Forms

C#
using System;
using System.IO;
using System.ComponentModel.DataAnnotations;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using HiQPdf_Next_AspNetDemo.Models;

using HiQPdf.Next;

namespace HiQPdf_Next_AspNetDemo.Controllers
{
    public class CreatePdfFormsFromHtmlFormsController : Controller
    {
        private readonly IWebHostEnvironment m_hostingEnvironment;
        public CreatePdfFormsFromHtmlFormsController(IWebHostEnvironment hostingEnvironment)
        {
            m_hostingEnvironment = hostingEnvironment;
        }

        public ActionResult Index()
        {
            var model = SetViewModel();

            return View(model);
        }

        [HttpPost]
        public ActionResult ConvertHtmlToPdf(CreatePdfFormsFromHtmlFormsViewModel model)
        {
            if (!ModelState.IsValid)
            {
                var errorMessage = ModelStateHelper.GetModelErrors(ModelState);
                throw new ValidationException(errorMessage);
            }

            // Set the serial number received after purchase to use the library in licensed mode; leave it commented for demo mode
            // Licensing.SerialNumber = "your-serial-number";

            // Create a HTML to PDF converter object with default settings
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            // Specifies whether HTML form controls are converted to interactive PDF form fields
            htmlToPdfConverter.Document.GeneratePdfFormFields = model.GeneratePdfFormFields;

            PdfFormOptions formOptions = htmlToPdfConverter.Document.PdfFormOptions;

            // The names of the PDF fields: the HTML names when they are unique, the HTML names as they are, or
            // names qualified with the form and the position of the control
            formOptions.FieldNamingMode = (PdfFieldNamingMode)Enum.Parse(typeof(PdfFieldNamingMode), model.FieldNamingMode);

            // The actions of the generated buttons: the HTML submit and reset buttons submit and reset the PDF form
            formOptions.EnableButtonActions = model.EnableButtonActions;
            formOptions.MapHtmlSubmitButtonsToPdfActions = model.MapHtmlSubmitButtonsToPdfActions;
            formOptions.MapHtmlResetButtonsToPdfActions = model.MapHtmlResetButtonsToPdfActions;

            // The fields submitted or reset by a button: only the fields of its HTML form, or all the fields
            formOptions.SubmitOnlyFieldsFromButtonForm = model.SubmitOnlyFieldsFromButtonForm;
            formOptions.ResetOnlyFieldsFromButtonForm = model.ResetOnlyFieldsFromButtonForm;
            formOptions.ExcludeDisabledFieldsFromSubmit = model.ExcludeDisabledFieldsFromSubmit;
            formOptions.IncludeReadOnlyFieldsInSubmit = model.IncludeReadOnlyFieldsInSubmit;

            // The HTML required attribute marks the PDF field as required
            formOptions.ApplyRequiredAsPdfRequiredFlag = model.ApplyRequiredAsPdfRequiredFlag;

            // The submit action is a native PDF action or a script that submits the form like a browser does;
            // the format is the format of the submitted data
            formOptions.SubmitBehavior = (PdfSubmitBehavior)Enum.Parse(typeof(PdfSubmitBehavior), model.SubmitBehavior);
            formOptions.SubmitFormat = (PdfSubmitFormat)Enum.Parse(typeof(PdfSubmitFormat), model.SubmitFormat);

            // A basic validation script can be generated from the HTML validation attributes
            formOptions.ValidationBehavior = (PdfValidationBehavior)Enum.Parse(typeof(PdfValidationBehavior), model.ValidationBehavior);

            if (model.UseFormFieldFont)
            {
                // The font of the text displayed in the fields; a standard font is used otherwise
                string fontFilePath = Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot", "DemoFiles", "Fonts", "DejaVuSerif.ttf");
                formOptions.FormFieldFont = PdfFontManager.CreateBaseFont(fontFilePath);
            }

            byte[] outPdfBuffer = null;

            if (model.HtmlPageSource == "Html")
            {
                string htmlWithForm = model.HtmlString;
                string baseUrl = model.BaseUrl;

                // Convert a HTML string to a PDF document
                outPdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlWithForm, baseUrl);
            }
            else
            {
                string url = model.Url;

                // Convert the HTML page to a PDF document
                outPdfBuffer = htmlToPdfConverter.ConvertUrlToMemory(url);
            }

            // Send the PDF file to browser
            FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
            fileResult.FileDownloadName = "CreatePdfForms.pdf";

            return fileResult;
        }

        private CreatePdfFormsFromHtmlFormsViewModel SetViewModel()
        {
            var model = new CreatePdfFormsFromHtmlFormsViewModel();

            var contentRootPath = Path.Combine(m_hostingEnvironment.ContentRootPath, "wwwroot");

            HttpRequest request = ControllerContext.HttpContext.Request;
            UriBuilder uriBuilder = new UriBuilder();
            uriBuilder.Scheme = request.Scheme;
            uriBuilder.Host = request.Host.Host;
            if (request.Host.Port != null)
                uriBuilder.Port = (int)request.Host.Port;
            uriBuilder.Path = request.PathBase.ToString() + request.Path.ToString();
            uriBuilder.Query = request.QueryString.ToString();

            string currentPageUrl = uriBuilder.Uri.AbsoluteUri;
            string rootUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "CreatePdfFormsFromHtmlForms".Length);

            model.HtmlString = System.IO.File.ReadAllText(Path.Combine(contentRootPath, "DemoFiles/Html/HTML_Form.html"));
            model.BaseUrl = rootUrl + "DemoFiles/Html/";
            model.Url = rootUrl + "DemoFiles/Html/HTML_Form.html";

            return model;
        }
    }
}

See Also