Skip to main content

VDMS – English Extraction (Template 2025+)

PDF Extractor (Console): Extracting Voter Data from ECI Electoral Roll PDFs​

1. Overview​

PDF Extractor is a Windows console application that turns ECI English Electoral Roll PDFs into structured voter records.

InputA folder of electoral roll PDFs (subfolders included)
OutputVoter records in SQL Server, plus an optional Excel file per PDF
How it reads the PDFsThe PDFs are scanned images, so pages are converted to images and read with AWS Textract OCR. The position of each text line on the page then decides which voter card it belongs to.
ScopeEnglish rolls only. This is the console edition of the earlier WPF extractor, and the Telugu and Google Vision code paths were removed.
ExecutablePdfExtractor_Console.exe (root namespace PdfExtractor)

What one run does, in brief:

  1. Reads the PDF's header page for constituency, district, state, booth, and revision details.
  2. Reads every voter page and extracts each voter card: serial number, EPIC ID, name, relation, house number, age, gender, photo status, and voter status.
  3. Flags fields that look wrong so a human can review them.
  4. Saves the records to the database and, if requested, to Excel.

The most important part to understand is how a page is divided into a grid (Section 8), because everything else depends on it.


2. Technology Stack​

AreaTechnologyVersion
Language / runtimeC# on .NET Framework 4.8 (net48, SDK-style project, LangVersion latest, nullable disabled). It is Windows-only because it uses the Registry and gswin64c.exe.4.8
OCRAWS Textract, synchronous DetectDocumentText API (AWSSDK.Textract, AWSSDK.Core)Textract 4.0.4.5, Core 4.0.8.1
PDF → imageGhostscript (gswin64c.exe, installed separately), 300 DPI PNGDeveloped against 10.06.0
PDF splittingPDFsharp6.2.4
DatabaseSQL Server via System.Data.SqlClient4.9.1
Excel outputClosedXML0.105.0
JSONNewtonsoft.Json13.0.4
ConfigurationSystem.Configuration.ConfigurationManager (reads App.config)10.0.8
BuildVisual Studio (2019 or later) or the .NET SDK–

3. Solution Structure​

File / classResponsibility
ProgramStartup checks, folder-prompt loop, per-PDF orchestration, builds the DB import table
GhostscriptLocatorFinds gswin64c.exe once at startup
PdfHelperSplits a PDF into single-page files named page_1.pdf, page_2.pdf, ...
VoterProcessingServiceRuns Ghostscript and Textract, processes pages in parallel, applies header metadata to records
MetadataParserValidates and reads the header page (Section 9)
GridMapperDivides a voter page into a 3 × 10 grid and assigns OCR lines to cells (Section 8)
VoterParserConverts one cell's text into a voter record and validates it (Section 10)
AwsConfigBuilds the Textract client from App.config
ExtractionDatabaseServiceConnects to SQL Server and performs the bulk import
ExcelHelperWrites the optional Excel file
LoggerApplication logging

Legacy code you may notice, which is not part of the current flow:

  • AwsConfig.EnsureKeysRegistered() is intentionally empty and kept only for compatibility with Program.cs.
  • RegistryHelper (stores DPAPI-encrypted keys under HKCU\Software\VDMS) comes from the WPF app and is not called by the console app.

4. Configuration (App.config)​

All settings live in App.config, next to the executable.

xml

<connectionStrings>
<add name="VoterDb"
connectionString="Data Source=<server>,<port>;Initial Catalog=VotersDataHub;User ID=<sql-user>;Password=<sql-password>;Encrypt=True;TrustServerCertificate=True;"
providerName="System.Data.SqlClient" />
</connectionStrings>

<appSettings>
<add key="AWSAccessKey" value="<access-key-id>" />
<add key="AWSSecretKey" value="<secret-access-key>" />
<add key="region" value="us-east-1" />
<!-- Optional: pin a specific Ghostscript install instead of auto-detect -->
<add key="GhostscriptExePath" value="C:\Program Files\gs\gs10.06.0\bin\gswin64c.exe" />
</appSettings>
SettingMeaning
VoterDbSQL Server connection string. It points to the VotersDataHub database, the same voter database used by the WPF app (VDMS) and PollManager.
AWSAccessKey / AWSSecretKeyCredentials of the restricted Textract IAM user (Section 6). Leading and trailing spaces or newlines are trimmed automatically, because a stray space breaks AWS request signing.
regionAWS region for Textract. Defaults to us-east-1 if the key is missing.
GhostscriptExePathOptional override (Section 5.2)

