How to get bookmarked table and rows in text file? - java

I'm having the docx file with the following string
"My name is santhanam"
"I'm from India"
"I love docx4j"
And I bookmarked the above three paragraph with the bookmark name para0,para1,para2. I need to get the output as text file with following string
{para0}My name is santhanam{para0}
{para1}I'm from India{para1}
{para2}I love docx4j{para2}
Which I already succeeded with following code.
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "5.txt";
String inputfilepath = "bookmark.docx";
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
// String bookmark[] = new String[100000];
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
// this to suit
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results)
{
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
// System.out.println("Document\n---------------\n" + docString);
try {
// BufferedWriter bw = new BufferedWriter(new
// FileWriter(outputfilepath));
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
public static List<Object> getAllElementFromObject(Object obj, Class<?> toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement)
obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
private P findBookmarkedParagraphInMainDocumentPart(String name, MainDocumentPart documentPart)
throws JAXBException, Docx4JException {
final String xpath = "//w:bookmarkStart[#w:name='" + name + "']/..";
List<Object> objects = documentPart.getJAXBNodesViaXPath(xpath, false);
return (org.docx4j.wml.P) XmlUtils.unwrap(objects.get(0));
}
// No xpath implementation for other parts than main document; traverse
// manually
private P findBookmarkedParagraphInPart(Object parent, String bookmark) {
P p = traversePartForBookmark(parent, bookmark);
return p;
}
// Used internally by findBookmarkedParagrapghInPart().
private P traversePartForBookmark(Object parent, String bookmark) {
P p = null;
List children = TraversalUtil.getChildrenImpl(parent);
if (children != null) {
for (Object o : children) {
o = XmlUtils.unwrap(o);
if (o instanceof CTBookmark) {
if (((CTBookmark) o).getName().toLowerCase().equals(bookmark)) {
return (P) parent; // If bookmark found, the surrounding
// P is what is interesting.
}
}
p = traversePartForBookmark(o, bookmark);
if (p != null) {
break;
}
}
}
return p;
}
}
Now I bookmarked the docx file which contains tables with table0 to table(etc) with bookmarked (Tr)rows and (Tc)cells.Is it possible to get the output as
{table0}{row0}{cello}{para0}text string{para0}{para1}text string{para1}{cell0}{row0}
{row1}{cell1}{para2}text string{para2}{para3}text string{para3}{cell1}{row1}{table0}
Thanks in advance.
UPDATE
Now,I'm halfway there with the following code
public class GetBookMark {
public static void main(String[] args) throws Exception {
String docString = "";
String outputfilepath = "BMChapter 14.txt";
String inputfilepath = "BMTable.docx";
String rowbm = null;
String tblbm = null;
String parabm = null;
String cellbm = null;
String tblparabm = null;
List<Object> tblTexts = null;
String partDocString = null;
String prtblbm = null;
String prrowbm = null;
String prcellbm = null;
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File(inputfilepath));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
GetBookMark gb = new GetBookMark();
ClassFinder finder = new ClassFinder(CTBookmark.class); // <----- change
new TraversalUtil(documentPart.getContent(), finder);
for (Object o : finder.results) {
CTBookmark BookMkStart = (CTBookmark) o;
String BookMarkName = BookMkStart.getName();
if (BookMarkName.startsWith("para")) {
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + BookMarkName + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + BookMarkName + ">");
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
} else {
if (BookMarkName.startsWith("table")) {
// rowbm = "</"+BookMarkName+">";
// tblbm = "<"+BookMarkName+">";
tblbm = BookMarkName;
}
if (BookMarkName.startsWith("row")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm +="<"+BookMarkName+">";
rowbm = BookMarkName;
}
if (BookMarkName.startsWith("cell")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
cellbm = BookMarkName;
}
if (BookMarkName.startsWith("tble")) {
// rowbm = "</"+BookMarkName+">" +rowbm;
// tblbm+="<"+BookMarkName+">";
tblparabm = BookMarkName;
P p = gb.findBookmarkedParagraphInMainDocumentPart(BookMarkName, documentPart);
List<Object> texts = getAllElementFromObject(p, Text.class);
if (texts.size() == 0) {
} else {
if (prtblbm != tblbm) {
docString += "<" + tblbm + ">";
}
if (prrowbm != rowbm) {
docString += "<" + rowbm + ">";
}
if (prcellbm != cellbm) {
docString += "<" + cellbm + ">";
}
Text t1st = (Text) texts.get(0);
t1st.setValue("<" + tblparabm + ">" + t1st.getValue());
Text tLast = (Text) texts.get(texts.size() - 1);
tLast.setValue(tLast.getValue() + "</" + tblparabm + ">");
}
prtblbm = tblbm;
prrowbm = rowbm;
prcellbm = cellbm;
}
for (Object o1 : texts) {
Text t = (Text) o1;
docString += t.getValue();
}
docString += "\r\n";
}
}
try {
Writer writer = new OutputStreamWriter(new FileOutputStream(outputfilepath), "UTF-8");
BufferedWriter bw = new BufferedWriter(writer);
bw.write(docString);
bw.close();
} catch (Exception e) {
System.out.println("Exception while writing to file : " + e);
}
}
System.out.println(docString);
}

