Skip to main content Skip to footer

How to Automate PDF Forms with a C# .NET PDF API

Quick Start Guide
Tutorial Concept

C# .NET PDF Form Automation - PDF documents can have user input capabilities automated in desktop applications using a C# .NET PDF API. This tutorial will use DsPdf to efficiently automate loan documents.

What You Will Need

Document Solutions for PDF

Visual Studio 2022

Controls Referenced DsPdf

Why waste time with manual paperwork? Switch to digital forms and streamline your process today!

Digital PDF forms are important because they enable users to complete tasks faster and easier. Unlike paper forms, you can fill them on any device and avoid the hassle of scanning or mailing them. Digital PDF forms are quicker for the person filling them out and the businesses receiving them.

MESCIUS offers the Document Solutions for Pdf (DsPdf) API for programmatically creating and working with PDF documents. It allows developers to automate the generation of PDF content, including interactive forms, whether you're building a form from scratch or modifying an existing PDF.

In this blog, we'll create a digital loan request PDF form using DsPdf, automatically filling it with user-provided data from the website. This ensures accuracy and offers a faster, more efficient loan application process. Let's walk through the steps to create the loan submission form using DsPdf:

Ready to Get Started? Download Document Solutions for PDF Today!

Design Web Form for User Input

Let's build a web form in an ASP.NET Core MVC application to collect essential information from users, such as their personal details, employment information, and loan request specifics. This data will be captured when users submit the form by clicking the button. Below is the HTML code for creating the user form:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>XYZ Bank Loan Application Form</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            margin: 0;
            padding: 20px;
            background-color: #f4f4f4; /* Light background to improve readability */
        }
        .form-container {
            background-color: #fff;
            padding: 20px;
            border-radius: 8px;
            max-width: 600px;
            margin: 0 auto;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        h2 {
            text-align: center;
            color: #004085;
        }
        .form-header {
            text-align: center;
            margin-bottom: 30px;
        }
        .image-container {
            width: 150px;
            margin: 0 auto;
            overflow: hidden;
        }
        .image-container img {
            width: 100%;
            height: auto;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
        }
        .form-group {
            margin-bottom: 20px;
        }
        input[type="text"], input[type="email"], input[type="number"], input[type="date"], input[type="tel"], select {
            width: calc(100% - 20px); /* Make room for the right margin */
            padding: 10px;
            border: 1px solid #ccc;
            border-radius: 4px;
            margin-right: 20px; /* Adds margin to the right of the input fields */
        }
        input[type="text"]::placeholder, input[type="email"]::placeholder, input[type="number"]::placeholder, input[type="tel"]::placeholder {
            color: #999;
        }
        button {
            display: block;
            width: 100%;
            padding: 10px;
            background-color: #004085;
            color: #fff;
            border: none;
            border-radius: 4px;
            cursor: pointer;
            font-size: 16px;
        }
        button:hover {
            background-color: #003366;
        }
    </style>
</head>
<body>

    <div class="form-container">
        <div class="form-header">
            <div class="image-container">
                <img src="https://www.freepnglogos.com/uploads/logo-bca-png/bank-bca-logo-vector-format-cdr-eps-svg-pdf-png-0.png" alt="XYZ Bank Logo">
            </div>
            <h2>Loan Application Form</h2>
        </div>

        <form asp-action="SubmitLoanApplication" method="POST">
            <!-- Personal Information -->
            <div class="form-group">
                <label for="fullName">Full Name:</label>
                <input type="text" id="fullName" name="fullName" placeholder="Enter your full name" required>
            </div>

            <div class="form-group">
                <label for="dob">Date of Birth:</label>
                <input type="date" id="dob" name="dob" placeholder="Enter your date of birth" required>
            </div>

            <div class="form-group">
                <label for="address">Residential Address:</label>
                <input type="text" id="address" name="address" placeholder="Enter your residential address" required>
            </div>

            <div class="form-group">
                <label for="email">Email Address:</label>
                <input type="email" id="email" name="email" placeholder="Enter your email address" required>
            </div>

            <div class="form-group">
                <label for="phoneNumber">Phone Number:</label>
                <input type="text" id="phoneNumber" name="phoneNumber" placeholder="Enter your 10-digit phone number" required maxlength="10" title="Please enter a valid 10-digit phone number">
            </div>

            <!-- Employment Details -->
            <div class="form-group">
                <label for="employmentStatus">Employment Status:</label>
                <select id="employmentStatus" name="employmentStatus" required>
                    <option value="">Select employment status</option>
                    <option value="employed">Employed</option>
                    <option value="self-employed">Self-Employed</option>
                    <option value="unemployed">Unemployed</option>
                </select>
            </div>

            <div class="form-group">
                <label for="jobTitle">Occupation/Job Title:</label>
                <input type="text" id="jobTitle" name="jobTitle" placeholder="Enter your job title">
            </div>

            <div class="form-group">
                <label for="employerName">Employer's Name:</label>
                <input type="text" id="employerName" name="employerName" placeholder="Enter your employer's name">
            </div>

            <div class="form-group">
                <label for="employmentYears">Years of Employment:</label>
                <input type="number" id="employmentYears" name="employmentYears" placeholder="Enter years of employment">
            </div>

            <!-- Loan Details -->
            <div class="form-group">
                <label for="loanAmount">Loan Amount:</label>
                <input type="number" id="loanAmount" name="loanAmount" placeholder="Enter the loan amount you need" required>
            </div>

            <div class="form-group">
                <label for="loanType">Loan Type:</label>
                <select id="loanType" name="loanType" required>
                    <option value="">Select loan type</option>
                    <option value="home">Home Loan</option>
                    <option value="personal">Personal Loan</option>
                    <option value="auto">Auto Loan</option>
                    <option value="education">Education Loan</option>
                </select>
            </div>

            <div class="form-group">
                <label for="loanTerm">Loan Term (in years):</label>
                <input type="number" id="loanTerm" name="loanTerm" placeholder="Enter loan term in years" required>
            </div>

            <!-- Financial Information -->
            <div class="form-group">
                <label for="annualIncome">Annual Income:</label>
                <input type="number" id="annualIncome" name="annualIncome" placeholder="Enter your annual income" required>
            </div>

            <div class="form-group">
                <label for="monthlyExpenses">Monthly Expenses:</label>
                <input type="number" id="monthlyExpenses" name="monthlyExpenses" placeholder="Enter your monthly expenses" required>
            </div>

            <div class="form-group">
                <label for="creditScore">Credit Score:</label>
                <input type="number" id="creditScore" name="creditScore" placeholder="Enter your credit score" required>
            </div>

            <div class="form-group">
                <label for="existingLoans">Existing Loans or Debts:</label>
                <input type="text" id="existingLoans" name="existingLoans" placeholder="Enter any existing loans or debts">
            </div>

            <!-- Co-Signer (optional) -->
            <div class="form-group">
                <label for="coSigner">Co-Signer (if applicable):</label>
                <input type="text" id="coSigner" name="coSigner" placeholder="Enter co-signer's name (if applicable)">
            </div>

            <!-- Submit Button -->
            <button type="submit">Submit Loan Application</button>
        </form>
    </div>

    <script>
        const phoneInput = document.getElementById('phoneNumber');

        phoneInput.addEventListener('input', function () {
            // Remove any non-digit character from the input value
            this.value = this.value.replace(/[^0-9]/g, '');

            // Ensure the number does not exceed 10 digits
            if (this.value.length > 10) {
                this.value = this.value.slice(0, 10);
            }
        });
    </script>

</body>
</html>

The user form created using the above code is shown below:

user form

We’ve created a LoanApplicationModel class to manage and store the form inputs. When the user clicks the button, the model captures the data, and the controller processes it for further actions. Below is the code of the Model and Controller to fetch the filled information:

  public class LoanApplicationModel
  {
      // Personal Information
      [Required(ErrorMessage = "Full Name is required")]
      public string FullName { get; set; }

      [Required(ErrorMessage = "Date of Birth is required")]
      [DataType(DataType.Date)]
      public DateTime DOB { get; set; }

      [Required(ErrorMessage = "Residential Address is required")]
      public string Address { get; set; }

      [Required(ErrorMessage = "Email Address is required")]
      [EmailAddress(ErrorMessage = "Invalid email format")]
      public string Email { get; set; }

      [Required(ErrorMessage = "Phone Number is required")]
      [StringLength(10, ErrorMessage = "Phone number must be 10 digits")]
      [RegularExpression(@"^\d{10}$", ErrorMessage = "Invalid phone number")]
      public string PhoneNumber { get; set; }

      // Employment Details
      [Required(ErrorMessage = "Employment Status is required")]
      public string EmploymentStatus { get; set; }

      public string JobTitle { get; set; }

      public string EmployerName { get; set; }

      [Range(0, 100, ErrorMessage = "Years of Employment must be between 0 and 100")]
      public int? EmploymentYears { get; set; }

      // Loan Details
      [Required(ErrorMessage = "Loan Amount is required")]
      [Range(0, Double.MaxValue, ErrorMessage = "Please enter a valid loan amount")]
      public decimal LoanAmount { get; set; }

      [Required(ErrorMessage = "Loan Type is required")]
      public string LoanType { get; set; }

      [Required(ErrorMessage = "Loan Term is required")]
      [Range(1, 50, ErrorMessage = "Loan term must be between 1 and 50 years")]
      public int LoanTerm { get; set; }

      // Financial Information
      [Required(ErrorMessage = "Annual Income is required")]
      [Range(0, Double.MaxValue, ErrorMessage = "Please enter a valid annual income")]
      public decimal AnnualIncome { get; set; }

      [Required(ErrorMessage = "Monthly Expenses are required")]
      [Range(0, Double.MaxValue, ErrorMessage = "Please enter valid monthly expenses")]
      public decimal MonthlyExpenses { get; set; }

      [Required(ErrorMessage = "Credit Score is required")]
      [Range(300, 850, ErrorMessage = "Credit score must be between 300 and 850")]
      public int CreditScore { get; set; }

      public string ExistingLoans { get; set; }

      // Co-Signer
      public string CoSigner { get; set; }
  }
 
 //HomeController.cs
[HttpPost]
 public IActionResult SubmitLoanApplication(LoanApplicationModel model)
 {
 //Controller Action to be performed here
 }

Generate Digital PDF Form Using DsPdf

In this step, we'll explore how to create a fillable PDF form, often called an AcroForm. The form includes fields like text boxes, checkboxes, buttons, and more, which users can fill out manually or through code. DsPdf provides various properties and methods in the AcroForm class to add, change, remove, and format these form fields. Refer to our documentation to learn more about form fields.

Below is the C# code to create the digital Loan request pdf form:

var doc = new GcPdfDocument();
var page = doc.NewPage();
var g = page.Graphics;
var tf = new TextFormat();
tf.Font = StandardFonts.Times;
tf.FontSize = 14;
var ip = new PointF(72, 72);
float fldOffset = 72 * 2;
float fldHeight = tf.FontSize * 1.2f;
float dY = 32;

g.DrawImage(Image.FromFile("bank-bca-logo-vector-format-cdr-eps-svg-pdf-png-0.png"), new RectangleF(150, 10, 200, 90), new ImageScale());

g.DrawString("Loan Application Form", new TextFormat()
{
    Font = StandardFonts.Times,
    FontSize = 20,
    FontBold = true,
    ForeColor = Color.DarkBlue
}, new PointF(150, 110));
ip.Y += 80;


// Full name Text field:
g.DrawString("Full Name:", tf, ip);
var fldFullNameText = new TextField();
fldFullNameText.Widget.Page = page;
fldFullNameText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldFullNameText.Widget.DefaultAppearance.Font = tf.Font;
fldFullNameText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldFullNameText);
ip.Y += dY;