Security rule: never commit real keys or passwords. Commit placeholders only.
Recommended: keep the secrets in a Git-ignored file and merge them in. For example, use <appSettings file="secrets.config"> and put AWSAccessKey and AWSSecretKey in secrets.config. Keys in the external file override the same keys in App.config. The same technique (configSource) works for connectionStrings.


5. Prerequisites​

5.1 Checklist​

  • Windows with .NET Framework 4.8. It is included in current Windows 10/11, otherwise install it.
  • Ghostscript, 64-bit (Section 5.2).
  • AWS keys for the restricted Textract user (Section 6).
  • Network access to the SQL Server instance and to AWS.

5.2 Ghostscript discovery​

GhostscriptLocator checks these in order and uses the first match, then caches the result:

  1. App.config key GhostscriptExePath
  2. The PATH environment variable
  3. The Windows Registry (HKLM\SOFTWARE\Artifex\GPL Ghostscript\<version>), highest version first
  4. A scan of Program Files\gs\ and Program Files (x86)\gs\

If nothing is found, the app stops at startup with instructions.


6. AWS Setup: an IAM User Limited to DetectDocumentText​

Goal: the application gets its own AWS identity that can call exactly one API, textract:DetectDocumentText (synchronous text detection). It cannot use any other Textract feature (such as AnalyzeDocument or async jobs), and it cannot use any other AWS service. If the keys leak, the damage is limited to OCR calls.

Do not attach the managed policy AmazonTextractFullAccess. It is far broader than needed.

Step 1: Create the custom policy​

  1. Sign in to the AWS Console and open IAM.
  2. Policies → Create policy → JSON tab. Replace the default content with:

json

{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowOnlyDetectDocumentText",
"Effect": "Allow",
"Action": "textract:DetectDocumentText",
"Resource": "*"
}
]
}
  1. Next. Name it PdfExtractor-TextractDetectDocumentTextOnly and add a description such as "Allows only synchronous Textract DetectDocumentText for the PDF Extractor app."
  2. Create policy.

Why this is enough: IAM denies everything that is not explicitly allowed. Resource must be "*" because Textract does not support resource-level restrictions for this action.

Optional hardening: add this second statement to the same Statement array. It explicitly denies every other action, so a policy attached to this user by mistake later cannot widen its access.

json

{
"Sid": "DenyEverythingElse",
"Effect": "Deny",
"NotAction": "textract:DetectDocumentText",
"Resource": "*"
}

Step 2: Create the IAM user​

  1. IAM → Users → Create user.
  2. User name: pdfextractor-textract-user.
  3. Leave "Provide user access to the AWS Management Console" unticked. This user is for programmatic access only.
  4. Next → Attach policies directly, then search for and tick PdfExtractor-TextractDetectDocumentTextOnly. It must be the only policy selected.
  5. Next → Create user.

Step 3: Create the access key and secret key​

  1. IAM → Users → pdfextractor-textract-user → Security credentials tab.
  2. Access keys → Create access key.
  3. Use case: Application running outside AWS. Tick the confirmation box and click Next.
  4. (Optional) add a description tag, e.g. PdfExtractor console – <developer name>.
  5. Create access key. You now see:
    • Access key ID
    • Secret access key, shown only once
  6. Click Download .csv file (or copy both into your password manager). If the secret is lost, create a new key and delete the old one.

Step 4: Put the keys in the application​

Paste the two values into the AWSAccessKey and AWSSecretKey settings (Section 4). The region setting is us-east-1. IAM users are global, so the same user works in any region, but the region you pick must offer Textract. Changing the region only requires editing region.

Step 5: Verify the restriction​

  • IAM Policy Simulator (policysim.aws.amazon.com): select the user and service Textract. DetectDocumentText should be allowed. AnalyzeDocument should be denied. An unrelated action such as s3:ListAllMyBuckets should also be denied.
  • Or run the app on one PDF. A permissions problem appears immediately as AccessDeniedException.

