Align Text and Image vertically with iText 2 - java

I'm trying to print an Image and a text next to each other into a PdfPCell. The image is bigger than the font size, so the row height is increased. iText renders the Text at the bottom of the baseline (First example).
But I want the text to be vertically aligned in the middle of the cell (Second example).
What can I do to change this? I know I can change the alignment of the cell, but that doesn't change anything.
PdfPCell getImageAndText(byte[] image, String text, int originalDimension){
final Image pdfImg = Image.getInstance(image);
//Scale to 16pt.
pdfImg.scalePercent(16 * 100f / originalDimension);
Phrase image = new Phrase(new Chunk(pdfImg, 0, 0));
//Create Cell with image
final PdfPCell cell = new PdfPCell(image);
//Add text to cell
cell.addElement(new Phrase(text, getFont()));
return cell;
}
I am using iText 2.1.7

Related

how can i position content at specified position in itext 7

I just started using this library.
How can i position text in a cell at middle and at bottom?
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
Paragraph para = new Paragraph("Test").setFont(font);
Table table = new Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
Cell cell = new Cell();
cell.setMinHeight(100);
cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
cell.add(para);
cell.add(new Paragraph("test")).setVerticalAlignment(VerticalAlignment.BOTTOM);
table.addCell(cell);
Currently setting the vertical alignment the content is aligned to the bottom. The output:
How can I achieve the position of text at middle and bottom?
Like this with in the same cell:
Thanks.
PdfFont font = PdfFontFactory.createFont(StandardFonts.HELVETICA_BOLD);
Paragraph para = new Paragraph("Test").setFont(font);
Table table = new
Table(UnitValue.createPercentArray(1)).useAllAvailableWidth();
table.setHorizontalAlignment(HorizontalAlignment.CENTER);
table.setTextAlignment(TextAlignment.CENTER);
Cell cell = new Cell();
cell.setMinHeight(100);
cell.setVerticalAlignment(VerticalAlignment.MIDDLE);
cell.add(para);
cell.add(new Paragraph("test")).setVerticalAlignment(VerticalAlignment.BOTTOM);
table.addCell(cell);

PDF Cell Vertical Alignment with com.lowagie.text

I am using com.lowagie.text to create PDF in my code. All is working fine except I am trying to align my cell content vertically. I want cell text to be in the middle of the cell height.
This is my code
PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
Here ,horizontal alignment is working fine but vertical alignment is not effective.
I'm not too sure as to why, but this works for me (vertical center alignment):
String headingLabel = "Test";
Paragraph heading = new Paragraph(headingLabel,
new Font(helvetica, 28, Font.NORMAL, new BaseColor(0, 0, 0)));
Float textWidth = ColumnText.getWidth(heading);
Float maxAllowed = 630f;
while (maxAllowed < textWidth) {
fontSize -= 2;
heading = new Paragraph(headingLabel,
new Font(helvetica, fontSize, Font.NORMAL, new BaseColor(0, 0, 0)));
textWidth = ColumnText.getWidth(heading);
}
heading.setAlignment(Element.ALIGN_CENTER);
PdfPCell titleCell = new PdfPCell();
titleCell.setHorizontalAlignment(Element.ALIGN_CENTER);
titleCell.setVerticalAlignment(Element.ALIGN_TOP);
titleCell.addElement(heading);
titleCell.setFixedHeight(65f);
headerTable.addCell(titleCell);
ALIGN_MIDDLE has integer value 5 defined in the the iText code. Please pay attention while you are writing ALIGN_MIDDLE a tip comes up "Possible value for vertical element." It means if your element is in vertical orientation then it will work as it calculates the center of the element. My suggestion is to replace ALIGN_MIDDLE with ALIGN_CENTER so your code will look like:
cell.setVerticalAlignment(Element.ALIGN_CENTER);
Try this:
PdfPCell cell = new PdfPCell(new Phrase(value, fontValueNew));
cell.setBorder(o);
cell.setBackgroundColor(new Color(233,232,232));
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.setVerticalAlignment(Element.ALIGN_CENTER);

How to get the Content added to the cell that doesn't fit the height of the cell?