// Date of Birth Text field:
g.DrawString("Date of Birth:", tf, ip);
var fldDOBText = new TextField();
fldDOBText.Widget.Page = page;
fldDOBText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldDOBText.Widget.DefaultAppearance.Font = tf.Font;
fldDOBText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldDOBText);
ip.Y += dY;

//Residential Address Text field:
g.DrawString("Residential Address:", tf, ip);
var fldAddressText = new TextField();
fldAddressText.Widget.Page = page;
fldAddressText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldAddressText.Widget.DefaultAppearance.Font = tf.Font;
fldAddressText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldAddressText);
ip.Y += dY;

//Email Address Text field:
g.DrawString("Email Address:", tf, ip);
var fldEmailText = new TextField();
fldEmailText.Widget.Page = page;
fldEmailText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldEmailText.Widget.DefaultAppearance.Font = tf.Font;
fldEmailText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldEmailText);
ip.Y += dY;

//Phone Number Text field:
g.DrawString("Phone Number:", tf, ip);
var fldPhoneNumberText = new TextField();
fldPhoneNumberText.Widget.Page = page;
fldPhoneNumberText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldPhoneNumberText.Widget.DefaultAppearance.Font = tf.Font;
fldPhoneNumberText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldPhoneNumberText);
ip.Y += dY;

