Controlling table row height for document in poi - ms-word

I am trying to draw a table in poi using XWPF component using the below code
// InputStream in= Temp.class.getResourceAsStream("Sample.docx");
XWPFDocument doc = new XWPFDocument();
XWPFTable table=doc.createTable(2,2);
// CTDecimalNumber rowSize = table.getCTTbl().getTblPr().getTblStyleRowBandSize();
// rowSize.setVal(new BigInteger("10"));
// table.getRow(1).setHeight(0);
table.getRow(0).getCell(0).setText("Row-0-Cell-0");
table.getRow(0).getCell(1).setText("Row-0-Cell-1");
table.getRow(1).getCell(0).setText("Row-1-Cell-0");
table.getRow(1).getCell(1).setText("Row-1-Cell-1");
FileOutputStream out = new FileOutputStream("simpleTable.docx");
doc.write(out);
out.close();
It draws the table properly but The height of the cells are too big and width also does not falls properly in place. I saw in a note that the table are supposed to auto fit as per the content. Tried couple of things which are as follows:
Tried setting the height as shown in the commented code above but
that did not worked.
Tried reading an existing doc as shown in
inputstream commented code. That gave an exception that could not
read a poi-ooxml file.
Tried using TblStyleRowBandSize but that
always remains null. Not sure how to create a new instance of
CTDecimalNumber or TblStyleRowBandSize
thanks in advance.
Some more insight:
When I create an empty table, and add rows and column by using create, it works fine and does not inserts the formatting character. But making an empty table results in a cell created at the begining and I am still trying to find a way to remove that first column. New code
XWPFTable table=doc.createTable();
XWPFTableRow row1 = table.createRow();
row1.createCell().setText("Row-0-Cell-0");
row1.createCell().setText("Row-0-Cell-1");
XWPFTableRow row2 = table.createRow();
row2.createCell().setText("Row-1-Cell-0");
row2.createCell().setText("Row-1-Cell-1");

I'm not sure on most of your query, but I can help with the last bit, you'll want something like:
if(! table.getTblPr().isSetTblStyleRowBandSize()) {
table.getTblPr().addNewTblStyleRowBandSize();
}
System.out.println("Was " + table.getTblPr().getTblStyleRowBandSize().getVal());
table.getTblPr().getTblStyleRowBandSize().setVal(new BigInteger("12345"));
System.out.println("Now " + table.getTblPr().getTblStyleRowBandSize().getVal());

Related

Word cannot open DOCX file with a table

I am trying to run mail merge against a DOCX file using Open XML API - just replacing a <w:t> element with a table (see below). Even the simplest table created using the following code results in Word erroring out when opening the file.
If I get rid of the row (so that I only have <w:tbl> / <w:tblGrid> / <w:GridCol>). there is no error, but then I cannot have any data of course.
Can anybody see what I am doing wrong?
Table table = new Table(new TableGrid(new GridColumn() { Width = "2000"}),
new TableRow(new TableCell(new Paragraph(new Run(new Text("test")))))
);
TextNode.Parent.ReplaceChild<Text>(table, TextNode);
You cannot replace <w:t> with <w:tbl>. The table is a block-level element so you can place it in the same places where you have the paragraph (<w:p>).
In other words, you can place it as a child element of one of the following: body, comment, customXml, docPartBody, endnote, footnote, ftr, hdr, sdtContent, tc, and txbxContent.
So, try something like this:
// TextNode (Text) -> Parent (Run) -> Parent (Paragraph)
var paragraph = TextNode.Parent.Parent as Paragraph;
paragraph.Parent.ReplaceChild(table, paragraph);
EDIT:
If the parent element is <w:tc>, you should add an empty paragraph to its end:
// TextNode (Text) -> Parent (Run) -> Parent (Paragraph)
var paragraph = TextNode.Parent.Parent as Paragraph;
var parent = paragraph.Parent;
parent.ReplaceChild(table, paragraph);
if (parent is TableCell)
parent.InsertAfter(new Paragraph(), table);

Adding columns to a Web2py table in a form