Working with iText and using table cells.
I have 25 cells (columns) in a table.
The content of each column is rotated 90 degree and is required to be fitted to the height of each cell.
In some cases when the length of the content exceeds the height of the cell, not all the content is visible (Only the part of content is visible that is fitted to the height of the cell, the rest is dropped). I want to get that dropped content and want to show it in the next adjacent cell.
The following code is used -
PdfPCell cell;
for(int i = 0;i< 25;i++)
{
if(locs.get(i) == null)
{
cell = new PdfPCell();
cell.setBorder(0);
table.addCell(cell);
}
else
{
Font font = new Font(FontFamily.HELVETICA, 9, Font.BOLD, BaseColor.BLACK);
cell = new PdfPCell(new Phrase(locs.get(i), font));
cell.setRotation(90);
cell.setBorder(0);
cell.setFixedHeight(110f);
//cell.setMinimumHeight(10f);
table.addCell(cell);
}
}
So if the value of locs.get(i) is greater then the height of the cell (cell height is fixed to 110f in the above code), some content that doesn't fit gets dropped to be shown in the view.
How to get that content and show it to the adjacent cell ?
The method used that solved the purpose is the following:
PdfPCell cell;
for(int i = 0;i< 25;i++)
{
if(locs.get(i) != null)
{
Font font = new Font(FontFamily.HELVETICA, 9, Font.BOLD, BaseColor.BLACK);
cell = new PdfPCell(new Phrase(locs.get(i), font));
cell.setRotation(90);
cell.setBorder(0);
cell.setFixedHeight(110f);
cell.setColspan(2);
table.addCell(cell);
}
else
{
cell = new PdfPCell();
cell.setBorder(0);
table.addCell(cell);
}
}
So setting the colspan to 2 ensures that if the contents exceeds the length of the first column then move the remaining contents to the next column of the cell (One cell having two columns now after adding the colspan of 2).
If anyone knows the better way to do the same thing then you are welcome!

Auto size height for rows in Apache POI

I am inputting values into a spreadsheet using Apache POI. These values have newlines, and I was able to use this code successfully:
CellStyle style = cell.getCellStyle()
style.setWrapText(true)
cell.setCellStyle(style)
Unfortunately, while the text is wrapping correctly, the rows are not always growing in height enough to show the content. How do I ensure that my rows are always the correct height?
currentRow.setHeight((short)-1)
Works for XSSFCell and Excel 2013
HSSFWorkbook workbook=new HSSFWorkbook();
HSSFSheet sheet = workbook.createSheet("FirstSheet");
HSSFRow rowhead= sheet.createRow((short)0);
HSSFCellStyle style = workbook.createCellStyle();
style.setWrapText(true);
row.setRowStyle(style);
row.getCell(0).setCellStyle(style);
The above code will generate dynamic height of rows.
The only way I got this to work was write my own implementation to calculate the row height. The code is now released as the Taro project, so you could use that. It has numerous convenience methods to let you write an Excel file in far fewer lines of code.
If you prefer to put the implementation in your own code, you can find it in the SpreadsheetTab class. There is an autoSizeRow(int rowIndex) method half way down. It basically iterates down the row and for each cell finds the number of lines of text, then uses the font size to calculate the optimal cell height. It then sets the row height to the height of the tallest cell.
See all this link, which provides some code to manually calculate the correct height for a row, based on the column width and cell content. I've not personally tested it. Also pasted below for convenience:
// Create Font object with Font attribute (e.g. Font family, Font size, etc) for calculation
java.awt.Font currFont = new java.awt.Font(fontName, 0, fontSize);
AttributedString attrStr = new AttributedString(cellValue);
attrStr.addAttribute(TextAttribute.FONT, currFont);
// Use LineBreakMeasurer to count number of lines needed for the text
FontRenderContext frc = new FontRenderContext(null, true, true);
LineBreakMeasurer measurer = new LineBreakMeasurer(attrStr.getIterator(), frc);
int nextPos = 0;
int lineCnt = 0;
while (measurer.getPosition() < cellValue.length())
{
nextPos = measurer.nextOffset(mergedCellWidth); // mergedCellWidth is the max width of each line
lineCnt++;
measurer.setPosition(nextPos);
}
Row currRow = currSht.getRow(rowNum);
currRow.setHeight((short)(currRow.getHeight() * lineCnt));
// The above solution doesn't handle the newline character, i.e. "\n", and only
// tested under horizontal merged cells.
cell.getRow().setHeight((short) -1);
Worked for HSSFCell in apache poi 3.9 or above
It works in Excel 2010.
I set the limit of cell length of 50 characters
Row row = sheet.createRow(0);
CellStyle style = workbook.createCellStyle();
style.setWrapText(true);
if (data.length() > 50) {
for (int i = 1; i <= Math.abs(data.length() / 50); i++) {
data = data.substring(0, i * 50) + "\n" + data.substring(i * 50);
}
Cell cell = row.createCell(0);
row.setRowStyle(style);
cell.setCellStyle(style);
cell.setCellValue(data);
sheet.autoSizeColumn(0);
}
In my case a robust solution was to calculate the number of lines and set the row height to a multiple of the default row height:
int numberOfLines = cell.getStringCellValue().split("\n").length;
row.setHeightInPoints(numberOfLines*sheet.getDefaultRowHeightInPoints());
You can't adjust cell height directly.
But you can change the row's height
final HSSFSheet fs = wb.createSheet("sheet1");
final HSSFRow row0 = fs.createRow(0);
final HSSFCell cellA1 = row0.createCell(0);
row0.setHeight((short)700);
Row aitosize work for me:
cell.getRow().setHeight((short)0);
Here 0 for calculate autoheight.
Workaround for “LibreOffice Calc“ and “WPS Spreadsheet” with auto height for merged sells.
I add a column out to the right of a main document (In my case it was 32 column)
Set width as all merged cells with same text.
Set style WrapText to true
Set style to Align Top
Copy content which will be displayed in the merged cells
Set that column to be hidden
Set a row height = -1
A sample of code:
private void applyRowHightWorkaroundForMergedCells(HSSFCell cell0) {
HSSFSheet sheet = cell0.getSheet();
HSSFRow row = cell0.getRow();
String value = cell0.getStringCellValue();
HSSFCell cell = row.createCell(32);
sheet.setColumnWidth(32, 32000);
cell.getCellStyle().setWrapText(true);
cell.getCellStyle().setVerticalAlignment(VerticalAlignment.TOP);
cell.setCellValue(value);
sheet.setColumnHidden(32, true);
row.setHeight((short) -1);
}
//we can use column width for sheet
Ex: sheet.setColumnWidth(0, 2000);

