PDF Cell Vertical Alignment with com.lowagie.text - java

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);

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);

Text not getting center aligned horizontally in itext? [duplicate]

I have a C# application that generates a PDF invoice. In this invoice is a table of items and prices. This is generated using a PdfPTable and PdfPCells.
I want to be able to right-align the price column but I cannot seem to be able to - the text always comes out left-aligned in the cell.
Here is my code for creating the table:
PdfPTable table = new PdfPTable(2);
table.TotalWidth = invoice.PageSize.Width;
float[] widths = { invoice.PageSize.Width - 70f, 70f };
table.SetWidths(widths);
table.AddCell(new Phrase("Item Name", tableHeadFont));
table.AddCell(new Phrase("Price", tableHeadFont));
SqlCommand cmdItems = new SqlCommand("SELECT...", con);
using (SqlDataReader rdrItems = cmdItems.ExecuteReader())
{
while (rdrItems.Read())
{
table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont));
double price = Convert.ToDouble(rdrItems["price"]);
PdfPCell pcell = new PdfPCell();
pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont));
table.AddCell(pcell);
}
}
Can anyone help?
I'm the original developer of iText, and the problem you're experiencing is explained in my book.
You're mixing text mode and composite mode.
In text mode, you create the PdfPCell with a Phrase as the parameter of the constructor, and you define the alignment at the level of the cell. However, you're working in composite mode. This mode is triggered as soon as you use the addElement() method. In composite mode, the alignment defined at the level of the cell is ignored (which explains your problem). Instead, the alignment of the separate elements is used.
How to solve your problem?
Either work in text mode by adding your Phrase to the cell in a different way.
Or work in composite mode and use a Paragraph for which you define the alignment.
The advantage of composite mode over text mode is that different paragraphs in the same cell can have different alignments, whereas you can only have one alignment in text mode. Another advantage is that you can add more than just text: you can also add images, lists, tables,... An advantage of text mode is speed: it takes less processing time to deal with the content of a cell.
private static PdfPCell PhraseCell(Phrase phrase, int align)
{
PdfPCell cell = new PdfPCell(phrase);
cell.BorderColor = BaseColor.WHITE;
// cell.VerticalAlignment = PdfCell.ALIGN_TOP;
//cell.VerticalAlignment = align;
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
return cell;
}
Here is my derivation of user2660112's answer - one method to return a cell for insertion into a bordered and background-colored table, and a similar, but borderless/colorless variety:
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BackgroundColor = color;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
private static PdfPCell GetCellForBorderlessTable(Phrase phrase, int align)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BorderWidth = PdfPCell.NO_BORDER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
These can then be called like so:
Font timesRoman9Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, BaseColor.BLACK);
Font timesRoman9BoldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9, BaseColor.BLACK);
Phrase phrasesec1Heading = new Phrase("Duckbills Unlimited", timesRoman9BoldFont);
PdfPCell cellSec1Heading = GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, BaseColor.YELLOW);
tblHeadings.AddCell(cellSec1Heading);
Phrase phrasePoisonToe = new Phrase("Poison Toe Toxicity Level (Metric Richter Scale, adjusted for follicle hue)", timesRoman9Font);
PdfPCell cellPoisonToe = GetCellForBorderlessTable(phrasePoisonToe, Element.ALIGN_LEFT);
tblFirstRow.AddCell(cellPoisonToe);
I ended up here searching for java Right aligning text in PdfPCell. So no offense if you are using java please use given snippet to achieve right alignment.
private PdfPCell getParagraphWithRightAlignCell(Paragraph paragraph) {
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderColor( BaseColor.WHITE);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
return cell;
}
In getParagraphWithRightAlignCell pass paragraph
Thanks
Perhaps its because you are mixing the different ways to add the cells? Have you tried explicitly creating a cell object, massaging it however you want then adding it for every cell?
Another thing you could try is setting the vertical alignment as well as the horizontal.
cell.HorizontalAlignment = Element.ALIGN_RIGHT;

Need to make PDF sample with boxes as table columns by android app

