simple-escp Documentation

Similar documents
CLEARING CHANGES (FONT FEATURES) IN DOD ISSUANCES

Chapter 3 Using Styles and Templates

Layout Manager - Toolbar Reference Guide

HTML TAG SUMMARY HTML REFERENCE 18 TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES TAG/ATTRIBUTE DESCRIPTION PAGE REFERENCES MOST TAGS

Quick Reference Card Business Objects Toolbar Design Mode

Create a new document based on default template, other available template like: memo, fax, agenda.

Word Getting Started The Word Window u vw. Microsoft QUICK Source. Creating a New Blank Document. Creating a New Document from a Template

Chapter 3 Using Styles and Templates

Lesson 19 Organizing and Enhancing Worksheets

Fall 2016 Exam Review 3 Module Test

Chapter 3 Using Styles and Templates

Reference Services Division Presents. Microsoft Word 2

3. What is the smallest and largest font size available in Font Size tool on formatting toolbar? A. 8 and 72 B. 8 and 68 C. 6 and 72 D.

Chapter 1 Getting Started with HTML 5 1. Chapter 2 Introduction to New Elements in HTML 5 21

SPARK. User Manual Ver ITLAQ Technologies

Creating Accessible Microsoft Word 2003 Documents Table of Contents

NOBLE INSTITUTE OF COMPUTER ACCOUNTANCY

Tutorial. Unit: Interactive Forms Integration into Web Dynpro for Java Topic: Dynamically generated forms

The American University in Cairo. Academic Computing Services. Word prepared by. Soumaia Ahmed Al Ayyat

Learning Map Excel 2007

Introducing Gupta Report Builder

Running head: WORD 2007 AND FORMATING APA PAPERS 1. A Brief Guide to using Word 2007 to Format Papers in the Publication Style of the American

Lesson 2 Quick Tour and Features

Chapter 3 Using Styles and Templates

Creating Web Pages with SeaMonkey Composer

Introduction to Microsoft Word 2010

Formatting a Report with Word 2010

Microsoft Excel 2016 / 2013 Basic & Intermediate

Basic Microsoft Word 2013

Setting Up Your Dissertation Format Using MS Word2000. Overview of the Process

Microsoft Excel 2010

OU EDUCATE TRAINING MANUAL

Requirements Document

Table of Contents. Word. Using the mouse wheel 39 Moving the insertion point using the keyboard 40 Resume reading 41

GO! with Microsoft Excel 2016 Comprehensive

Word Tips & Tricks. Status Bar. Add item to Status Bar To add an itme to the status bar, click on the item and a checkmark will display.

AASHTO Materials Standard Template Users Guide

Dataflow Editor User Guide

QRG: Using the WYSIWYG Editor

Zeppelin Website Content Manager User Manual

Word Tutorial 3. Creating a Multiple- Page Report COMPREHENSIVE

TABLE OF CONTENTS. i Excel 2016 Basic

Contents. Launching Word

Excel 2007 Tutorials - Video File Attributes

Bridge Course Information and Communication Technology

Microsoft Office 2010 Tutorial

Word processing software

Advanced Excel. Click Computer if required, then click Browse.

Word Processing. 3.1 Using the Application

Quick Access Toolbar. You click on it to see these options: New, Open, Save, Save As, Print, Prepare, Send, Publish and Close.

Table of Contents Headings:... 2 Changing text to a heading... 2 Modifying Style settings for current and future documents... 2

Excel 2003 Tutorials - Video File Attributes

San Pedro Junior College. WORD PROCESSING (Microsoft Word 2016) Week 4-7

Creating Accessible Word Documents

Microsoft Office Training Skills 2010

Spring Semester Study Guide

Microsoft Office Excel 2013 Courses 24 Hours

WHAT S NEW. Version 3.0

Word for Research Writing I: Text and Structure

ECDL Module 4 REFERENCE MANUAL

Understanding Word Processing

Access 2003 Introduction to Report Design

