set the table cell width in iText java pdf - java

I am using the opensource http://itextpdf.com/ , to create some pdf .
I could create a table , but width of all column are same , I need to change the width of the particular column .
PdfPTable table = new PdfPTable(6);
Phrase tablePhrse = new Phrase("Sl n0", normalFontBold);
PdfPCell c1 = new PdfPCell(tablePhrse);
c1.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(c1);
I could not find any method to set the width of the column , pls suggest some way to do achieve this ..

You can make use of setWidths() method.
table.setWidths(new int[]{200,50});
public void setWidths(int[] relativeWidths)

Try this.
float[] columnWidths = new float[]{10f, 20f, 30f, 10f};
table.setWidths(columnWidths);

Here is the corrected one if table.setWidths(new int[]{200,50}); does not work.
innertable.setWidthPercentage(50);

float[] columnWidths = {1, 5, 5};
// columnWidths = {column1, column2, column3...}
PdfPTable table = new PdfPTable(columnWidths)

Make sure to set table total width
// Set Column Number
PdfPTable table = new PdfPTable(2);
// Set Table Total Width
table.setTotalWidth(500);
// Set Each Column Width - Make Sure Array is the same number specified in constructor
table.setWidths(new int[]{50, 450});

Related

How can I get the page number and position for a specific pdf form field and insert a table in it's place in iText7?

I wanted to insert a Table in the position of the form field. How do I get the position and page number of the form field? How do I insert the table in that location?
//Retrieves AcroForm from the document.
//If there is no AcroForm in the document Catalog and createIfNotExist
//flag is true then the AcroForm dictionary will be created and added to the document.
PdfAcroForm acroForm = PdfAcroForm.getAcroForm(pdfDoc, true);
//Gets the form fields as a Map.
Map<String, PdfFormField> fields = acroForm.getFormFields();
//Create Table
Table table = new Table(new float[]{1,1});
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
table.setWidthPercent(95);
Cell cell = new Cell();
cell.add(new Paragraph("Name"));
//cell.setBorder(Border.NO_BORDER);
table.addCell(cell);
Cell cell = new Cell();
cell.add(new Paragraph("Address"));
//cell.setBorder(Border.NO_BORDER);
table.addCell(cell);
...
...
doc.add(table);
...
Field by itself does not have any position or page number. However, its widget annotations do.
To access those, you can use field.getWidgets(). You then can use annotation.getPage() and annotation.getRectangle() to get information about the annotation's position.
To layout an single element at some specific position, one of the best choices is using Canvas layout object. Annotation can then be removed with page.removeAnnotation(annotation);.
Overall, this compiles into following solution:
String fieldName = "Text1";
PdfFormField field = form.getField(fieldName);
for (PdfAnnotation annotation : field.getWidgets()) {
PdfPage page = annotation.getPage();
Rectangle rectangle = annotation.getRectangle().toRectangle();
Table table = new Table(UnitValue.createPointArray(new float[] {-1, -1}));
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
Cell cell = new Cell();
cell.add(new Paragraph("Name"));
table.addCell(cell);
cell = new Cell();
cell.add(new Paragraph("Address"));
table.addCell(cell);
Canvas canvas = new Canvas(new PdfCanvas(page), pdfDocument, rectangle);
canvas.add(table);
canvas.close();
page.removeAnnotation(annotation);
}
Of course, you will have to take full responsibility for creating a table of proper size so that it fits into the area you want. You can use smaller font sizes etc.

How to create multiple AutoFilter at different rows using Apache POI

I want to create AutoFilters at multiple places in an excel sheet using Apache POI. (e.g. at row 2 & at row 8).
hssfSheet.setAutoFilter(new CellRangeAddress(2, 4, 6, 3));
hssfSheet.setAutoFilter(new CellRangeAddress(8, 5, 3, 5));
I've been adding it like mentioned above but second filter is overriding the first one and when excel sheet is created I can see only one.
Can someone please help me.
Thanks.
Use should use XSSFSheet and create CTTable. Sheet may contain many tables.
Here is code for adding table to sheet. Please ensure that cells were created and exist.
private void createExcelTable(XSSFSheet sheet, AreaReference reference, int tableId,
String name) {
XSSFTable table = sheet.createTable();
table.setDisplayName(name);
CTTable cttable = table.getCTTable();
// Style configurations
// CTTableStyleInfo is available in ooxml-schemas-1.1.jar.
// Replace with it your poi-ooxml.
CTTableStyleInfo style = cttable.addNewTableStyleInfo();
style.setName("TableStyleLight1");
style.setShowColumnStripes(false);
style.setShowRowStripes(true);
// Set which area the table should be placed in
cttable.setRef(reference.formatAsString());
// id starts from 1
cttable.setId(tableId);
cttable.setName(name);
cttable.setDisplayName(name);
// first row is used for header with filter
CTAutoFilter autoFilter = cttable.addNewAutoFilter();
autoFilter.setRef(reference.formatAsString());
CTTableColumns columns = cttable.addNewTableColumns();
// sets count of columns for current table
short firstColumn = reference.getFirstCell().getCol();
short lastColumn = reference.getLastCell().getCol();
columns.setCount(lastColumn - firstColumn + 1);
for (int i = firstColumn; i <= lastColumn; i++) {
// create columns
CTTableColumn column = columns.addNewTableColumn();
column.setName("Column" + i);
// id starts from 1
column.setId(i + 1);
}
}
Example of AreaReference:
new AreaReference(new CellReference(0, 0), new CellReference(4, 5));

