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.
| Input | A folder of electoral roll PDFs (subfolders included) |
| Output | Voter records in SQL Server, plus an optional Excel file per PDF |
| How it reads the PDFs | The 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. |
| Scope | English rolls only. This is the console edition of the earlier WPF extractor, and the Telugu and Google Vision code paths were removed. |
| Executable | PdfExtractor_Console.exe (root namespace PdfExtractor) |
What one run does, in brief:
- Reads the PDF's header page for constituency, district, state, booth, and revision details.
- Reads every voter page and extracts each voter card: serial number, EPIC ID, name, relation, house number, age, gender, photo status, and voter status.
- Flags fields that look wrong so a human can review them.
- 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
| Area | Technology | Version |
|---|---|---|
| Language / runtime | C# 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 |
| OCR | AWS Textract, synchronous DetectDocumentText API (AWSSDK.Textract, AWSSDK.Core) | Textract 4.0.4.5, Core 4.0.8.1 |
| PDF → image | Ghostscript (gswin64c.exe, installed separately), 300 DPI PNG | Developed against 10.06.0 |
| PDF splitting | PDFsharp | 6.2.4 |
| Database | SQL Server via System.Data.SqlClient | 4.9.1 |
| Excel output | ClosedXML | 0.105.0 |
| JSON | Newtonsoft.Json | 13.0.4 |
| Configuration | System.Configuration.ConfigurationManager (reads App.config) | 10.0.8 |
| Build | Visual Studio (2019 or later) or the .NET SDK | – |
3. Solution Structure
| File / class | Responsibility |
|---|---|
Program | Startup checks, folder-prompt loop, per-PDF orchestration, builds the DB import table |
GhostscriptLocator | Finds gswin64c.exe once at startup |
PdfHelper | Splits a PDF into single-page files named page_1.pdf, page_2.pdf, ... |
VoterProcessingService | Runs Ghostscript and Textract, processes pages in parallel, applies header metadata to records |
MetadataParser | Validates and reads the header page (Section 9) |
GridMapper | Divides a voter page into a 3 × 10 grid and assigns OCR lines to cells (Section 8) |
VoterParser | Converts one cell's text into a voter record and validates it (Section 10) |
AwsConfig | Builds the Textract client from App.config |
ExtractionDatabaseService | Connects to SQL Server and performs the bulk import |
ExcelHelper | Writes the optional Excel file |
Logger | Application logging |
Legacy code you may notice, which is not part of the current flow:
AwsConfig.EnsureKeysRegistered()is intentionally empty and kept only for compatibility withProgram.cs.RegistryHelper(stores DPAPI-encrypted keys underHKCU\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>
| Setting | Meaning |
|---|---|
VoterDb | SQL Server connection string. It points to the VotersDataHub database, the same voter database used by the WPF app (VDMS) and PollManager. |
AWSAccessKey / AWSSecretKey | Credentials 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. |
region | AWS region for Textract. Defaults to us-east-1 if the key is missing. |
GhostscriptExePath | Optional 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 putAWSAccessKeyandAWSSecretKeyinsecrets.config. Keys in the external file override the same keys inApp.config. The same technique (configSource) works forconnectionStrings.
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:
App.configkeyGhostscriptExePath- The
PATHenvironment variable - The Windows Registry (
HKLM\SOFTWARE\Artifex\GPL Ghostscript\<version>), highest version first - A scan of
Program Files\gs\andProgram 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
- Sign in to the AWS Console and open IAM.
- Policies → Create policy → JSON tab. Replace the default content with:
json
{
"Version": "2012-10-17",
"Statement": [
{
"Sid": "AllowOnlyDetectDocumentText",
"Effect": "Allow",
"Action": "textract:DetectDocumentText",
"Resource": "*"
}
]
}
- Next. Name it
PdfExtractor-TextractDetectDocumentTextOnlyand add a description such as "Allows only synchronous Textract DetectDocumentText for the PDF Extractor app." - 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
- IAM → Users → Create user.
- User name:
pdfextractor-textract-user. - Leave "Provide user access to the AWS Management Console" unticked. This user is for programmatic access only.
- Next → Attach policies directly, then search for and tick
PdfExtractor-TextractDetectDocumentTextOnly. It must be the only policy selected. - Next → Create user.
Step 3: Create the access key and secret key
- IAM → Users →
pdfextractor-textract-user→ Security credentials tab. - Access keys → Create access key.
- Use case: Application running outside AWS. Tick the confirmation box and click Next.
- (Optional) add a description tag, e.g.
PdfExtractor console – <developer name>. - Create access key. You now see:
- Access key ID
- Secret access key, shown only once
- 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.DetectDocumentTextshould be allowed.AnalyzeDocumentshould be denied. An unrelated action such ass3:ListAllMyBucketsshould 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
yto 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
*.pdffiles 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)
- Split. PDFsharp writes one PDF per page. The page number in the file name (
page_7.pdf) becomes the record'sPageNumber. - 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. - 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 earlierMagick.NETpath 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).
- Rasterize. Ghostscript runs with
- 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. - Apply header fields to every record: constituency, district, state, booth number and name, revision year and type.
- 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:
- Collect the
Leftvalue of every line. - Run 1-D k-means clustering with k = 3 to find the three column centres.
- Each column boundary is the midpoint between two neighbouring centres.
- Each line is assigned to the column its
Leftfalls 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:
- The text lines are joined with a vertical bar separator.
- If the first line is only a status letter (
E,S,R,M,D,Q, optionally with digits), aTEXTS=<letter>prefix is added. - Stray
#and separator artefacts around serial numbers are cleaned. - The EPIC is the first EPIC in the cell, or
N/Aif none. - A second, independent read of the house number is taken from the cell, for the cross-check in Section 10.2.
- 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:
- Inline: label and value in the same OCR block (
District : NTR). - 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.
- 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 field | Source on the page | Saved 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 |
| State | Title line ELECTORAL ROLL <year> S<code> <State>, taking the text after the code | Yes |
| Booth number and name | "No. and Name of Polling Station", e.g. 7 - Gandrai, split into number 7 and name Gandrai | Yes |
| Constituency number, qualifying date, publication date, town/village, post office, police station, tehsil, subdivision, pin code, polling station address and type | Matching labels | No. 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.
| Field | How it is found |
|---|---|
| Serial number | First 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 status | The 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). |
| Name | Text 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 name | Keyword 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 number | Text 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. |
| Age | The number after Age |
| Gender | Male, Female, or Third Gender after Gender |
| Photo status | Available if the word "Photo" appears in the cell, otherwise Missing |
| EPIC ID | Taken 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.
| Field | Flagged when |
|---|---|
| Name, relationship name | Contains characters other than letters, space, ., ,, or has fewer than 3 letters |
| Relationship type | Missing or N/A |
| House number | Missing, or contains words from the voter's or relative's name |
| Age | Not a number, or outside 18–120 |
| Gender | Anything other than Male or Female |
| EPIC | First 3 characters contain a digit, shorter than 10 characters, or not alphanumeric |
| Status | Anything 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), plusLowConfidenceWordsandLowConfidenceFieldWords(JSON columns that the parsing code described here does not fill). - Reserved for later use, not set by the extractor:
MobileNumberand 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
| Tag | Meaning |
|---|---|
[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] ... FAILED | A 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
| Symptom | Likely 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 Textract | Wrong keys or region, or the IAM policy does not allow textract:DetectDocumentText (Section 6). |
| Signature or authentication errors from AWS | Check the keys were pasted completely. The app trims spaces and newlines, but a truncated key still fails. |
Textract InvalidParameterException | The log prints imageBytes. The synchronous API accepts images up to 10 MB, so check the page's PNG size. |
| Throttling errors | Too 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 contains | Possible 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 page | Column 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
CellErrorsafter every import. - Records with an unreadable serial are dropped.
IsSerialBrokenis set when the serial is0, butProcessPdfthen 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 inVoterParserand 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** inCellErrors, 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.configmust never be committed (Section 4).