DYMO ID User Guide BC

Chapter 13 Working with Styles

Enhancing Your Customer Facing Documents (updated 10/03/2017)

CST272 Getting Started Page 1

Access Intermediate

More Skills 11 Format and Position Report Controls

WebIntelligence. Creating Documents

Microsoft Access 2007 Module 1

GO! with Microsoft Access 2016 Comprehensive

Word Training - Maintaining Consistency Supporting Handout Designing Styles within a Word Template Version: Mac

Excel 2010 Tutorials - Video File Attributes

A Guide to Quark Author Web Edition 2015

Formatting documents in Microsoft Word Using a Windows Operating System

The figure below shows the Dreamweaver Interface.

Information System Services

Spreadsheets Microsoft Office Button Ribbon

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University : Advanced Applications of MS-Office

Word Training - Maintaining Consistency Supporting Handout Designing Styles within a Word Template Version: Windows

Microsoft Word Intermediate March 25, Exercise 1: Open Word Click on Word. OR Click Start. Click All Programs. Click Microsoft Office.

Microsoft Excel Keyboard Shortcuts

ST. MARY S COLLEGE FORM 4

Report Writer User s Guide V E R S I O N Copyright 2018 Jade Software Corporation Limited. All rights reserved.

Excel Tutorials - File Size & Duration

EtatRequete.book Page 1 Mardi, 6. avril :01 15 Reports and Queries

EDITOR GUIDE. Button Functions:...2 Inserting Text...4 Inserting Pictures...4 Inserting Tables...8 Inserting Styles...9

Getting Started Guide. Chapter 3 Using Styles and Templates

NiceForm User Guide. English Edition. Rev Euro Plus d.o.o. & Niceware International LLC All rights reserved.

MICROSOFT WORD 2010 BASICS

Word Select New in the left pane. 3. Select Blank document in the Available Templates pane. 4. Click the Create button.

REPORT DESIGNER GUIDE

By Ryan Stevenson. Guidebook #2 HTML

LECTURE 08B: EXPLORING MS OFFICE WORD 2010

Microsoft Excel 2010 Tutorial

Reference Services Division Presents. Microsoft Word 2

In so many ways summary

How to Run Reports in Version 12

Formatting Worksheets

Microsoft Word Chapter 1. Creating, Formatting, and Editing a Word Document with Pictures

Transcription:

Table of Contents 1. Getting Started... 1 2. Template... 6 2.1. Page Format... 6 2.2. Template... 7 2.3. Line... 9 2.4. Table... 9 2.5. List... 12 3. Placeholder... 13 3.1. Basic Placeholder... 13 3.2. Script Placeholder... 14 4. Function... 15 4.1. Numbering Functions... 15 4.2. Styling Functions... 16 4.3. Miscellaneous Functions... 16 4.4. Custom Function... 17 5. Data Source... 18 6. Swing... 18 7. Reference... 21 Download PDF version 1 1. Getting Started simple-escp is a small library for simplyfing ESC/P text-mode printing in Java. Many modern reporting libraries for Java works in graphic mode. While modern dot-matrix and receipt printers can print in graphics mode, printing graphic is slow. It is also cumbersome to print at exact position in graphic mode. Such problems can be avoided by using text mode printing. In text mode printing, printers will print ASCII characters one by one. They will usually use fonts stored inside their RAM and accept control characters for manipulating printing process. 1 http://jockihendry.github.io/simple-escp/simple-escp-doc.pdf 1