Related

Exporting data to PDF JAVA, Eclipse, Jasper

I tried to make an exporting data to PDF but when I try to export it, the pdf can't show up like "no data found"
this code on bean
public JasperPrint exportTo() {
if(this.listReportMaster == null || this.listReportMaster.isEmpty()){
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
return null;
}
String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("/resources/report/PRPKReportPDF.jasper");
JRBeanCollectionDataSource beanCollectionDataSource = new JRBeanCollectionDataSource(this.listReportMaster);
try {
JasperPrint jasperPrint = JasperFillManager.fillReport(path, null, beanCollectionDataSource);
return jasperPrint;
} catch (JRException e) {
e.printStackTrace();
return null;
}
}
public void exportToPdf(ActionEvent actionEvent){
if(this.lazyMasterReportDataModel != null){
System.out.println("masuk exporttopdf");
String sql = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getSqlReportPrint();
List<Object> listObject = ((LazyMasterReportDataModel) this.lazyMasterReportDataModel).getObjectSqlListReportPrint();
this.listReportMaster = reportMasterPRPKController.getPRPKForReport(sql, listObject);
JasperPrint jasperPrint = exportTo();
String fileName = "PRPKNew_Report".concat("_").concat(".pdf");
if(jasperPrint != null) reportMasterPRPKController.exportToPDF(fileName, jasperPrint);
else System.out.println("jasperprint null");
}else{
System.out.println("keluar exporttopdf");
FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found");
RequestContext.getCurrentInstance().showMessageInDialog(messageFailed);
}
}
every I try to export it, always show "no data found" which is the program run this code FacesMessage messageFailed = new FacesMessage(FacesMessage.SEVERITY_INFO,"Info","No data found"); and which meam the "this.lazyMasterReportDataModel" is null but when I check it again, there's nothing wrong on code, I don't know if it have a wrong code or deficiency code
this the lazy code
List<ReportMasterPRPK> listMasterPRPK = new ArrayList<>();
ReportMasterPRPKQuery reportMasterPRPKQuery = new ReportMasterPRPKQuery();
Page page = new Page();
String order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
String columname = "";
String sql = "";
List<Object> objectSqlList = new ArrayList<>();
String sqlReport = "";
String sqlReportPrint = "";
List<Object> objectSqlListReport = new ArrayList<>();
List<Object> objectSqlListReportPrint = new ArrayList<>();
String flag;
public LazyMasterReportDataModel() {
}
public LazyMasterReportDataModel(String flag) { //ini
this.flag = flag;
}
public LazyMasterReportDataModel(String sqlReport, List<Object> objectSqlListReport) {
this.sqlReport = sqlReport;
this.objectSqlListReport = objectSqlListReport;
}
#Override
public List<ReportMasterPRPK> load(int first, int pageSize, String sortField, SortOrder sortOrder,
Map<String, Object> filters) {
page.setLimit(pageSize);
page.setOffset(first);
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList = new ArrayList<>();
//objectSqlList.clear();
}
if(flag != null){ //ini
if(flag.equals("no selected")){
sql = sql+" AND c.is_selected = 'n' ";
}
}
if (filters != null){
for(String key: filters.keySet()){
String filterColumnName = "";
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(key)) filterColumnName = field.getAnnotation(Column.class).value();
}
if(filters.get(key) instanceof String){
if("receivedDate".equals(key)){
if(((String)filters.get(key)).trim().length() > 20){
String startDate = "'" + filters.get(key).toString().substring(0, 10) + "'";
String endDate = "'" + filters.get(key).toString().substring(11, 21) + "'";
sql = sql + " AND " + filterColumnName + " BETWEEN " + startDate + " AND " + endDate+ " ";
}
}else{
if(((String) filters.get(key)).trim().length() > 0){
sql = sql+"AND "+filterColumnName+" ILIKE ? ";
String value = "%"+filters.get(key)+"%";
objectSqlList.add(value);
}
}
}else{
if(((String[]) filters.get(key)).length > 0){
sql = sql+" AND "+filterColumnName+" in ";
String value = "(";
for(String string : (String[]) filters.get(key)){
value = value+"'"+string+"',";
}
value = value.substring(0, value.length()-1)+") ";
sql = sql + value;
}
}
}
}
if(sortField != null){
for(Field field : ReportMasterPRPK.class.getDeclaredFields()){
if(field.getName().equals(sortField)) columname = field.getAnnotation(Column.class).value();
}
if(sortOrder.toString().equals("ASCENDING")) order = " ASC";
else order = " DESC";
sql = sql+" GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY "+columname+" "+order;
System.out.println("sql sort: "+sql+" : "+objectSqlList.size());
}else{
sql = sql + order;
}
sqlReportPrint = sql;
objectSqlListReportPrint = objectSqlList;
this.listMasterPRPK = reportMasterPRPKQuery.retrivePage(page, sql, objectSqlList.toArray());
int dataSize = reportMasterPRPKQuery.retrieveMaxRow(sql, objectSqlList.toArray());
this.setRowCount(dataSize);
//objectSqlList.clear();
if(this.sqlReport != null){
this.sql = this.sqlReport;
this.objectSqlList = this.objectSqlListReport;
}else{
sql = "";
objectSqlList.clear();
}
order = "GROUP a.prpk_number, a.prpk_type_id, a.created_date, a.pic_prpk_id, a.business_unit_id, a.pic_department_id, a.prpk_desc, a.prpk_request, a.prpk_background, a.prpk_analysis_benefit, a.priority_level_id, a.cost, b.prpk_type_name, c.business_unit, d.department_name, e.priority_name, f.user_name ORDER BY a.created_date ";
return listMasterPRPK;
}
public List<ReportMasterPRPK> calculateRownum(List<ReportMasterPRPK> listMasterPRPK, int first){
int i = 1;
for (ReportMasterPRPK masterPRPK : listMasterPRPK) {
masterPRPK.setRownum(first + i);
i++;
}
return listMasterPRPK;
}
public String getSqlReportPrint() {
return sqlReportPrint;
}
public void setSqlReportPrint(String sqlReportPrint) {
this.sqlReportPrint = sqlReportPrint;
}
public List<Object> getObjectSqlListReportPrint() {
return objectSqlListReportPrint;
}
public void setObjectSqlListReportPrint(List<Object> objectSqlListReportPrint) {
this.objectSqlListReportPrint = objectSqlListReportPrint;
}
sorry before, if my english is to bad, but I hope you understand about what I mean...
thanks before...