I need to make PDF sample file just like the below image but I didn't find any suitable guide to do exactly like this. I have followed some links
http://itextpdf.com/examples/iia.php?id=102
Is there a way to draw a rectangle into a PdfPCell in iText (the Java version)?
but from the second link I didn't understand how could I make more likely to my requirement.
Thanks in advance.
It is unclear to me why you refer to this example: http://itextpdf.com/examples/iia.php?id=102
The PDF that is created with that example shows me in a Superman outfit. What is the link with creating a table with rounded borders?
Please take a look at the NestedTableRoundedBorder example. It creates a PDF that looks like this: nested_table_rounded_border.pdf
This construction consists of nested tables. The outer table only has one column, but we use it to create the rounded corners:
class RoundRectangle implements PdfPCellEvent {
public void cellLayout(PdfPCell cell, Rectangle rect,
PdfContentByte[] canvas) {
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cb.roundRectangle(
rect.getLeft() + 1.5f, rect.getBottom() + 1.5f, rect.getWidth() - 3,
rect.getHeight() - 3, 4);
cb.stroke();
}
}
This cell event is used like this:
cell = new PdfPCell(innertable);
cell.setCellEvent(roundRectangle);
cell.setBorder(Rectangle.NO_BORDER);
cell.setPadding(8);
outertable.addCell(cell);
The inner tables are used to create cells with or without borders, for instance like this:
// inner table 1
PdfPTable innertable = new PdfPTable(5);
innertable.setWidths(new int[]{8, 12, 1, 4, 12});
// first row
// column 1
cell = new PdfPCell(new Phrase("Record Ref:"));
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 2
cell = new PdfPCell(new Phrase("GN Staff"));
cell.setPaddingLeft(2);
innertable.addCell(cell);
// column 3
cell = new PdfPCell();
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 4
cell = new PdfPCell(new Phrase("Date: "));
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
// column 5
cell = new PdfPCell(new Phrase("30/4/2015"));
cell.setPaddingLeft(2);
innertable.addCell(cell);
// spacing
cell = new PdfPCell();
cell.setColspan(5);
cell.setFixedHeight(3);
cell.setBorder(Rectangle.NO_BORDER);
innertable.addCell(cell);
If some of the dimensions are quite like you want, it's sufficient to change parameters such as the widths array, the padding, the fixed height, etc.

add border to pdf page using itext

this is my source code. why am I not able to add border to my pdf page even after enabling borders for all sides? I've set border and its color too still I'm not able to add border.
void create() throws DocumentException,IOException{
// step 1
Document document = new Document();
// step 2
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.setPageSize(PageSize.LETTER);
document.setMargins(36, 72, 108, 180);
document.setMarginMirroring(false);
// step 3
document.open();
// step 4
Rectangle rect= new Rectangle(36,108);
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorder(2);
rect.setBorderColor(BaseColor.BLACK);
document.add(rect);
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 26, Font.UNDERLINE, BaseColor.BLACK);
Paragraph title= new Paragraph("CURRICULUM VITAE\n\n",font);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Font f1= new Font (Font.FontFamily.UNDEFINED, 13, Font.NORMAL, BaseColor.BLACK);
Paragraph info= new Paragraph("Name\n\nEmail\n\nContact Number",f1);
Paragraph addr= new Paragraph("Street\n\nCity\n\nPin",f1);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.spacingAfter();
PdfPCell cell = new PdfPCell(info);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
cell = new PdfPCell(addr);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
document.add(table);
document.add(new Chunk("\n"));
document.add(new LineSeparator(2f,100,BaseColor.DARK_GRAY,Element.ALIGN_CENTER,-1f));
You didn't define a border width.
You're adding the border only once. What if you want the border to appear on every page?
You can fix (1.) by adding:
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);
Note that I would remove the enableBorderSide() calls. You'll notice that you've used the setBorder() method in the wrong way.
To fix (2.), I would use a page event. Note that you can't use document.add() in a page event, so you'll have to do something as described in the DrawRectangle example that was written in answer to the question iText: PdfContentByte.rectangle(Rectangle) does not behave as expected
You didn't define a page size when creating the Document object, which means that iText will be using PageSize.A4. A couple of lines later, you use PageSize.LETTER. These values are immutable Rectangle objects. You can create a new Rectangle using the dimensions/coordinates of PageSize.A4 (or in your case: PageSize.LETTER). You can obtain the dimensions using the getWidth() and getHeight() method and the coordinates using getLeft(), getBottom(), getRight() and getTop().
Rectangle rect= new Rectangle(577,825,18,15); // you can resize rectangle
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorderColor(BaseColor.BLACK);
rect.setBorderWidth(1);
document.add(rect);

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!

Categories