In my web2py application, in the controller I read from an external DB the names of students I want to take a register for. I loop through the resulting list adding the list elements to a new list.
for student in pupils_query:
attendance_list.insert(counter, [student[0], student[1], student[2], student[3]])
counter += 1
counter = 0
Then for each student I read their attendance codes for the day so far from another table, and append them to attendance_list:
for attendance_code in attendance_result:
attendance_list[counter].append(attendance_code)
Now, I'm going to want to make a form from all this, using a table which will show each students' attendance code in a text input (so they can be updated if wrong), then have a dropdown for input of the current lesson code.
I'm using a FORM and TABLE helper to create the table in the form:
form=FORM(TABLE(*[TR(*rows) for rows in attendance_list]))
but can't seem to be able to add a new 'row' form item with something like:
select = "SELECT("+ main_reg_list +")"
attendance_list[counter].append(select)
where main_reg_list is dictionary of acceptable attendance codes (or of course, any other form input element).
In summary, I'm stuck adding new TDs to a table made with a TABLE helper from a list of lists. I bet I'm not the first person to overcome this problem.
I am still not clear about what you want. I think you want table of student information and in one column you want dropdown. Something similat to following image
Above form is created from following code.
I hope following code will help you:
# controller/default.py
def index():
# Dummy attendance list, list after appending attendance code
attendance_list = [['stud_id_1', 'first_name_1', 'last_name_1', 'attendance_code_1'],
['stud_id_2', 'first_name_2', 'last_name_2', 'attendance_code_2'],
['stud_id_3', 'first_name_3', 'last_name_3', 'attendance_code_5'],
['stud_id_4', 'first_name_4', 'last_name_4', 'attendance_code_4']]
possible_att_code = ['attendance_code_1', 'attendance_code_2', 'attendance_code_3', 'attendance_code_4', 'attendance_code_5']
# initialise form_rows with Table heading
form_rows = [THEAD(TR(TH('ID'), TH('First Name'), TH('Last Name'), TH('Attendence Code')))]
for attendance in attendance_list:
attendance_code_dropdown = _get_dropdown(attendance[0], attendance[3], possible_att_code)
td_list = [TD(attendance[0]), TD(attendance[1]), TD(attendance[2]),
TD(attendance_code_dropdown)]
table_row = TR(td_list, _id='row_' + attendance[0])
form_rows.append(table_row)
# Form submit button
form_rows.append(TR(INPUT(_type='submit')))
form = FORM(TABLE(*form_rows), _name='student_attendance',
_id='student_attendance')
if form.accepts(request, session):
# Write code to update record
pass
return dict(form=form)
def _get_dropdown(stud_id, att_code, possible_att_code):
option_list = []
for pac in possible_att_code:
if pac == att_code:
option_list.append(OPTION(pac, _value=pac, _selected='selected'))
else:
option_list.append(OPTION(pac, _value=pac))
return SELECT(*option_list, _name=stud_id)
<!-- views/default/index.html -->
{{extend 'layout.html'}}
{{=form}}
Are my assumptions correct? or you want any thing else? Comment if didn't understood code.

iTextSharp - how to find out how many columns have the page [duplicate]

My code below is lost when opening PDF file which has only one column on the front page and more than 1 column on other pages.
Someone can tell me what I'm doing wrong?
Below my code:
PdfReader pdfreader = new PdfReader(pathNmArq);
ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
for (int page=1; page <= lastPage; page++)
{
     extractText = PdfTextExtractor.GetTextFromPage(pdfreader, page, strategy);
extractText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(extractText)));
    / / ...
}
You use the SimpleTextExtractionStrategy. This strategy assumes that the text drawing instructions in the PDF are sorted by the reading order. In your case that does not seem to be the case.
If you cannot count on the PDF containing drawing operations in reading order but are only using iText text extraction strategies from the distribution, you have to know areas which constitute a single column. If a page contains multiple columns, you have to use RegionTextRenderFilter to restrict to a column and then use the LocationTextExtractionStrategy.
PS: What exactly is your intention in that
extractText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(extractText)));
line?

GWT incubator table data ordering issue

I have implemented a gwt incubator table following the example at http://zenoconsulting.wikidot.com/blog:17
this works great however, the order of rows is not same as it is passed using the list object.
the data in this example is set in the following part of the code:
public long showMessages(ArrayList<Message> list) {
long start = System.currentTimeMillis();
// update the count
countLabel.setText("There are "+ list.size() + " messages.");
// reset the table model data
tableModel.setData(list);
// reset the table model row count
tableModel.setRowCount(list.size());
// clear the cache
cachedTableModel.clearCache();
// reset the cached model row count
cachedTableModel.setRowCount(list.size());
// force to page zero with a reload
pagingScrollTable.gotoPage(0, true);
long end = System.currentTimeMillis();
return end - start;
}
Please provide some solution to fix this issue.
awesome! thank you! somehow i ignored this part and internally down the line code was using a hashMap to manage table data which obviously does not retain the sort order. i changed it to linkedHashMap and it worked

jasper reports table creation

I would like to create a table in my Jasper Report.
This could be done (and it is done :-) ) in iReport, but the content of the table (for example names of the columns) are changing, so I would like to create the report solely from JAVA code (by not using jrxml files).
How is it possible?
So far, this is what I have done (the main parts only):
//table component
final StandardTable table = new StandardTable();
final StandardColumn col1 = new StandardColumn();
final DesignCell col1Header = new DesignCell();
final JRDesignStaticText textElement = new JRDesignStaticText();
col1Header.addElement(textElement);
col1.setDetailCell(col1Header);
table.addColumn(col1);
/datasource
final JRDesignDatasetParameter param = new JRDesignDatasetParameter();
param.setName("REPORT_DATA_SOURCE");
final JRDesignExpression exp = new JRDesignExpression("$P{REPORT_DATA_SOURCE}");
param.setExpression(exp);
//datasetrun
final JRDesignDatasetRun drs = new JRDesignDatasetRun();
table.setDatasetRun(drs);
drs.addParameter( param );
How to continue?
Thank you,
krisy
In case anyone stumbles upon the same problem (and for future myself :-) ) here is how to continue the code above, to add a table element to the summary of the report:
//create reportElement (inside componentelement)
JRDesignComponentElement reportElem = new JRDesignComponentElement();
//reportElem.setKey("table");
reportElem.setComponentKey(new ComponentKey("http://jasperreports.sourceforge.net/jasperreports/components", "jr", "table"));
reportElem.setComponent(table);
reportElem.setHeight(100);
reportElem.setWidth(100);
//add to summary
jRSummary.addElement(reportElem);
(the hard part was to find out how to create the ComponentKey object)
Note: in order to use the table, the subdataset element needs to be created as well.
For htmlComponent the ComponentKey should be:
new ComponentKey("http://jasperreports.sourceforge.net/htmlcomponent", "jr",
"html");