XWPFDocument replace paragraphe in a loop

I have a table that contains items. I want to set the names of items in the word document but each one in a new line.
So I created the void below:
When my text contain "P01" I replace the text by the name, add a new line and set another text "P01".
public void findAndRemplaceString(XWPFDocument doc, String champs) throws IOException {
for (XWPFParagraph p : doc.getParagraphs()) {
java.util.List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("P01")) {
text = text.replace("P01", champs);
System.out.println("text replaced");
r.setText(text, 0);
//add new line
r.addBreak();
//new "P01" added
r.setText("P01");
}
}
}
}
}
So that the next name of item will be replaced in the paragraph below.
#FXML
void endButton(ActionEvent event) {
String file = "model";
for (Person item : table.getItems()) {
//get the name of item
String a = item.getName();
// get the index of item
int ind0 = table.getItems().indexOf(item);
int ind1 = table.getItems().indexOf(item) + 1;
try {
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File(file + ind0 + ".docx")));
findAndRemplaceString(doc, a);
FileOutputStream fileOutputStream = new FileOutputStream(new File(file + ind1 + ".docx"));
doc.write(fileOutputStream);
fileOutputStream.close();
doc.close();
} catch (Exception e) {
System.out.println("erreur " + e);
}
}
}
The problem is:
It replace only the first name of item and not the others. It doesn't read the new "P01" that I set.
I found the answer, it's not the best but it works.
I changed the type of String[] instead of String, so that i can do it this way :
public void findAndRemplaceString(XWPFDocument doc,String champs[]){
for (XWPFParagraph p : doc.getParagraphs()) {
java.util.List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("P01") ) {
for (int i=0;i<champs.length;i++){
text = text.replace("P01","");
r.setText(text,0); //Replace the old text
r.setText(champs[i]);//add the new text
r.addBreak(); //new line
}
}
}
}
}
}
And when I click the button, the void findAndReplaceString is called only once instead of looping, so I put all the item names in a list like that:
#FXML void endButton(ActionEvent event) {
List<String> list = new ArrayList<String>();
for (Person item : table.getItems()) {
String a = item.getName();
list.add(a);
}
String[] simpleArray = new String[list.size()];
list.toArray(simpleArray);
try{
XWPFDocument doc = new XWPFDocument(new FileInputStream(new File("input.docx")));
findAndRemplaceString(doc,simpleArray);
FileOutputStream fileOutputStream = new FileOutputStream(new File("output.docx"));
doc.write(fileOutputStream);
fileOutputStream.close();
doc.close();
}catch (Exception e) {
System.out.println("erreur " + e);
}
}