Marking table, row and cell as DIV iText

I am creating a PDF using iText 5.5.6.
I wanted to tag table, row and cell as a DIV.
I have written the following code but only the table gets marked as a DIV and not the row and cell.
PdfPTable table = new PdfPTable(2);
table.setRunDirection(PdfAWriter.RUN_DIRECTION_LTR);
table.setRole(PdfName.DIV);
table.setWidthPercentage(80);
table.setWidths(new float[] { 0.8f, 1.2f });
table.setHorizontalAlignment(PdfPTable.ALIGN_LEFT);
table.setSpacingBefore(10);
table.setSpacingAfter(15);
Paragraph p3 = new Paragraph("Name:", font12);
Paragraph p4 = new Paragraph("FirstName LastName", font12);
Paragraph p5 = new Paragraph("DOB: ", font12);
Paragraph p6 = new Paragraph("00-00-0000", font12);
PdfPCell cellp3 = new PdfPCell(p3);
cellp3.setBorder(0);
PdfPCell cellp4 = new PdfPCell(p4);
cellp4.setBorder(0);
cellp3.setRole(PdfName.DIV);
cellp4.setRole(PdfName.DIV);
table.addCell(cellp3);
table.addCell(cellp4);
PdfPCell cellp5 = new PdfPCell(p5);
cellp5.setBorder(0);
PdfPCell cellp6 = new PdfPCell(p6);
cellp6.setBorder(0);
cellp5.setRole(PdfName.DIV);
cellp6.setRole(PdfName.DIV);
table.addCell(cellp5);
table.addCell(cellp6);
How to solve this?
If I test your code the table and all the cells are tagged as DIV. The rows are indeed not.
In iText the classes PdfPTable, PdfPRow and PdfPCell are responsible for table functionality. PdfPRow is typically only used in the iText implementation internally, because a PdfPTable instance accepts PdfPCells directly.
But you are able to retrieve the table rows to set their role. After you have added all the cells to the table, do this:
for (PdfPRow row : table.getRows())
row.setRole(PdfName.DIV);

How to auto stretch detail band when print order is set to "horizontal" in JasperReport?

I have a main report which is printed horizontally. It has 5 columns.
On every column i want to put a sub report. So i created this:
And the sub-report just like this:
The problem is, when i run i get the following exception:
net.sf.jasperreports.engine.JRRuntimeException: Subreport overflowed on a band that does not support overflow.
Looks like jasper reports can't stretch the detail band vertically when there is a sub-report in it and the print order is set to horizontal.
What can I do to avoid this error and achieve what i want?
I found the solution for this problem. After a deep search i found that, sadly, there's no way to do this on Jasper Reports because, no matter what, when you have a report printed horizontally, the "Detail" band will never change it's height. So, subreports or text fields which overflows will throw an exception.
The workaround for this problem is to work without reports, with a PDF generator like iText, for example.
This is the code i did to achive what i wanted with iText if somebody needs it:
Document document = new Document();
File arquivo = new File("C:\\Users\\Mateus\\Desktop\\testezãozarãozão.pdf");
PdfWriter.getInstance(document, new FileOutputStream(arquivo));
document.open();
LinkedHashMap<Produto, LinkedHashMap<String, List<PrePedidoItem>>> produtos = createStructuredHashMap();
for (Produto produto : produtos.keySet()) {
PdfPTable table = new PdfPTable(5);
PdfPCell cellProduto = new PdfPCell();
Phrase phraseProduto = new Phrase(String.valueOf(produto));
phraseProduto.setFont(new Font(Font.FontFamily.HELVETICA, 11, Font.BOLD|Font.UNDERLINE, new BaseColor(50, 65, 200)));
cellProduto.addElement(phraseProduto);
cellProduto.setColspan(5);
cellProduto.setHorizontalAlignment(PdfPCell.ALIGN_MIDDLE);
cellProduto.setBorder(Rectangle.NO_BORDER);
cellProduto.setPaddingBottom(10);
cellProduto.setPaddingTop(20);
table.addCell(cellProduto);
LinkedHashMap<String, List<PrePedidoItem>> mapas = produtos.get(produto);
int mapasAdicionados = 0;
for (String mapa : mapas.keySet()) {
PdfPCell cellMapa = new PdfPCell();
Phrase phraseMapa = new Phrase(mapa);
phraseMapa.setFont(new Font(Font.FontFamily.HELVETICA, 9, Font.BOLD, new BaseColor(215, 100, 0)));
cellMapa.addElement(phraseMapa);
List<PrePedidoItem> itensDoMapa = mapas.get(mapa);
for (PrePedidoItem item : itensDoMapa) {
DecimalFormat df = new DecimalFormat("###,##0.00");
Phrase phraseItem = new Phrase(df.format(item.getLargura()) + " x " + df.format(item.getComprimento()));
phraseItem.setFont(new Font(Font.FontFamily.HELVETICA, 9, Font.NORMAL, BaseColor.BLACK));
cellMapa.addElement(phraseItem);
}
cellMapa.setBorder(Rectangle.NO_BORDER);
table.addCell(cellMapa);
mapasAdicionados ++;
if(mapasAdicionados == 5) {
mapasAdicionados = 0;
}
}
PdfPCell celulaPreenchimentoMapas = new PdfPCell();
celulaPreenchimentoMapas.setColspan(5 - mapasAdicionados);
celulaPreenchimentoMapas.setBorder(Rectangle.NO_BORDER);
table.addCell(celulaPreenchimentoMapas);
document.add(table);
}
document.close();
Desktop.getDesktop().open(arquivo);