Key handling rules​

  • Never commit keys to Git, paste them into Confluence or chat, or email them.
  • Give each developer or machine its own key. A user can hold two active keys, which also enables rotation.
  • To rotate: create the new key, update the config, verify, then Deactivate and Delete the old key.
  • If a key is exposed, deactivate and delete it immediately.
  • Cost: Textract bills per page, and the app sends every page of each PDF (header, voter, summary, and map pages) because it must read a page to know it should be skipped. Set an AWS Budget alert so a bad run is noticed.

7. Running the Application​

PdfExtractor_Console.exe "C:\path\to\pdf\folder" (database only)
PdfExtractor_Console.exe "C:\path\to\pdf\folder" y (database + Excel per PDF)
  • With no arguments, the app prompts for the folder path. You can type a trailing y to request Excel, e.g. F:\02 test y.
  • Startup checks: Ghostscript found, Textract client created, database connection tested. If any fails, the app prints why and exits.
  • All *.pdf files in the folder and its subfolders are processed one after another. An error in one PDF is logged and does not stop the others.
  • After each folder the app prompts for the next one. Ctrl+C exits.
  • The console shows per-page progress, timing, and for each PDF the DB result: ImportId, Inserted, Updated, Skipped, Errors, and PDF time.
  • Excel files are named after the PDF (abc.pdf → abc.xlsx) and saved in the folder path you entered.
  • Working files go to %TEMP%\pdfextractor_<guid> and are deleted after each PDF.

8. Processing Pipeline and the Page Grid​

8.1 Pipeline​

PDF
| PdfHelper.SplitPdf -> page_1.pdf, page_2.pdf, ... page_N.pdf
|
+-- page_1 (header) -> Ghostscript PNG -> Textract -> MetadataParser -> header fields
|
+-- page_2..N -> Ghostscript PNG (300 DPI) -> Textract OCR
-> skip if non-voter page
-> GridMapper (3 x 10 grid) -> VoterParser -> voter records
|
v
merge all pages -> drop unusable records -> sort -> add header fields
-> SQL Server import (+ Excel if requested)
  1. Split. PDFsharp writes one PDF per page. The page number in the file name (page_7.pdf) becomes the record's PageNumber.
  2. Header page. Page 1 is checked and read by MetadataParser (Section 9). If it does not look like an English Electoral Roll, the PDF is rejected with "Please upload the correct format PDF" and skipped.
  3. Voter pages. Pages 2 to N are processed in parallel, at most 12 at a time (threadPoolSize). For each page:
    • Rasterize. Ghostscript runs with -sDEVICE=png16m -r300, producing a 300 DPI PNG. This takes about 4 s per page. The earlier Magick.NET path took 25–30 s per page, which is why it was replaced.
    • OCR. The PNG bytes go to Textract DetectDocumentText, which returns text lines, each with a position on the page.
    • Skip non-voter pages (8.2).
    • Read the section name (8.3).
    • Map to the grid and parse (8.4 onward, then Section 10).
  4. Clean up. All pages are merged. Records with no serial number, or with no name (or name N/A), are dropped. The rest are sorted by page and serial number.
  5. Apply header fields to every record: constituency, district, state, booth number and name, revision year and type.
  6. Save to the database, then write Excel if requested.

A page that fails (rasterize or Textract error) is logged and skipped, and the remaining pages continue.

8.2 Non-voter pages​

A page is skipped if its text contains any of: summary of electors, roll type, roll identification, number of electors, net elector, mother roll, list of deletions, modifications, nazri naksha, google map view, cad view, key map (case-insensitive).

8.3 Section name​

Each voter page prints "Section No and Name". It is stored on every record from that page. Textract sometimes splits one printed line into fragments (for example E and ast side building). To rebuild the line, the code groups text lines into one visual row when their vertical extents overlap by at least 40%, then joins them left to right.

8.4 Page layout​

Each voter page is a grid of voter cards, 3 columns × 10 rows, so up to 30 voters per page. Each card holds the serial number, EPIC ID, name, relation, house number, age, and gender.\