Issue of Duplicate cell content in last cell and last row while Copying table from one docx file to other docx file using docx4j

//*I am trying to copy a table from one document of docx file to other document of docx file. But last cell of my table and last row are getting duplicated along with content in the last cell. Rest all is working fine. I am able to copy complete table but only when it come to last cell and last row , i am getting duplicate. It Will be very helpful, if someone could guide me , exactly where i am doing mistakes , i have tried it for complete 2 days but it didn't work.
This is my complete code and i am trying with only one table in file nothing else.
*//
public class ExtractTables {
public static void main(String args[]) throws JAXBException, IOException, Docx4JException {
try {
WordprocessingMLPackage wordMLPackage;
wordMLPackage = WordprocessingMLPackage.load(new java.io.File("D://Table.docx"));
MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();
ObjectFactory factory = Context.getWmlObjectFactory();
ExtractTables wordExt = new ExtractTables();
wordExt.extractTable(factory, documentPart);
} catch (Docx4JException DOE) {
System.out.println("The exception is : ");
DOE.printStackTrace();
}
}
private void extractTable(ObjectFactory objFact, MainDocumentPart documentPart) throws Docx4JException {
try {
WordprocessingMLPackage wml = WordprocessingMLPackage.createPackage();
int noTbls = 0;
int noRows = 0;
int noCells = 0;
int noParas = 0;
int noTexts = 0;
List<Object> allTables = getAllElementFromObject(documentPart, Tbl.class);
for (Object table : allTables) {
noTbls++;
Tbl tbl = (Tbl) table;
Tr tr = null;
Tc tc = null;
P p = null;
R r = null;
Text txt = null;
// Get all the Rows in the table
List<Object> allRows = getAllElementFromObject(tbl, Tr.class);
for (Object row : allRows) {
tr = (Tr) row;
noRows++;
// Get all the Cells in the Row
List<Object> allCells = getAllElementFromObject(tr, Tc.class);
for (Object cell : allCells) {
tc = (Tc) cell;
noCells++;
// Get all the Paragraph's in the Cell
List<Object> allParas = getAllElementFromObject(tc, P.class);
for (Object par : allParas) {
p = (P) par;
noParas++;
// Get all the Run's in the Paragraph
List<Object> allRuns = getAllElementFromObject(p, R.class);
for (Object runs : allRuns) {
r = (R) runs;
// Get the Text in the Run
List<Object> allText = getAllElementFromObject(r, Text.class);
for (Object text : allText) {
noTexts++;
txt = (Text) text;
}
System.out.println("No of Text in Para No: " + noParas + "are: " + noTexts);
}
}
System.out.println("No of Paras in Cell No: " + noCells + "are: " + noParas);
}
System.out.println("No of Cells in Row No: " + noRows + "are: " + noCells);
}
System.out.println("No of Rows in Table No: " + noTbls + "are: " + noRows);
r.getContent().add(txt);
p.getContent().add(r);
tc.getContent().add(p);
tr.getContent().add(tc);
tbl.getContent().add(tr);
wml.getMainDocumentPart().addObject(tbl);
wml.save(new File("D://TestTable.docx"));
}
System.out.println("Total no of Tables: " + noTbls);
}
catch (Docx4JException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static List getAllElementFromObject(Object obj, Class toSearch) {
List<Object> result = new ArrayList<Object>();
if (obj instanceof JAXBElement)
obj = ((JAXBElement<?>) obj).getValue();
if (obj.getClass().equals(toSearch))
result.add(obj);
else if (obj instanceof ContentAccessor) {
List<?> children = ((ContentAccessor) obj).getContent();
for (Object child : children) {
result.addAll(getAllElementFromObject(child, toSearch));
}
}
return result;
}
}

How to remove the quotes while converting a file from sql to tbl

Below is the code which converts the .sql file for insert statements into .tbl file. As the input file is .sql file it contains varchar(string) values inside single quotes. How can I prevent these quotes from getting in my tbl file?
Input:
INSERT INTO
post_tran(post_tran_id,tran_nr,datetime_tran_local,system_trace_audit_nr,settle_
amount_rsp,settle_tran_fee_rsp,post_tran_cust_id,prev_post_tran_id,next_post_tra
n_id,message_type,tran_postilion_originated,sink_node_name,settle_entity_id,batc
h_nr,tran_completed,tran_type,rsp_code_rsp,auth_type,auth_reason,retrieval_refer
ence_nr,settle_amount_req,settle_tran_fee_req,settle_currency_code,datetime_req,
recon_business_date,realtime_business_date,acquiring_inst_id_code) VALUES(
1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink',
1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11
12:00:00', '2004-02-11 12:00:00', '2200017000')
For example:
While processing sink_node_name, its data value should be LinkSink instead of 'LinkSink'.
public class SqlToTblCoverter {
private File source_folder = null;
private File destination_folder = null;
private String source_absolute_path = null;
private String destination_absolute_path = null;
private String absolute_file_name = null;
private String absolute_new_file_name = null;
private List<String> column_name_list = null;
private List<String> column_values_list = null;
public SqlToTblCoverter(String source_folder_name,
String destination_folder_name) {
source_folder = new File(source_folder_name);
destination_folder = new File(destination_folder_name);
source_absolute_path = source_folder.getAbsolutePath();
destination_absolute_path = destination_folder.getAbsolutePath();
column_name_list = new ArrayList<String>();
column_values_list = new ArrayList<String>();
}
public void run() throws IOException {
validateInputs();
migrateFiles();
}
private void validateInputs() {
if (source_folder.isDirectory() == false) {
System.out.println("Source must be a FOLDER");
} else if (destination_folder.isDirectory() == false) {
System.out.println("Destination must be a FOLDER");
}
}
private void migrateFiles() throws IOException {
String[] file_list = source_folder.list();
String file_name1 = file_list[0];
// System.out.println(file_name1);
String file_name2 = file_list[1];
// System.out.println(file_name2);
String f1 = migrateFileContains(file_name1);
String f2 = migrateFileContains(file_name2);
Migrator mg = new Migrator();
mg.migrate(f1, f2);
}
private String migrateFileContains(String file_name) throws IOException {
absolute_file_name = source_absolute_path + File.separator + file_name;
absolute_new_file_name = destination_absolute_path + File.separator
+ getNewFileName(file_name);
BufferedReader br = new BufferedReader(new InputStreamReader(
new FileInputStream(new File(absolute_file_name))));
String line_info = br.readLine();
StringBuffer new_query = new StringBuffer("");
FileWriter fw = new FileWriter(new File(absolute_new_file_name));
while (line_info != null) {
String convertQuery = convertQuery(line_info);
if (convertQuery.isEmpty()) {
line_info = br.readLine();
continue;
}
new_query.append(convertQuery);
new_query.append(System.getProperty("line.separator"));
fw.write(new_query.toString());
new_query.setLength(0);
line_info = br.readLine();
}
br.close();
fw.close();
return absolute_new_file_name;
}
private String convertQuery(String query) {
String new_query = "";
if (query.startsWith("INSERT")) {
int round_bracket_start = query.indexOf('(');
int round_bracket_end = query.indexOf(')');
int round_bracket_start_after_values = query.indexOf('(',
round_bracket_end);
String query_column_name = query.substring(round_bracket_start + 1,
round_bracket_end);
String query_column_values = query.substring(
round_bracket_start_after_values + 1, query.length() - 1);
covertColumnNameList(query_column_name);
covertColumnValueList(',' + query_column_values + ',');
new_query = createNewQuery() + "\n";
}
column_name_list.clear();
column_values_list.clear();
return new_query;
}
private void covertColumnNameList(String query_column_name) {
String[] column_list = query_column_name.split(",");
for (String column_name : column_list) {
column_name_list.add(column_name);
}
}
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}
private String createNewQuery() {
StringBuffer buffer = new StringBuffer("");
if (column_name_list.size() != column_values_list.size()) {
System.out.println("Error : " + absolute_file_name);
} else {
for (int index = 0; index < column_name_list.size(); index++) {
buffer.append(createNewColumn(column_name_list.get(index),
column_values_list.get(index)));
}
}
return buffer.toString();
}
private String createNewColumn(String column_name, String column_value) {
StringBuffer buffer = new StringBuffer("");
buffer.append("[name]".trim());
buffer.append(column_name.trim());
buffer.append("[/name]=[data]".trim());
buffer.append(column_value.trim());
buffer.append("[/data]".trim());
buffer.append("\r\n");
return buffer.toString();
}
private String getNewFileName(String file_name) {
String new_file_name = "";
int dot_index = file_name.indexOf('.');
new_file_name = file_name.subSequence(0, dot_index) + ".tbl";
return new_file_name;
}
}
You can replace covertColumnValueList with below code:
private void covertColumnValueList(String query_column_values) {
String temp_val = null;
for (String col_val : query_column_values.split(",")) {
if (col_val.contains("\'")) {
temp_val = col_val.replaceAll("\'", "");
column_values_list.add(temp_val.trim());
} else
column_values_list.add(col_val.trim());
}
}
I assume you have query_column_values something like below:
String query_column_values = "1,2,'2002-04-02 19:02:28','008497',4120,10, 2, 0,0,'0200', 0, 'LinkSink', 1,1,0,'01','01','00',0,'000000000102',6000,0,'840', '', '2004-02-11 12:00:00', '2004-02-11 12:00:00', '2200017000'";
replace '' by current date: Once you populate this list, replace list value at specified index.
DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Calendar cal = Calendar.getInstance();
column_values_list.set( 23, dateFormat.format(cal.getTime()));
The code to remove the delimiting apostrophes is there in covertColumnValueList, but it doesn't handle the case where a space precedes the apostroph. See the simple fix below.
//....
int next_comma_index = 0;
// skip space(s)
while( query_column_values.charAt(comma_index + 1) == ' ' ){
comma_index++;
}
if (query_column_values.charAt(comma_index + 1) == '\'') {
//...
private void covertColumnValueList(String query_column_values) {
if (query_column_values.equals(",")) {
return;
}
String column_value = null;
int comma_index = query_column_values.indexOf(',');
int next_comma_index = 0;
if (query_column_values.charAt(comma_index + 1) == '\'') {
int quote_index = query_column_values.indexOf('\'', comma_index);
int next_quote_index = query_column_values.indexOf('\'',
quote_index + 1);
next_comma_index = query_column_values.indexOf(',',
next_quote_index);
column_value = query_column_values.substring(comma_index + 2,
next_comma_index - 1);
column_value=column_value.replace("\'","") ;
} else {
next_comma_index = query_column_values
.indexOf(',', comma_index + 1);
column_value = query_column_values.substring(comma_index + 1,
next_comma_index);
column_value=column_value.replace("\'","") ;
}
column_values_list.add(column_value);
covertColumnValueList(query_column_values.substring(next_comma_index));
}

How to change text size to print on thermal printer

I have a java applicato that use the thermal print to printer a text. I use this printer to print the order for the bar.
This is an example of the ticket:
--> BAR
Coca Cola 1 x 1.5
Fanta 1 x 1.5
-------------------
TOTALE 3.00 euro
And the code to print this ticket works.
But I wanto to change the font size because the font is to small. How can I change the font ??
This is the code that I use to create and printer a ticket:
PrinterBean localPrinterBean = null;
StringBuffer localStringBuffer = null;
HashMap localHashMap=null;
if(emettiScontrinoCartaceo){
//PER LA STAMPA SCOTRNIO
localPrinterBean = getPrinterBean();
localStringBuffer = new StringBuffer();
localHashMap = null;
if ((localPrinterBean.isPrn_Enabled()) && (!localPrinterBean.isPrn_Onlyticket()))
{
//log.info("" + localPrinterBean.getPrn_driver());
localHashMap = PrinterManager.loadEscDriver(localPrinterBean);
//localStringBuffer.append("\n");
localStringBuffer.append(String.format("\t%s->> %s%s\n", new Object[] { localHashMap.get("size2w"), "BAR", localHashMap.get("size2w-off") }));
localStringBuffer.append("\n");
}
//FINE STAMPA SCOTNRINO
}
while (it.hasNext()) {
Map.Entry entry = (Map.Entry)it.next();
ArticoliScontrini artSco = (ArticoliScontrini) (entry.getValue());
//devo inserire nella lista le righe di stampa dello scontrino
//INIZIO STAMPA SCONTRINO
localStringBuffer.append(String.format("%s\n", new Object[] { artSco.getDescrizioneArticolo() }));
String quantita = artSco.getQuantita() + " x " +artSco.getPrezzoTotStringFormattato();//toString(artSco.getQuantita(), true);
localStringBuffer.append(String.format("\t %s", new Object[] { quantita }));
localStringBuffer.append("\n");
//FINE STAMPA SCONTRINO
}
localStringBuffer.append("------------------------------------------");
localStringBuffer.append("\n");
String totale = "TOTALE " + decimalFormatter2.format(totaleScontrinoCartaceo) + " euro";
localStringBuffer.append(String.format("%s\n", new Object[] { totale }));
String str = localStringBuffer.toString();
try{
cbPrintBuffer(localPrinterBean);
}
catch(Exception e){
VisualMessageScontrini.getErroreStampaScontrino();
}
public void cbPrintBuffer(PrinterBean paramPrinterBean)
throws Exception
{
/*Object localObject1 = JabirCfg.hexItIfn(paramPrinterBean.getPrn_Hexinit());
if ((localObject1 != null) && (!((String)localObject1).equals(""))) {
printRawBytes(paramPrinterBean, ((String)localObject1).getBytes());
}*/
Object localObject1 = null;
if (paramPrinterBean.hasPrn_Bitopt(2))
{
localObject1 = new FileOutputStream(paramPrinterBean.getPrn_driver());
((FileOutputStream)localObject1).write(cbGetFlow());
((FileOutputStream)localObject1).close();
return;
}
localObject1 = PrinterManager.getPrintService_cached(paramPrinterBean);
if (paramPrinterBean.isPrnGd())
{
boolean bool = paramPrinterBean.hasPrn_Bitopt(32);
PrinterJob localObject2 = PrinterJob.getPrinterJob();
((PrinterJob)localObject2).setPrintService((PrintService)localObject1);
((PrinterJob)localObject2).setJobName("easy ticket");
PageFormat localPageFormat = ((PrinterJob)localObject2).defaultPage();
PrinterExtra.deserialize_pagejson_to_PageFormat(paramPrinterBean.getPrn_pagejson(), localPageFormat);
Printable localPrintable = null;
for (int i = 0;; i++)
{
if (bool) {
localPrintable = cbPrintable(i);
} else {
localPrintable = cbPrintable(-1);
}
if (localPrintable == null) {
break;
}
((PrinterJob)localObject2).setPrintable(localPrintable, ((PrinterJob)localObject2).validatePage(localPageFormat));
((PrinterJob)localObject2).print();
if (!bool) {
break;
}
String str = JabirCfg.hexItIfn("0x1b 0x6d");
printRawBytes(paramPrinterBean, str.getBytes());
}
return;
}
DocPrintJob localDocPrintJob = ((PrintService)localObject1).createPrintJob();
Object localObject2 = new SimpleDoc(cbGetFlow(), DocFlavor.BYTE_ARRAY.AUTOSENSE, null);
localDocPrintJob.print((Doc)localObject2, new HashPrintRequestAttributeSet());
}

Categories

Resources