How to fill a PdfPTable column by column instead of row by row, using iText

I am using Java with iText in order to generate some PDFs. I need to put text in columns, so I am trying to use PdfPTable. I create it with:
myTable = new PdfPTable(n);
n being the number of columns. The problem is that PdfPTable fills the table row by row, that is, you first give the cell in column 1 of row 1, then column 2 of row 1, and so on, but I need to do it column by column, because that is how the data is being fed to me.
I would use a Table (which lets you specify the position) like in http://stderr.org/doc/libitext-java-doc/www/tutorial/ch05.html, but I get a "could not resolve to a type", and my Eclipse can't find the proper import.
Edit: in case my previous explanation was confusing, what I want is to fill the table in this order:
1 3 5
2 4 6
Instead of this:
1 2 3
4 5 6
Here is one way: Create a PdfPTable with the number of columns desired, in your case 3. For each iteration through your data create a PdfPTable with 1 column. Create 2 PdfPCell objects, one containing the data element you are currently on and the other containing the next value in your data. So now you have a PdfPTable with 1 column and two rows. Add this PdfPTable to the PdfPTable that has 3 columns. Continue that until you've printed all your data. Better explained with code:
public class Clazz {
public static final String RESULT = "result.pdf";
private String [] data = {"1", "2", "3", "4", "5", "6"};
private void go() throws Exception {
Document doc = new Document();
PdfWriter.getInstance(doc, new FileOutputStream(RESULT));
doc.open();
PdfPTable mainTable = new PdfPTable(3);
PdfPCell cell;
for (int i = 0; i < data.length; i+=2) {
cell = new PdfPCell(new Phrase(data[i]));
PdfPTable table = new PdfPTable(1);
table.addCell(cell);
if (i+1 <= data.length -1) {
cell = new PdfPCell(new Phrase(data[i + 1]));
table.addCell(cell);
} else {
cell = new PdfPCell(new Phrase(""));
table.addCell(cell);
}
mainTable.addCell(table);
}
doc.add(mainTable);
doc.close();
}
}
One way could be creating inner table of column no = 1 for each main column and add that into a main table.
private static PdfPTable writeColumnWise(String[] data, int noOfColumns, int noOfRows) {
PdfPTable table = new PdfPTable(noOfColumns);
PdfPTable columnTable = new PdfPTable(1);
columnTable.getDefaultCell().setBorderWidth(0.0f);
columnTable.getDefaultCell().setPadding(0.0f);
for(int i=0; i<data.length; i++){
if( i != 0 && i % noOfRows == 0 ){
// add columnTable into main table
table.addCell(columnTable);
//re initialize columnTable for next column
columnTable = new PdfPTable(1);
columnTable.getDefaultCell().setBorderWidth(0.0f);
columnTable.getDefaultCell().setPadding(0.0f);
}
PdfPCell cell = new PdfPCell(new Paragraph(data[i]));
columnTable.addCell(cell);
}
// add columnTable for last column into main table
table.addCell(columnTable);
return table;
}

Categories

Resources