ESC/P (Espon Standard Code for Printers) is a printer control language mainly used in dot matrix and receipt printers. ESC/P commands can be used to configure page length, change font styles, and many more configurations. simple-escp supports ESC/ P for 9-pin printers. To use simple-escp in Gradle, add the following lines to build.gradle : build.gradle repositories maven url "http://dl.bintray.com/jockihendry/maven" dependencies compile group: 'jockihendry', name: 'simple-escp', version: '0.5.3' To include simple-escp manually to a Java project, download simple-escp s binary distribution from https://github.com/jockihendry/simple-escp/releases. The first step in using simple-escp is creating a template in JSON format. This template contains page format attributes and placeholders that will be filled later in application. For example, create template.json that has the following content: template.json "pageformat": "pagewidth": 50, "pagelength": 13, "usepagelengthfromprinter": false, "template": "header": [ " ### Company Name Page %PAGE_NO", " ####### ", "######### Invoice No: $invoiceno:10 ", 2

"detail": [ "table": "table_source", "border": true, "columns": [ "source": "code", "width": 9, "caption": "Code", "source": "name", "width": 34, "caption": "Name", "source": "qty", "width": 6, "caption": "Qty", " ", " (Signature) (Signature) " This report s width is 50 characters. Every page consists of 13 lines. Overrides page length settings in printer s ROM so that form feed will work as expected. %PAGE_NO is a function that will be replaced by page number. $invoiceno:10 is a placeholder that will be replaced by value from data source. It will be exactly 10 characters. This will create a table based on a collection. This is used to configure every table s column. The next step is to read the JSON template form Java code, for example: Main.java JsonTemplate template = new JsonTemplate(getClass().getResource("/ template.json").touri(); Template need to be filled with values from one or more data sources (unless it doesn t contains any placeholders). Data source can be stored as Map or JavaBean object. For example, the following code will define a Map data source: Main.java Map<String, Object> map = new HashMap<>(); map.put("invoiceno", "INVC-00001"); List<Map<String, Object>> tables = new ArrayList<>(); 3

for (int i=0; i<5; i++) Map<String, Object> line = new HashMap<>(); line.put("code", String.format("CODE-%d", i)); line.put("name", String.format("Product Random %d", i)); line.put("qty", String.format("%d", i*i)); tables.add(line); map.put("table_source", tables); This value will be used to fill $invoiceno:10. This is used by "table": "table_source". Every items in this collection will represent a line in table. The last step is to fill the template and print the result to printer: Main.java SimpleEscp simpleescp = new SimpleEscp(); simpleescp.print(template.parse(), map); Print directly to default printer. simple-escp has a preview panel that can be used in Swing application to preview the result. For example, the following is a complete code that will read a JSON template, fill it with data and displays the result: MainFrame.java import simple.escp.template; import simple.escp.json.jsontemplate; import javax.swing.jframe; import java.awt.borderlayout; import java.awt.dimension; import java.io.ioexception; import java.net.urisyntaxexception; import java.util.arraylist; import java.util.hashmap; import java.util.list; import java.util.map; public class MainFrameTest extends JFrame public MainFrameTest() throws URISyntaxException, IOException super("preview"); 4

Template template = new JsonTemplate(Thread.currentThread(). getcontextclassloader().getresource("report.json").touri()); Map<String, Object> value = new HashMap<>(); value.put("invoiceno", "INVC-00001"); List<Map<String, Object>> tables = new ArrayList<>(); for (int i=0; i<5; i++) Map<String, Object> line = new HashMap<>(); line.put("code", String.format("CODE-%d", i)); line.put("name", String.format("Product Random %d", i)); line.put("qty", String.format("%d", i*i)); tables.add(line); value.put("table_source", tables); PrintPreviewPane printpreview = new PrintPreviewPane(template, value, null); getcontentpane().setlayout(new BorderLayout()); getcontentpane().add(printpreview, BorderLayout.CENTER); setpreferredsize(new Dimension(500, 500)); pack(); setdefaultcloseoperation(jframe.exit_on_close); setvisible(true); public static void main (String[ args) try new MainFrameTest(); catch (Exception e) e.printstacktrace(); Read the JSON template. Prepare data. Create a preview panel. Add the preview panel to this frame. 5

Figure 1. The Preview Panel 2. Template JSON template consists of 2 keys: pageformat and template. 2.1. Page Format The value of pageformat must be a JSON object. The following keys are available for pageformat : Key Value Type Default Value "autoformfeed" boolean true "autolinefeed" boolean false "bottommargin" number undefined 6

Key Value Type Default Value "characterpitch" number, string "10 cpi" "leftmargin" number undefined "linespacing" string "1/6" "pagelength" number undefined "pagewidth" number undefined "rightmargin" number undefined "typeface" string undefined "usepagelengthfromprinter" boolean true Example: "pageformat": "characterpitch": "5", "linespacing": "1/8", "typeface": "roman" Page format can also be created programmatically, for example: PageFormat pageformat = new PageFormat(); pageformat.setcharacterpitch("5"); pageformat.setlinespacing("1/8"); pageformat.settypeface("roman"); 2.2. Template The value of template can be JSON object or JSON array. If template is a JSON array, every elements of the array is a single line. The first element of the array is the first line, the second element is the second line, and so on. For example, the following template consists of three lines: "template": ["Line #1", "Line #2", "Line #3" 7

The template above can also be create programmatically by using the following code: Report report = new Report(pageFormat, null, null); report.append(new TextLine("Line #1"), false); report.append(new TextLine("Line #2"), false); report.append(new TextLine("Line #3"), false); If template is a JSON object, every members of the object represents a report section. The following keys are available for template : Key "detail" "firstpage" "footer" Description Put the content of the report in this section. This section will be displayed as the first page of the report. This section will be added at the bottom of every page in "detail" section. "lastpagefooter" This section will be added at the bottom of the last page only. "header" "lastpage" This section will be added at the top of every page in "detail" section. This section will be displayed as the last page of the report. All sections must have a JSON array as value. Every elements of the array is a single line in that section. Example: "template": "firstpage": ["First page only.", "header": ["Header line #1", "Header line #2", "detail": [ "First line of detail", "Second line of detail", "footer": ["The footer.", "lastpage": ["Last page only." 8

The template above can also be create programmatically by using the following code: TextLine[ firstpage = new TextLine[ new TextLine("First page only.") ; TextLine[ lastpage = new TextLine[ new TextLine("Last page only.") ; TextLine[ header = new TextLine[ new TextLine("Header line #1"), new TextLine("Header line #2") ; TextLine[ footer = new TextLine[ new TextLine("The footer.") ; Report report = new Report(pageFormat, header, footer); report.appendsinglepage(firstpage, true); report.append(new TextLine("First line of detail"), false); report.append(new TextLine("Second line of detail"), false); report.appendsinglepage(lastpage, true); 2.3. Line template and all sections accept an array that represent lines. The elements inside this array should be a string or JSON object. String will be converted to TextLine. All TextLine may contains placeholders and/or functions. JSON object will be converted to either TableLine or ListLine depending on their keys. detail section allows mixing multiple TextLine, TableLine and ListLine in any position inside the array. 2.4. Table Table is a JSON object that contains table key. The value for table is script placeholder that must be evaluated to Collection. All valid keys for table are: Key Value Type Required Description "border" boolean If true, simple-escp will add CP437 border to this table. Default value is false. "columns" array The columns for this table. "lineseparator" boolean If true, simple-escp will add CP437 line separator for each line in this table. Default value is false. 9

Key Value Type Required Description "underlineseparator" boolean If true, simpe-escp will add underline format to the last line of each row. Default value is false. "table" string A script that should return Collection as the content of this table. Every element in columns array is a JSON object. The valid keys for this JSON object are: Key Value Type Required Description "caption" string The column name. Default value is the same as value of "source". "source" string A script that will be executed for members of Collection to return the value for this column. "width" number Width of this column in number of characters. "wrap" boolean If true, value that exceeds column s width will be advanced to next line. Default value is false. Example of table in JSON template: "pageformat": "pagelength": 10, "template": [ "This is a text line", "table": "persons", "columns": [ "source": "firstname", "width": 10, "wrap": true, "source": "lastname", "width": 20, "source": "nickname", "width": 10, "This is a text line" 10

A normal text line that will be displayed before the table. Table is a JSON object that have "table" as key. A normal text line that will be displayed after the table. If table can t fit in one page, following pages that display the rest of table will have column s name and full border (if border is enabled). A report can have more than one table. The source key in table s column can have the following predefined value: Key Value Type Description "col" number The column number for current column, starting from 1 for the first column. "row" number The row number for current row, starting from 1 for the first row. For example: "pageformat": "pagelength": 10, "template": [ "table": "persons", "columns": [ "source": "row", "width": 4, "caption": "No", "source": "firstname", "width": 10, "wrap": true "row" will be evaluated to the current row number. 11

2.5. List Like table, list is also used to display collection. The difference is list doesn t have columnar layout. It can be treated as a collection of similiar lines. All valid keys for list are: Key Value Type Required Description "footer" array Footer that will be displayed in the end of each page if list spans multiple pages. "header" array Header that will be displayed in the beginning of each page if list spans multiple pages. "line" string Text line that will be used to evaluate every lines of this list. "list" string A script that should return Collection as the content of this list. Example of list in JSON template: "pageformat": "pagelength": 10, "template": [ "This is a text line", "list": "persons", "line": "$firstname $lastname or $nickname", "header": [ "List of persons:", "This is a text line" A normal text line that will be displayed before the list. List is a JSON object that have "list" as key. A normal text line that will be displayed after the list. 12

3. Placeholder All text lines may contain a placeholder in form of $. Placeholders will be substituted by values from data sources during filling process. simple-escp supports two kinds of placeholder: basic placeholder and script placeholder. All placeholders supports common configurations. In basic placeholder, the common configurations are separated by : such as $name:10:left. In script placeholder, they are separated by :: such as firstname + " " + lastname::10::left. The following is list of available configurations for placeholder: Type Possible Value Description Aggregation sum, count Can be used only in collection that contains number. Alignment left, right, center Determine the alignment of value if number of characters is less than width. Format number, integer, currency, date_full, date_long, date_medium, date_short Format the value based on the specified formatter. Width Number The number of characters for value. If number of characters is less than this number, value will be filled by spaces. If number of characters is more than this number, value will be truncated. The configurations can be in any orders. For example, $name:20:left is equals to $name:left:20. 3.1. Basic Placeholder Basic placeholder is defined by using the following syntax: $. The content of basic placeholder is simply a string that refers to a member of data source. For example, $name will refer to map.get("name") if the data source is a map or object.getname() if the data source is a JavaBean object. 13

For JavaBean object data source, basic placeholder supports nested attributes. For example, $name.firstname will refer to object.getname().getfirstname(). Basic placeholder also supports method call by prepending the method s name with @. For example, $@fullname will refer to object.fullname(). Example: "pageformat": "pagelength": 10, "template": [ "First name : $firstname:20", "Last name : $lastname:20", "Address 1 : $address.line1:20", "Address 2 : $address.line2:20", "Total : $@total:20:currency" 3.2. Script Placeholder Script placeholder is defined by using the following syntax:. The content of script placeholder will be evaluated by script engine. simple-escp uses JSR 223: Scripting for the Java Platform API to evaluates the content of script placeholder. If Groovy script engine is available, simple-escp will use it. Otherwise simple-escp will use the default JavaScript engine bundled in JDK. Script can refer to any members of data source by their name. Script may use special variable bean to refer to JavaBean data source if it is available. Example: "template": [ "First name : firstname :: 20 ", "Last name : lastname :: 20 ", "Address 1 : address.getline1() :: 20 ", "Address 2 : address.getline2() :: 20 ", "Total : bean.total() :: 20 :: currency" 14

User can also add custom variables to script s engine context, for example: FillJob job = new FillJob(report, datasource); job.addscriptvariable("prefix", "Mr"); String result = job.fill(); Can be used in script placeholder, for example: prefix + " " + firstname 4. Function To call function in text lines, use the following syntax: %. 4.1. Numbering Functions The following is list of functions that return number. Name Example Description GLOBAL_LINE_NO %GLOBAL_LINE_NO Return the current global line number. INC %INC A, %INC B Create a global number variable that start from 1 and return its value. The subsequent invocations of this function will increase the variable by 1. LINE_NO %LINE_NO Return the current line number. Line number will reset to 1 when encountering a new page. PAGE_NO %PAGE_NO Return the current page number. Example: "template": "header": ["Page %PAGE_NO", "detail": [ 15

"%LINE_NO This is the content." 4.2. Styling Functions Styling functions are used to generate ESC/P codes to change font style for a portion of text. They are commonly used in form of % text %. The following is list of functions used for changing font style: Name Example Description BOLD %BOLDtext%BOLD Bold font style. DOUBLE %DOUBLEtext%DOUBLE Double-strike font style. ITALIC %ITALICtext%ITALIC Italic font style. SUB %SUBtext%SUB Subscript font style. SUP %SUPtext%SUP Superscript font style. UNDERLINE %UNDERLINEtext%UNDERLINE Underline font style. Example: "template": "detail": [ "%BOLDbold text%bold and %ITALICitalic text%italic." 4.3. Miscellaneous Functions To generate an ASCII character, call function with ASCII number. For example: "template": "detail": [ "%176 %177 %178" 16

ASCII function can also be used to repeat characters. For example: "template": "detail": [ "%177 R10." Create 10 characters that consist of ASCII character 177. 4.4. Custom Function User can also create custom functions by extending Function class. The following is an example of custom function: public class CustomFunction extends Function public CustomFunction() super("%\\\\s*(my_custom)\\s*\\"); @Override public String process(matcher matcher, Report report, Page page, Line line) return "MyCustomResult"; @Override public void reset() // do nothing This function will replace all occurences of %MY_CUSTOM. It always return MyCustomResult. 17

To make simple-escp recognize this function, it must be added to FillJob by using code such as: CustomFunction customfunction = new CustomFunction(); FillJob.addFunction(customFunction); customfunction will be available globally. 5. Data Source In simple-escp, a data source is an implementation of DataSource. By default, simple-escp shipped with following implementations: MapDataSource BeanDataSource JsonDataSource The following code shows how to create data source: MapDataSource mapdatasource = new MapDataSource(map); BeanDataSource beandatasource = new BeanDataSource(bean); FillJob fillwithmap = new FillJob(report, mapdatasource); FillJob fillwithbean = new FillJob(report, beandatasource); FillJob fillmultiplesources = new FillJob(report, new DataSource[mapDataSource, beandatasource); User can also directly create DataSource from Map or JavaBean object by using DataSources factory, for example: FillJob fillwithmap = new FillJob(report, DataSources.from(map)); FillJob fillwithmap = new FillJob(report, DataSources.from(bean)); FillJob fillmultiplesources = new FillJob(report, DataSources.from(map, bean)); 6. Swing simple-escp provides PrintPreviewPane that can be used to preview and print a report from Swing-based user interface. The following code shows how to use PrintPreviewPane : 18

printpreviewpane = new PrintPreviewPane(); printpreviewpane.display(template, datasources); simple-escp also shipped with a small editor that can be used to test Json template. This editor consists of three tabs. Use the first tab to enter Json template. Default shortcut for first tab is Ctrl+1. Figure 2. Json template editor Use the second tab to enter data source. This will be used as source value for JsonDataSource. Default shortcut for second tab is Ctrl+2. 19

Figure 3. Json data source editor The third tab is used to display the print preview for current template and data source. Default shortcut for third tab is Ctrl+3. This tab will refresh itself whenever it is opened. Figure 4. Preview pane 20

7. Reference Source code: https://github.com/jockihendry/simple-escp Javadoc: http://jockihendry.github.io/simple-escp/javadoc/index.html 21