+--------------------------------------------------------------+
| HEADER (top 3% of page height) -> ignored |
+------------------+------------------+------------------------+
| Col 0 / Row 0 | Col 1 / Row 0 | Col 2 / Row 0 |
+------------------+------------------+------------------------+
| Col 0 / Row 1 | Col 1 / Row 1 | Col 2 / Row 1 |
+------------------+------------------+------------------------+
| ... | ... | ... |
+------------------+------------------+------------------------+
| Col 0 / Row 9 | Col 1 / Row 9 | Col 2 / Row 9 |
+------------------+------------------+------------------------+
| FOOTER (bottom 4%) -> ignored |
+--------------------------------------------------------------+

8.5 What Textract returns​

Each LINE has its text and a bounding box (Left, Top, Width, Height) expressed as fractions of the page (0.0 to 1.0). The grid logic uses only Left (which column) and Top (which row). Each line lands in exactly one cell.

8.6 Rows: fixed​

  • The grid starts at 3% of the page height and covers 93%, so it ends at 96%. Lines outside that band are header or footer and are discarded.
  • That band is split into 10 equal rows: row = floor((Top − 0.03) / 0.093), limited to 0–9.
  • The code uses a page height of 3508, which is A4 at 300 DPI. It cancels out mathematically, so the rows are effectively percentage-based.

8.7 Columns: detected on every page​

Columns are not fixed at thirds, because different states' PDF templates place their columns differently. On one template, column 3's text starts left of the 66.7% line, so fixed thirds merged two voters into one cell. Instead, for each page:

  1. Collect the Left value of every line.
  2. Run 1-D k-means clustering with k = 3 to find the three column centres.
  3. Each column boundary is the midpoint between two neighbouring centres.
  4. Each line is assigned to the column its Left falls in.

Why k-means instead of "the biggest gaps": inside one card, the name sits at the left edge but the EPIC ID sits far to the right. That internal spread can be larger than the real gap between two cards, so a gap-based method mistakes it for a column boundary and pushes the EPIC into the wrong voter.

Two separate sets of boundaries. Free text starts near the left of each card (about 0.03 / 0.35 / 0.67 of the page width). EPIC IDs sit further right (about 0.26 / 0.58 / 0.90). Using one shared set misplaced one or the other, so:

  • Text boundaries come from the non-EPIC lines and place the text.
  • EPIC boundaries come from the EPIC lines only and place the EPIC IDs.

Fallback to plain thirds (0.333 / 0.667): used when a page has fewer than 9 points or the horizontal spread is under 0.05. This happens on sparse last pages.

8.8 Recognising an EPIC ID​

A line is an EPIC ID if it matches 2–4 capital letters followed by 6–8 digits (for example ABC1234567). EPIC lines go into the cell's EPIC list, and every other line goes into the cell's text list.

8.9 Collision repair​

If a boundary is slightly off, one cell can hold two EPIC IDs while its neighbour holds none. RepairMisassignedEpics handles this:

  • 2 or more EPICs in a cell, and exactly one empty neighbour in the same row: the last EPIC moves to that neighbour. The log shows [GRID-COLLISION-REPAIRED].
  • Anything more ambiguous: nothing changes and the log shows [GRID-COLLISION-UNRESOLVED]. Review these pages manually.

8.10 Preparing a cell for parsing​

For each non-empty cell:

  1. The text lines are joined with a vertical bar separator.
  2. If the first line is only a status letter (E, S, R, M, D, Q, optionally with digits), a TEXTS=<letter> prefix is added.
  3. Stray # and separator artefacts around serial numbers are cleaned.
  4. The EPIC is the first EPIC in the cell, or N/A if none.
  5. A second, independent read of the house number is taken from the cell, for the cross-check in Section 10.2.
  6. The result goes to VoterParser.Parse(...).

9. Header Metadata (Page 1)​

Format check. Page 1 must contain all of these phrases (case-insensitive), or the PDF is rejected as the wrong format: ELECTORAL ROLL, ASSEMBLY CONSTITUENCY, POLLING STATION.