Changing size of cell comments in Apache POI

I use the following java code to successfully generate cell comments in Apache POI
public static void setComment(String text, Cell cell) {
final Map<Sheet, HSSFPatriarch> drawingPatriarches = new HashMap<Sheet, HSSFPatriarch>();
CreationHelper createHelper = cell.getSheet().getWorkbook().getCreationHelper();
HSSFSheet sheet = (HSSFSheet) cell.getSheet();
HSSFPatriarch drawingPatriarch = drawingPatriarches.get(sheet);
if (drawingPatriarch == null) {
drawingPatriarch = sheet.createDrawingPatriarch();
drawingPatriarches.put(sheet, drawingPatriarch);
}
Comment comment = drawingPatriarch.createComment(new HSSFClientAnchor(100, 100, 100, 100, (short)1, 1, (short) 10, 5));
comment.setString(createHelper.createRichTextString(text));
cell.setCellComment(comment);
}
I copied it from creating cell comments using HSSFClientAnchor in apache poi. Thank you Erik!
How can I change the size of the comment to 300 pixels width and 100 pixels height?
Thanks!
From what I can tell there's not an easy way since comment anchor points are specified by cell (column, row parameters) and offset into cell (dx, dy parameters). So you need to compute the width/height of the cells to figure out the second cell coordinates and then the offsets into that cell to make it exactly the pixel size you want.
Busy Developers' Guide to HSSF and XSSF Features
// When the comment box is visible, have it show in a 1x3 space
ClientAnchor anchor = factory.createClientAnchor();
anchor.setCol1(cell.getColumnIndex());
anchor.setCol2(cell.getColumnIndex()+1);
anchor.setRow1(row.getRowNum());
anchor.setRow2(row.getRowNum()+3);
Just change the values for setCol2 and setRow2.
You can assign a column width for any cell as follows:
sheet.setColumnWidth(0, 1000);

Categories