// Employment Status Combo-box field:
g.DrawString("Employment Status:", tf, ip);
var fldEmploymentStatusComboBox = new ComboBoxField();
fldEmploymentStatusComboBox.Editable = true;
fldEmploymentStatusComboBox.Items.Add(new ChoiceFieldItem("Employed"));
fldEmploymentStatusComboBox.Items.Add(new ChoiceFieldItem("Self-Employed"));
fldEmploymentStatusComboBox.Items.Add(new ChoiceFieldItem("Unemployed"));
fldEmploymentStatusComboBox.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldEmploymentStatusComboBox.Widget.Page = page;
doc.AcroForm.Fields.Add(fldEmploymentStatusComboBox);
ip.Y += dY;

// Occupation/Job Title Text field:
g.DrawString("Occupation/Job Title:", tf, ip);
var fldJobTitleText = new TextField();
fldJobTitleText.Widget.Page = page;
fldJobTitleText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldJobTitleText.Widget.DefaultAppearance.Font = tf.Font;
fldJobTitleText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldJobTitleText);
ip.Y += dY;

//Employer's Name Text field:
g.DrawString("Employer's Name:", tf, ip);
var fldEmployerNameText = new TextField();
fldEmployerNameText.Widget.Page = page;
fldEmployerNameText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldEmployerNameText.Widget.DefaultAppearance.Font = tf.Font;
fldEmployerNameText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldEmployerNameText);
ip.Y += dY;