How values are found. The header page is a form of "label : value" pairs. MetadataParser groups the OCR lines into printed rows (40% vertical overlap, the same idea as 8.3) and looks for each label. It tries, in order:

  1. Inline: label and value in the same OCR block (District : NTR).
  2. Beside it: the nearest block to the right on the same row, within 0.35 of the page width. Scanning stops at another known label, so text from a neighbouring column is not picked up.
  3. Nearby lines: among the next 6 lines, a block level with the label to its right, or directly beneath it.

Polling station name and address are printed below their labels, so they are read from the lines underneath (the address joins up to two lines). Scanning stops at section boundaries such as numbered headings, "Number of Electors", or "Signature of Electoral". If a core field cannot be read, the log names the candidate label lines to help debugging.

Extracted fieldSource on the pageSaved on each voter?
Year of revision"Year of Revision"Yes
Type of revision"Type of revision"Yes
Constituency name"Assembly Constituency". The leading number (123 -) and trailing reservation tag such as (SC) are stripped.Yes
District"District"Yes
StateTitle line ELECTORAL ROLL <year> S<code> <State>, taking the text after the codeYes
Booth number and name"No. and Name of Polling Station", e.g. 7 - Gandrai, split into number 7 and name GandraiYes
Constituency number, qualifying date, publication date, town/village, post office, police station, tehsil, subdivision, pin code, polling station address and typeMatching labelsNo. They are logged as [META] only.

10. Voter Field Identification​

VoterParser receives one cell and finds each field with a label-based regular expression. It looks for the printed labels ("Name", "Father's Name", "House Number", "Age", "Gender") and reads what follows, so it does not depend on line order. Before parsing it makes a cleaned copy of the text (vertical bars, "Photo", "Available", extra spaces, and the age and gender segments removed) and keeps the raw text for fields that need it.

FieldHow it is found
Serial numberFirst choice: a status letter followed by a 3–4 digit number (e.g. S 0123), taking the number. Otherwise the number at the start of a line, allowing a leading #. Last resort: a number between two vertical bars. If none is found, the serial is 0 and the record is marked IsSerialBroken.
Voter statusThe status letter next to the serial: E Expired, S Shifted/Change of Residence, R Duplicate, D Deleted, M Missing, Q Disqualified. No letter means Valid. A secondary fallback reads the letter from the TEXTS= prefix (8.10).
NameText after Name up to the next relation keyword (Father / Husband / Mother / Other). If that fails or gives 2 characters or fewer, a looser pattern is tried.
Relationship type and nameKeyword Father, Husband, Mother, or Other(s). Common OCR misspellings such as "Husbande" are tolerated. The name runs up to House Number, H.NO, D.NO, Door No, Age, Gender, or Photo. Stored as Father / Husband / Mother / Others.
House numberText after House Number / House No up to Age, Gender, or Photo. If the voter's or relative's name spilled next to the label, it is removed first. = becomes -. If nothing is found, the first number-like token is used, otherwise N/A.
AgeThe number after Age
GenderMale, Female, or Third Gender after Gender
Photo statusAvailable if the word "Photo" appears in the cell, otherwise Missing
EPIC IDTaken from the grid stage (8.8), not from the parser

10.1 Data-quality flags (CellErrors)​

After parsing, each record is validated. Every problem is added to a per-field CellErrors dictionary and logged as [CELL-ERROR]. A flag does not remove the record. It tells a human where to look. The flags are saved to the database as JSON in CellErrorsRaw.

FieldFlagged when
Name, relationship nameContains characters other than letters, space, ., ,, or has fewer than 3 letters
Relationship typeMissing or N/A
House numberMissing, or contains words from the voter's or relative's name
AgeNot a number, or outside 18–120
GenderAnything other than Male or Female
EPICFirst 3 characters contain a digit, shorter than 10 characters, or not alphanumeric
StatusAnything other than Valid. This is informational, e.g. "Voter marked as Deleted".

10.2 House-number cross-check​

The parser's house number is compared with the independent read from 8.10. A mismatch is flagged as [HOUSE-CELL-ERROR] when the parser's value is truncated, cut mid-word, missing address components, or contains name words that leaked in.


11. Output​

11.1 Database​

