A document template is set by the Template class. It contains template items - fields, tables and barcodes. Each item has a unique (in the template bounds) name and an optional page index - the value that represents the index of the page where the template item is located; null if the template item is located on any page.
The document is parsed by the template with the parseByTemplate(Template) method of the Parser class. See Working with data extracted by template for details how to read the result.
The code snippets below use the following imports:
The template field is set by the TemplateField class with the following constructor:
newTemplateField(position,name,pageIndex)
Parameter
Description
position
Defines the way how to find the field on a page.
name
A unique template item name.
pageIndex
The page index. An integer value that represents the index of the page where the template item is located; null (or omitted) if the template item is located on any page.
TemplatePosition is an abstract base class. The following classes are used to set template positions:
TemplateFixedPosition. Provides a template field position which is defined by the rectangular area.
TemplateRegexPosition. Provides a template field position which uses the regular expression.
TemplateLinkedPosition. Provides a template field position which uses the linked field.
TemplateFixedPosition
This is the simplest way to define the field position. It requires to set a rectangular area on the page that bounds the field value. All the text that is contained (even partially) in the rectangular area will be extracted as a value:
// Create a fixed template field with "Address" name which is bounded by a rectangle at the position (35, 160) and with the size (110, 20)
consttemplateField=newTemplateField(newTemplateFixedPosition(newRectangle(newPoint(35,160),newSize(110,20))),'Address');
It is recommended to define a rectangular area above (below) the center of the line that is below (above) the selected area, in order to avoid the excessive extraction of the text. For example:
Template definition
Result
Extracts only one line: 67890
Extracts two lines: 4321 First Street, Anytown, State ZIP
Extracts four lines: Company Name, 4321 First Street, Anytown, State ZIP, Date: 06/02/2019
TemplateRegexPosition
This way to define the field position allows to find a field value by a regular expression. For example, if the document contains “Invoice Number INV-3337” then the template field can be defined in the following way:
// Create a regex template field with "InvoiceNumber" name
consttemplateField=newTemplateField(newTemplateRegexPosition('Invoice Number\\s+[A-Z0-9\\-]+'),'InvoiceNumber');
In this case the entire string is extracted as a value. To extract only a part of the string the regular expression group “value” is used:
// Create a regex template field with "InvoiceNumber" name with "value" group
consttemplateField=newTemplateField(newTemplateRegexPosition('Invoice Number\\s+(?<value>[A-Z0-9\\-]+)'),'InvoiceNumber');
In this case “INV-3337” string is extracted as a value.
The regular expression is passed to Java as a string, so backslashes must be escaped in JavaScript string literals ('\\s'), or use String.raw.
Regular expression fields can be used as linked fields.
TemplateLinkedPosition
This way to define the field position allows to find a field value by extracting a rectangular area around the linked field. For example, if it’s known that the field with an invoice number is placed on the right of “Invoice Number” string the following code is used:
// Create a regex template field to find "Invoice Number" text
constinvoice=newTemplateField(newTemplateRegexPosition('Invoice Number'),'Invoice');// Create a related template field associated with "Invoice" field and extract the value on the right of it
constinvoiceNumber=newTemplateField(newTemplateLinkedPosition('Invoice',newSize(100,15),newTemplateLinkedPositionEdges(false,false,true,false)),'InvoiceNumber');
Template definition
Result
Extracts a text on the right of “Invoice Number” field: INV-3337
To simplify the setting of the size of the template field, the autoScale parameter (the fourth parameter of the TemplateLinkedPosition constructor) is used. The size of the template field is scaled according to the related field if autoScale is set to true. This is useful when the font size is not known in advance, but the proportions of the size of the value (the ratio of height to width) are approximately known:
// Create a regex template field to find "Invoice Number" text
constinvoice=newTemplateField(newTemplateRegexPosition('Invoice Number'),'Invoice');// Create a related template field associated with "Invoice" field and extract the value on the right of it
constinvoiceNumber=newTemplateField(newTemplateLinkedPosition('Invoice',newSize(100,15),newTemplateLinkedPositionEdges(false,false,true,false),true),'InvoiceNumber');
Template definition
Result
Extracts a text on the right of “Invoice Number” field. The search area is scaled according to the size of the linked field.
The field value can be extracted from either side of the related field. The side of the value extraction is set by the TemplateLinkedPositionEdges(left, top, right, bottom) object (getEdges()). The size of the rectangular area is set by the getSearchArea() property. The position of the rectangular area depends on the side of the value extraction:
The related field can be any field which was previously defined in the template:
// Create a regex template field
constfromField=newTemplateField(newTemplateRegexPosition('From'),'From',0);// Create a related template field linked to "From" regex field and placed under it
constcompanyField=newTemplateField(newTemplateLinkedPosition('From',newSize(100,10),newTemplateLinkedPositionEdges(false,false,false,true)),'FromCompany',0);// Create a related template field linked to "FromCompany" related field and placed under it
constaddressField=newTemplateField(newTemplateLinkedPosition('FromCompany',newSize(100,30),newTemplateLinkedPositionEdges(false,false,false,true)),'FromAddress',0);
Template definition
Result
The extraction is processed in the following way: extracts data of “From” regex field (green), extracts data of “FromCompany” related field (yellow), extracts data of “FromAddress” related field (red).
A value of the field depends on the related field. The field is always empty if the related field doesn’t have a value. If the field has a value then it has a link to the related field.
Document template with fields
An instance of the Template class is created by the constructor which accepts a Java collection of template items (java.lang.Iterable<TemplateItem>). Use java.util.ArrayList:
// Create a collection of template fields
constfields=newArrayList();fields.add(newTemplateField(newTemplateRegexPosition('From'),'From',0));fields.add(newTemplateField(newTemplateLinkedPosition('From',newSize(100,10),newTemplateLinkedPositionEdges(false,false,false,true)),'FromCompany',0));fields.add(newTemplateField(newTemplateLinkedPosition('FromCompany',newSize(100,30),newTemplateLinkedPositionEdges(false,false,false,true)),'FromAddress',0));// Create a document template
consttemplate=newTemplate(fields);
The field name is case-insensitive (Field and FIELD - the same names) and must be unique in the template. The related field must be associated with an earlier defined field. If these conditions aren’t met, an exception is thrown.
Template tables
A template table is set by the TemplateTable class with the following constructors:
newTemplateTable(layout,name,pageIndex)// layout is TemplateTableLayout
newTemplateTable(parameters,name,pageIndex)// parameters is TemplateTableParameters
A template table can be set by detector parameters or by table layout. If the page index is null, tables are extracted from every document page. It’s useful in the cases when the document contains pages with the same layout (pages differ only by data).
The TemplateTableParameters class has the following constructors:
Each of the parameters is optional (pass null). The easiest way to define a table is to set the rectangular area of the table and column separators. The separators are a Java collection of java.lang.Double values: create the values with java.newDouble, because integral JavaScript numbers are passed to Java as java.lang.Integer:
// Helper which converts a JavaScript array of numbers to a Java list of doubles
functiontoDoubleList(values){constlist=newArrayList();values.forEach((v)=>list.add(java.newDouble(v)));returnlist;}constparameters=newTemplateTableParameters(newRectangle(newPoint(175,350),newSize(400,200)),toDoubleList([185,370,425,485,545]));
If a template table is set by detector parameters, the table is detected automatically:
constparameters=newTemplateTableParameters(newRectangle(newPoint(175,350),newSize(400,200)),toDoubleList([185,370,425,485,545]));consttable=newTemplateTable(parameters,'Details',0);// Create a document template
constitems=newArrayList();items.add(table);consttemplate=newTemplate(items);
A template table is set by table layout if the table can’t be detected automatically:
These collections represent bounds of columns and rows. For example, for a 2x2 table there are 3 vertical and 3 horizontal separators:
---------
| | |
---------
| | |
---------
The moveTo(Point) method is used to move the table layout.
For example, a document has tables on each page (or a set of documents with a table on the page). These tables differ by position and content, but have the same columns and rows. In this case a user can define a TemplateTableLayout object at (0, 0) once and then move it to the location of the definite table.
If the table position depends on another object of the page, a user can define a TemplateTableLayout object based on the template document and then move it according to an anchor object. For example, if this is a summary table and it is followed by a details table (which can contain a different count of rows). In this case a user can define a TemplateTableLayout object on the template document (with the known details table rectangle) and then move the TemplateTableLayout object according to the difference of the details table rectangle of the template and the real document.
The moveTo(Point) method returns a copy of the current object. A user can pass any coordinates (even negative - then the layout will be moved to the left/top):
// Move the layout to the position (100, 100)
constmovedLayout=layout.moveTo(newPoint(100,100));
Template barcodes
Template barcodes work in the same way as a template field with the fixed position. The following example shows how to define a template barcode field and parse the document:
constjava=require('java');constgroupdocs=require('@groupdocs/groupdocs.parser');constArrayList=java.import('java.util.ArrayList');// Define a barcode field
constbarcode=newgroupdocs.TemplateBarcode(newgroupdocs.Rectangle(newgroupdocs.Point(430,50),newgroupdocs.Size(140,140)),'QR');// Create a template
constitems=newArrayList();items.add(barcode);consttemplate=newgroupdocs.Template(items);// Create an instance of Parser class
constparser=newgroupdocs.Parser('Barcodes.pdf');try{// Parse the document by the template
constdata=parser.parseByTemplate(template);// Print all extracted data
for(leti=0;i<data.getCount();i++){constfield=data.get(i);// As we have defined only barcode fields in the template,
// the page area is expected to be PageBarcodeArea
constarea=field.getPageArea();constvalue=java.instanceOf(area,'com.groupdocs.parser.data.PageBarcodeArea')?area.getValue():'Not a template barcode field';console.log(field.getName()+': '+value);}}finally{parser.close();}process.exit(0);
The barcode field has no page index, so the QR codes of both pages of Barcodes.pdf are extracted:
This example shows the template which is used to parse the following invoice:
constjava=require('java');constgroupdocs=require('@groupdocs/groupdocs.parser');const{Parser,Template,TemplateField,TemplateFixedPosition,TemplateRegexPosition,TemplateLinkedPosition,TemplateLinkedPositionEdges,TemplateTable,TemplateTableParameters,Rectangle,Point,Size,}=groupdocs;constArrayList=java.import('java.util.ArrayList');// Create a field with the fixed position
constfixedField=(x,y,width,height,name)=>newTemplateField(newTemplateFixedPosition(newRectangle(newPoint(x,y),newSize(width,height))),name);// Create a field which is placed on the right of the linked field
constrightOf=(linkedName,name)=>newTemplateField(newTemplateLinkedPosition(linkedName,newSize(200,15),newTemplateLinkedPositionEdges(false,false,true,false)),name);// Create detector parameters for "Details" table
constdetailsTableParameters=newTemplateTableParameters(newRectangle(newPoint(35,320),newSize(530,55)),null);// Create detector parameters for "Summary" table
constsummaryTableParameters=newTemplateTableParameters(newRectangle(newPoint(330,385),newSize(220,65)),null);// Create a collection of template items
consttemplateItems=newArrayList();[fixedField(35,135,100,10,'FromCompany'),fixedField(35,150,100,35,'FromAddress'),fixedField(35,190,150,2,'FromEmail'),fixedField(35,250,100,2,'ToCompany'),fixedField(35,260,100,15,'ToAddress'),fixedField(35,290,150,2,'ToEmail'),newTemplateField(newTemplateRegexPosition('Invoice Number'),'InvoiceNumber'),rightOf('InvoiceNumber','InvoiceNumberValue'),newTemplateField(newTemplateRegexPosition('Order Number'),'InvoiceOrder'),rightOf('InvoiceOrder','InvoiceOrderValue'),newTemplateField(newTemplateRegexPosition('Invoice Date'),'InvoiceDate'),rightOf('InvoiceDate','InvoiceDateValue'),newTemplateField(newTemplateRegexPosition('Due Date'),'DueDate'),rightOf('DueDate','DueDateValue'),newTemplateField(newTemplateRegexPosition('Total Due'),'TotalDue'),rightOf('TotalDue','TotalDueValue'),newTemplateTable(detailsTableParameters,'details',null),newTemplateTable(summaryTableParameters,'summary',null),].forEach((item)=>templateItems.add(item));// Create a document template
consttemplate=newTemplate(templateItems);// Parse the invoice by the template
constparser=newParser('invoice.pdf');try{constdata=parser.parseByTemplate(template);for(leti=0;i<data.getCount();i++){constfield=data.get(i);constarea=field.getPageArea();if(java.instanceOf(area,'com.groupdocs.parser.data.PageTextArea')){console.log(field.getName()+': '+area.getText());}elseif(java.instanceOf(area,'com.groupdocs.parser.data.PageTableArea')){console.log(field.getName()+': table '+area.getRowCount()+'x'+area.getColumnCount());}}}finally{parser.close();}process.exit(0);
The beginning of the output for invoice.pdf (the parser returns field names in upper case):
FROMCOMPANY: DEMO - Sliced Invoices
FROMADDRESS: Suite 5A-1204
123 Somewhere Street
Your City AZ 12345
FROMEMAIL: admin@slicedinvoices.com
TOCOMPANY: Test Business
...
INVOICENUMBERVALUE: INV-3337
...
TOTALDUEVALUE: $93.50
DETAILS: table 2x5
SUMMARY: table 3x2
More resources
Free online document parser App
Along with the full-featured library we provide simple but powerful free Apps.
You are welcome to parse documents and extract data from PDF, DOC, DOCX, PPT, PPTX, XLS, XLSX, Emails and more with our Free Online Document Parser App.
Was this page helpful?
Any additional feedback you'd like to share with us?
Please tell us how we can improve this page.
Thank you for your feedback!
We value your opinion. Your feedback will help us improve our documentation.
On this page
Analyzing your prompt, please hold on...
An error occurred while retrieving the results. Please refresh the page and try again.