//Years of Employment Text field:
g.DrawString("Years of Employment:", tf, ip);
var fldYearsOfEmploymentText = new TextField();
fldYearsOfEmploymentText.Widget.Page = page;
fldYearsOfEmploymentText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldYearsOfEmploymentText.Widget.DefaultAppearance.Font = tf.Font;
fldYearsOfEmploymentText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldYearsOfEmploymentText);
ip.Y += dY;

//Loan Amount Text field:
g.DrawString("Loan Amount:", tf, ip);
TextField fldLoanAmountText = new TextField();
fldLoanAmountText.Widget.Page = page;
fldLoanAmountText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldLoanAmountText.Widget.DefaultAppearance.Font = tf.Font;
fldLoanAmountText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldLoanAmountText);
ip.Y += dY;

// Loan Type Combo-box field:
g.DrawString("Employment Status:", tf, ip);
var fldLoanTypeComboBox = new ComboBoxField();
//fldLoanTypeComboBox.Editable = true;
fldLoanTypeComboBox.Items.Add(new ChoiceFieldItem("Home Loan"));
fldLoanTypeComboBox.Items.Add(new ChoiceFieldItem("Personal Loan"));
fldLoanTypeComboBox.Items.Add(new ChoiceFieldItem("Auto Loan"));
fldLoanTypeComboBox.Items.Add(new ChoiceFieldItem("Education Loan"));
fldLoanTypeComboBox.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldLoanTypeComboBox.Widget.Page = page;
doc.AcroForm.Fields.Add(fldLoanTypeComboBox);
ip.Y += dY;

// Loan Term (in years) Text field:
g.DrawString("Loan Term (in years):", tf, ip);
var fldLoanTermText = new TextField();
fldLoanTermText.Widget.Page = page;
fldLoanTermText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldLoanTermText.Widget.DefaultAppearance.Font = tf.Font;
fldLoanTermText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldLoanTermText);
ip.Y += dY;

//Annual Income Text field:
g.DrawString("Annual Income:", tf, ip);
var fldAnnualIncomeText = new TextField();
fldAnnualIncomeText.Widget.Page = page;
fldAnnualIncomeText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldAnnualIncomeText.Widget.DefaultAppearance.Font = tf.Font;
fldAnnualIncomeText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldAnnualIncomeText);
ip.Y += dY;

//Monthly Expenses Text field:
g.DrawString("Monthly Expenses:", tf, ip);
var fldMonthlyExpensesText = new TextField();
fldMonthlyExpensesText.Widget.Page = page;
fldMonthlyExpensesText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldMonthlyExpensesText.Widget.DefaultAppearance.Font = tf.Font;
fldMonthlyExpensesText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldMonthlyExpensesText);
ip.Y += dY;