All voters of one PDF are sent as one import batch (StartAndImportAsync) tagged with the PDF file name, and the console prints ImportId, Inserted, Updated, Skipped, and Errors. The import user id is currently hard-coded to 1 (superadmin) until authentication is added.

Each row contains:

  • Voter: EPIC ID, serial number, name, relationship type and name, house number, age, gender, photo status, voter status.
  • From the header: booth number and name, constituency name, district, state, revision year and type, and the section text.
  • Traceability: PageNumber, GridRow, GridCol, SerialSource, IsSerialBroken, RawSerialText, IsEpicBroken, RawEpicText.
  • Quality: CellErrorsRaw (JSON of the flags in 10.1), plus LowConfidenceWords and LowConfidenceFieldWords (JSON columns that the parsing code described here does not fill).
  • Reserved for later use, not set by the extractor: MobileNumber and the sentiment flags (Favour, Opposition, Neutral, Undecided, Others).

11.2 Excel (optional, when y is passed)​

One workbook per PDF with a single sheet named Voters and these columns:
BoothNumber, BoothName, YearOfRevision, Section, SerialNo, EpicId, Name, RelationshipType, RelationshipName, HouseNumber, Age, Gender, Status, ConstituencyName, District, State.
Serial, EPIC, house number, and age are stored as text so Excel does not reformat them.


12. Log Tags​

TagMeaning
[GRID-COLLISION-REPAIRED]An EPIC was moved to an empty neighbour cell automatically
[GRID-COLLISION-UNRESOLVED]Two EPICs in one cell with no clear fix. Verify this page.
[CELL-ERROR] / [HOUSE-CELL-ERROR]A field failed validation (Section 10)
[SKIP]A non-voter page was skipped
[SECTION] / [META]Section name and header fields that were read
[MetadataParser] ... FAILEDA core header field could not be read, with candidate lines
[TIMING PAGE] / [TIMING SUMMARY]Rasterize time versus Textract time per page and per PDF
[RASTERIZE ...] / [TEXTRACT ...]Ghostscript or Textract failure, with error code and request id

13. Troubleshooting​

SymptomLikely cause and action
"Ghostscript initialization failed"Ghostscript is missing or not found. Install it, or set GhostscriptExePath (Section 5.2).
"Could not connect to the database"Check the VoterDb connection string and network access.
AccessDeniedException from TextractWrong keys or region, or the IAM policy does not allow textract:DetectDocumentText (Section 6).
Signature or authentication errors from AWSCheck the keys were pasted completely. The app trims spaces and newlines, but a truncated key still fails.
Textract InvalidParameterExceptionThe log prints imageBytes. The synchronous API accepts images up to 10 MB, so check the page's PNG size.
Throttling errorsToo many concurrent pages for the account's Textract quota. Lower threadPoolSize (12) in VoterProcessingService.
"Not in the expected English Electoral Roll format"Wrong language, or the header page lacks the required phrases (Section 9).
Fewer voters than the PDF containsPossible causes: (a) a card whose serial number could not be read, or whose name is missing or N/A, is dropped before saving. (b) A page that failed is skipped, with only a log entry. Search the log for [CELL-ERROR], [RASTERIZE ...], and [TEXTRACT ...] on the affected pages.
Two voters swapped or merged on a pageColumn detection failed on a sparse or unusual page. Look for [GRID-COLLISION-...].

14. Known Limitations and Issues​

  • English rolls only. The grid is fixed at 3 × 10, and the header and footer bounds (3% and 96%) are fixed. A different template needs changes in GridMapper.
  • Accuracy depends on OCR quality. Review CellErrors after every import.
  • Records with an unreadable serial are dropped. IsSerialBroken is set when the serial is 0, but ProcessPdf then removes every record with a serial of 0 or less, so those rows never reach the database.
  • Two fallback regexes never match. The TEXTS= status fallback in VoterParser and the "Name" fallback pattern contain \\s* inside a verbatim string, which matches a literal backslash instead of whitespace. Only the primary detection paths work.
  • Third Gender** is flagged as an invalid gender** in CellErrors, even though it is read correctly.
  • Non-voter page detection is keyword-based over the whole page text, so an unusual page containing one of those phrases would be skipped.
  • **Secrets in **App.config must never be committed (Section 4).