//Credit Score Text field:
g.DrawString("Credit Score Text field:", tf, ip);
var fldCreditScoreText = new TextField();
fldCreditScoreText.Widget.Page = page;
fldCreditScoreText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldCreditScoreText.Widget.DefaultAppearance.Font = tf.Font;
fldCreditScoreText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldCreditScoreText);
ip.Y += dY;

//Existing Loans or Debts Text field:
g.DrawString("Existing Loans or Debts:", tf, ip);
var fldDebtsText = new TextField();
fldDebtsText.Widget.Page = page;
fldDebtsText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldDebtsText.Widget.DefaultAppearance.Font = tf.Font;
fldDebtsText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldDebtsText);
ip.Y += dY;

//Co-Signer Text field:
g.DrawString("Co-Signer:", tf, ip);
var fldCoSignerText = new TextField();
fldCoSignerText.Widget.Page = page;
fldCoSignerText.Widget.Rect = new RectangleF(ip.X + fldOffset, ip.Y, 72 * 3, fldHeight);
fldCoSignerText.Widget.DefaultAppearance.Font = tf.Font;
fldCoSignerText.Widget.DefaultAppearance.FontSize = tf.FontSize;
doc.AcroForm.Fields.Add(fldCoSignerText);
ip.Y += dY;

When saved to a PDF file, the form appears as shown below:

Pdf form

Populate PDF with User Information

Now that we have the form and the user details, it’s time to populate the PDF with the provided data. By programmatically filling in the values, we can ensure that the user's information is accurately captured in the form. This allows us to store the user's data for future reference and generate a completed form copy to be shared with the customer for their records.

Below, we’ll map the user inputs to the corresponding fields in the PDF using the following C# code:

  fldFullNameText.Value = fullName;
  fldDOBText.Value = dob.ToShortDateString();
  fldAddressText.Value = address;
  fldEmailText.Value = email;
  fldPhoneNumberText.Value = phoneNumber;
  fldEmploymentStatusComboBox.Text = employmentStatus;
  fldJobTitleText.Value = jobTitle;
  fldEmployerNameText.Value = employerName;
  fldYearsOfEmploymentText.Value = employmentYears.ToString();
  fldLoanAmountText.Value = loanAmount.ToString();
  fldLoanTypeComboBox.Text = loanType;
  fldLoanTermText.Value = loanTerm.ToString();
  fldAnnualIncomeText.Value = annualIncome.ToString();
  fldMonthlyExpensesText.Value = monthlyExpenses.ToString();
  fldCreditScoreText.Value = creditScore.ToString();
  fldDebtsText.Value = existingLoans.ToString();
  fldCoSignerText.Value = coSigner;

Flatten and Save the Completed PDF

As the form is filled with user information, the next important step is to flatten the PDF. This converts all interactive form fields into a static, non-editable format. Flattening ensures that the form fields are locked and cannot be edited further to become a permanent part of the document. After flattening, we can save the finalized PDF, readying it to be shared with the customer or stored securely for future reference.

We will use the code below to flatten the document and download the copy on the user's device:

  //Flattening the Pdf
  var flatDoc = new GcPdfDocument();
  foreach (var srcPage in doc.Pages)
  {
      var flatSDocPage = flatDoc.Pages.Add();
      var fxo = new FormXObject(flatDoc, srcPage);
      flatSDocPage.Graphics.DrawForm(fxo, flatSDocPage.Bounds, null, ImageAlign.Default);
      // This method draws all annotations on the page including form field widgets:
      srcPage.DrawAnnotations(flatSDocPage.Graphics, flatSDocPage.Bounds);
  }

  //Download the Pdf
  MemoryStream ms = new MemoryStream();
  flatDoc.Save(ms);
  byte[] byteArray = ms.ToArray();
  return File(byteArray, "application/pdf", "LoanApplication.pdf");

Use this sample to implement the scenario described above. See it in action below:

Loan application

Ready to try it out? Download Document Solutions for PDF Today!

Conclusion

In this blog, we explored how to create a digital loan request form using the DsPdf API. These forms can be customized for different business needs, making them a flexible and valuable tool for businesses aiming to enhance their form management. Explore our demos to learn more about PDF forms.

If you have any questions, feel free to ask in the comments below!

More References:

comments powered by Disqus