iText: Set height of table cell with image - java

I created a table with iText 5.5.13.2 (latest iText5 version) and I'm filling it with text and images that are read from a specific folder on the same PC:
Paragraph p = new Paragraph();
p.add(new Phrase("This is a new paragraph!"));
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
for(int i=0;i<imageArr.size();i++) { //imageArr.size()%2==0!
PdfPCell cell = new PdfPCell();
String name = imageArr.get(i);
String path = imgFolder + File.separator + name;
File f = new File(path);
if(f.isFile()) {
Image img = Image.getInstance(path);
//cell.setCalculatedHeight(50);
cell.addElement(img);
} else {
cell.addElement(new Phrase(name));
}
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setHorizontalAlignment(Element.ALIGN_MIDDLE);
//cell.setCalculatedHeight(50);
table.addCell(cell);
}
p.add(table);
doc.add(p);
Both columns in the table use the same width (which is great) and big images are automatically resized to fit the width (which is also great), the only thing that's not working:
The cells should all be a certain height and the big images should resize accordingly (while still keeping the proper height/width ratio). It doesn't seem to matter if I use setCalculatedHeight before or after I add the image to the cell (only doing one or the other, see code above), the cell always sets its height according to the image's height, so rows with only text or images in landscape format are always smaller than rows with images in portrait format.
Small images are also resized (stretched), even while using img.setScaleToFitLineWhenOverflow(false) and img.setScaleToFitHeight(false), but even then the height isn't set properly.
I already tried to use a Chunk (cell.addElement(new Chunk(img, 0, 0))) but then the images are tiny and my height setting is still ignored.
How do I set the cell's height and make the images resize accordingly?

I managed to find a solution. A lot of testing was involved and even now I'm not 100% sure why it was behaving the way it did most of the time.
First of all: Do not add the element with addElement because once you call this with a PdfPCell, iText switches from "Text Mode" (seems to affect images too) to "Composite Mode" and from then on ignores all the alignment,... settings for that cell, including horizontal alignment for text - you can find a more detailed explanation by the original iText developer here (with examples here). Instead do whatever you want to do with the Image first and only then create the PdfPCell with that image. Afterwards the cell can be edited - using the table.getDefaultCell() won't work though, the changes to it won't have any effect on the cells created with the code below.
My working code:
float docWidth = doc.getPageSize().getWidth() - doc.leftMargin() - doc.rightMargin();
float docHeight = doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin();
float docWidthDiv2 = docWidth/2 - 10;
float docHeightDiv2 = docHeight/2 - 10;
PdfPCell cell = null;
if(f.isFile()) {
Image img = Image.getInstance(path);
//img.scaleAbsolute(100, 50);
if(img.getWidth() < docWidthDiv2 && img.getHeight < docHeightDiv2) {
cell = new PdfPCell(img, false);
} else {
cell = new PdfPCell(img, true);
}
} else {
cell = new PdfPCell(new Phrase(name));
}
cell.setFixedHeight(50); //"setCalculatedHeight" doesn't work
Why do I compare the image's width to docWidthDiv2 and the image's height to docHeightDiv2?
There are a lot of combinations for setting the cell's height but none show 100% of the behavior I expected: Really big images should be scaled down to fit the width of the column (more important for images in landscape mode) but also respect the cell's fixed height (more important for images in portrait mode), while still keeping their aspect ratio. Small images that already fit the cell comfortably should not be scaled at all.
The documentation for new PDfPCell(Image image, boolean fit) describes the fit parameter with:
true to fit the image to the cell
In my case true resizes the image (while still respecting its aspect ratio and the cell's height) until it touches two opposite sides of the cell, hence: Big images are reduced in size and small images are stretched.
With false the aspect ratio of the image and the cell's height are still respected but while small images keep their size, big images in landscape mode "bleed" into the neighboring cell (and setScaleToFitLineWhenOverflow doesn't help) and big images in portrait mode might not even be displayed at all (when they're too tall for the cell).
To not stretch small images but decrease the size of big images, a combination of both is needed. I only added the -10, so a potential default padding won't mess with it. If you want to add text before or after the table, then you have to deduct its height from docHeightDiv2 too.
As mentioned, there are also other combinations I tested, the most important information I took away from it:
If the cell's height is set before the image is added, then the image'll overwrite the height, no matter if it's smaller (cell shrinks in height) or bigger (cell's height increases) than the cell.
There are a couple of combinations that can be used, between the parameter, setting the image size and setting the cell's height but with most of them the images either keep their original size (e.g. 2000x1000 won't be completely visible on the page) or they're increased in size until they touch two opposite sides of the cell (which also increases the height of the cell). In the end there's only one combination left that's still useful (in my opinion) - an example:
img.scaleAbsolute(100, 50);
cell = new PdfPCell(img, false);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE); //"center" doesn't work here
cell.setHorizontalAlignment(Element.ALIGN_CENTER); //"middle" doesn't work here
cell.setFixedHeight(150);
This'll create an image with a size of 100x50 (the original aspect ratio is ignored) in the center of a cell that's 150 units tall (= padding of 50 units above and below the image).
Additional information about iText's table:
Columns share the available width of the table equally and there's no need to change it, even if the first cell contains a really small image and the second a really big one. The only thing that you have to pay attention to, in that regard, is the number of cells that are added - rows always have to be completely filled, so a table with 3 columns has to contain 3 cells per row, otherwise that row won't be printed into the pdf file (the same way an empty new page also won't be printed). It's possible to create empty extra cells to fill the rest of the row:
PdfPCell extra = new PdfPCell();
extra.setFixedHeight(50);
table.addCell(extra);

Related

Get width of an Excel column in pixels instead of the default unit of measurement

It appears from some experiments I performed and from reading this page that the default units of measurement of the column width and row height in Excel are not pixels or even the standard metric such as centimeters but they are the number of characters that will fit in the space.
I am using Aspose Cells for Java. How do I get the width of a column in pixels?
Well, you may try to use Cells.getColumnWidthPixel() to get a column's width in the units of pixel, see the sample code for your reference.
e.g
Sample code:
Workbook wb = new Workbook("Book1.xlsx");
Worksheet ws = wb.getWorksheets().get(0);
Cells cells = ws.getCells();
//Get the second column's width in pixels, i.e, B.
int colwidth = cells.getColumnWidthPixel(1);
System.out.println(colwidth);
Similarly you may try to use Cells.getRowHeightPixel() to get the row height in pixel.
I am working as Support developer/ Evangelist at Aspose.

Image overlay on pdf using itext java

I am trying to overlay an image on PDF pages. When I try to do that using adobe acrobat and select vertical distance from top and left equal to 0, then image overlays correctly at the required location.
I am trying to achieve the same using iText API but can't seem to position the image at correct location on the pdf.
The values for position are trail and error. The size of the pdf is 612X792 and the size of the image is 1699.0x817.0 so I scaled the image to fit the pdf size.
The left of the image and pdf align correctly but the tops have issue. I tried with all the values and somehow 792/2+100 matches this but again will change in case I get a different pdf or image.
Somehow adobe reader is able to do that. Is there a way to align left and top in iText or any other library.
The pdf is existing pdf generated from some other source.
Updated source code
public void manipulatePdfNoTransparency(String inputFileName,
String outputfileName, String overlayFilePath,
int altPage) throws IOException, DocumentException {
System.out.println("outputfileName :"+outputfileName);
PdfReader reader = new PdfReader(inputFileName);
int n = reader.getNumberOfPages();
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputfileName));
stamper.setRotateContents(false);
// image watermark
Image img = Image.getInstance(overlayFilePath);
float yOffset=calculateYOffset(reader.getPageSize(1).getWidth(), reader.getPageSize(1)
.getHeight(),img.getWidth(),img.getHeight());
img.scaleToFit(reader.getPageSize(1).getWidth(), reader.getPageSize(1)
.getHeight());
Rectangle pagesize;
float x, y;
// loop over every page
//int i=1;
pagesize = reader.getPageSize(1);
x = (pagesize.getLeft() + pagesize.getRight()) / 2;
y = (pagesize.getTop() + pagesize.getBottom()) / 2;
img.setAbsolutePosition(0,yOffset);
for (int i = 1; i <= n; i = i + altPage) {
stamper.getUnderContent(i).addImage(img);
}
stamper.close();
reader.close();
System.out.println("File created at "+outputfileName);
}
public static float calculateYOffset(float pdfWidth,float pdfHeight, float originalImageWidth,float originalImageHeight) {
// size of image 1699.0x817.0
// size of pdf 612X792
//This means that the scaled image has a height of 817 * (612/1699) = ca. 294.3 PDF coordinate system units.
System.out.println("pdfWidth : "+pdfWidth+ " pdfHeight : "+pdfHeight+" originalImageWidth : "+originalImageWidth+" originalImageHeight : "+originalImageHeight);
float scaledImageHeight = originalImageHeight*pdfWidth / originalImageWidth;
//The image shall be positioned on the page by putting its top left corner onto the top left corner of the page.
//Thus, the x coordinate of its lower left corner is 0, and the y coordinate of its lower left corner is
//the y coordinate of the upper left corner of the page minus the height of the scaled image,
//i.e. ca. 792 - 294.3 = 497.7.
float yOffset = pdfHeight-scaledImageHeight;
System.out.println("yoffset : "+ yOffset);
return yOffset;
}
First let's take a look at this line:
img.scaleToFit(
reader.getPageSize(1).getWidth(),
reader.getPageSize(1).getHeight());
The scaleToFit() method resizes an images keeping the aspect ratio intact. You seem to overlook that, so let me give you an example of what it means to keep the aspect ratio intact.
Suppose that you have an image img400x600 that measures 400 x 600 user units, and you scale that image to fit a rectangle of 200 x 10,000 user units:
img400x600.scaleToFit(200, 10000);
What will be the size of image400x600? You seem to think that the size will be 200 x 10,000, but that assumption is incorrect. The new size of the image will be 200 x 300, because the aspect ratio is width = 0.66666 * height.
You complain that the size of the image doesn't equal the size of the page when you use scaleToFit(), but that is normal if the aspect ratio of the image is different from the aspect ratio of the page.
If you really want the image to have the same size of the page, you need to use the scaleAbsolute() method:
img.scaleAbsolute(
reader.getPageSize(1).getWidth(),
reader.getPageSize(1).getHeight());
However, this might result in really distorted images, because scaleAbsolute() doesn't respect the aspect ratio. For instance: I have seen developers who used scaleAbsolute() on portraits of people, and the result was that the picture of these people became ugly; either their head became extremely fat, or it became extremely thin depending on the different in aspect ratio.
Now let's take a look at this line:
img.setAbsolutePosition(0,y+100);
That is a very strange line. You are making the assumption that the x coordinate of the lower left corner is 0; I understand that y + 100 was obtained through trial and error.
Let's see what the official documentation has to say about defining the offset of objects added to an existing PDF document. There are several FAQ items on this subject:
Where is the origin (x,y) of a PDF page?
How to position text relative to page?
How should I interpret the coordinates of a rectangle in PDF?
...
You currently only look at the value of the /MediaBox (you obtain this value using the getPageSize() method), and you ignore the /CropBox (in case it is present).
If I were you, I'd do this:
Rectangle pageSize = reader.getCropBox(pageNumber);
if (pageSize == null)
pageSize = reader.getPageSize(pageNumber);
Once you have the pageSize, you need to add the take into account the offset when adding content. The origin might not coincide with the (0, 0) coordinate:
img.setAbsolutePosition(pageSize.getLeft(), pageSize.getBottom());
As you can see: there is no need for trial and error. All the values that you need can be calculated.
Update:
In the comments, #mkl clarifies that #Gagan wants the image to fit the height exactly. That is easy to achieve.
If the aspect ratio needs to be preserved, it's sufficient to scaleToFit the height like this:
img.scaleToFit(100000f, pageSize.getHeight());
In this case, the image won't be deformed, but part of the image will not be visible.
If the aspect ratio doesn't need to be preserved, the image can be scaled like this:
img.scaleAbsolute(pageSize.getWidth(), pageSize.getHeight());
If this still doesn't answer the question, I suggest that the OP clarifies what it is that is unclear about the math.
In a comment to the question I mentioned
somehow 792/2+100 matches this - actually that is off by about 1.7. You only need very simple math to calculate this.
and the OP responded
when you say it is off by 1.7 and simple math is required to calculate this. could you please let me know what math and how you arrived at 1.7.
This answer explains that math.
Assumed requirements
From the question and later comments by the OP I deduced these requirements:
An image shall be overlayed over a PDF page.
The image for this shall be scaled, keeping its aspect ratio. After scaling it shall completely fit onto the page and at least one dimension shall equal the corresponding page dimension.
It shall be positioned on the page by putting its top left corner onto the top left corner of the page, no rotation shall be applied.
The crop box of the PDF page coincides with the media box.
Calculation at hand
In the case at hand, the size of the pdf is 612X792 and the size of the image is 1699.0x817.0. Furthermore, the OP's comments imply that the bottom left corner of the page actually is the origin of the coordinate system.
To scale the horizontal extent of the image to exactly fit the page, one has to scale by 612/1699. To scale the vertical extent to exactly fit the page, one has to scale by 792/817. To make the whole image fit the page with aspect ration kept, one has to use the smaller scaling factor, 612/1699. This is what the OP's
img.scaleToFit(reader.getPageSize(1).getWidth(),reader.getPageSize(1).getHeight());
does, assuming the crop box coincides with the media box.
This means that the scaled image has a height of 817 * (612/1699) = ca. 294.3 PDF coordinate system units.
When positioning an image on a PDF page, you usually do that by giving the coordinates where the bottom left corner of the image shall go.
The image shall be positioned on the page by putting its top left corner onto the top left corner of the page. Thus, the x coordinate of its lower left corner is 0, and the y coordinate of its lower left corner is the y coordinate of the upper left corner of the page minus the height of the scaled image, i.e. ca. 792 - 294.3 = 497.7.
Thus, the scaled image shall be positioned at (0, 497.7).
The numbers the OP found by trial and error are 0 for x and middle height plus 100 for y. The middle height is (792 + 0)/2 = 396. Thus, he uses the coordinates (0, 496) which (see above) vertically are off by ca. 1.7.

Libgdx aligning Bitmap font to top right of the screen

So since I seem to can't put font into a Table and expand it to top and right, I wonder what is the solution to draw fonts on top right of the screen.
I'm trying with this:
highScoreFont.draw(batch, "" + getHighScore, Gdx.graphics.getWidth() - 1070, Gdx.graphics.getHeight() - 650);
which aligns it perfectly when I'm testing it on my Xperia Z1 which has resolution of 1920x1080. But when I test it on Nexus S which is 800x400 the alignment is completly wrong, the font draws itself in the on the bottom left part of the screen.
Any solutions?
Using scene2d, you can use a BitmapFont with Tables, you just need to use a Label, not the BitmapFont directly.
BitmapFont font = ...;
Label label = new Label(new LabelStyle(font, Color.WHITE));
Table table = new Table();
table.add(label).expand().top().right();
This is preferred, as scenes will size to your device and you won't have to worry about the device's screen size.
Using Gdx.graphics.getWidth() returns the device's width, not necessarily your viewport's width, so positioning elements using that value will result in inconsistencies across devices. Hardcoding positions typically becomes very difficult to maintain, but if you want to go this route I'd suggest looking into positioning elements based on the viewport size, not the value returned from Gdx.graphics.

iText Maximum Font Size

I'm using a fixed cell height to create a table.
If the font size is too large, the text is not visible in the table.
Is there a built-in function in iText that automatically reduces the font size to the maximum possible size, or do I have to implement this by myself?
Automatic font size is only possible in the context of AcroForm text fields. When you define the font size of a text field as 0, then a font size is chosen that fits the rectangle. In the case of a fixed cell height in a table, you are responsible to make sure that the text fits.
If you're concerned about the height, please take a look at the FitTextInRectangle example:
BaseFont bf = BaseFont.createFont();
int textHeightInGlyphSpace = bf.getAscent(text) - bf.getDescent(text);
float fontSize = 1000f * fixedHeight / textHeightInGlyphSpace;
This example was written in answer to Correct text position center in rectangle iText
If you're concerned about the width, then you need to use the getWidthPoint() method as explained here: How to calculate the string width in iText?
BaseFont bf = BaseFont.createFont();
float width = bf.getWidthPoint("My text", myFontSize);
You'll need to make sure that width doesn't exceed the width of the cell. To achieve this, you'll need to adjust myFontSize.
See my answer to this question: How to choose the optimal size for a font?

Resize font based on string length

From an xml file, I'm given a width, height and id. All of them can and do vary very quickly. Now, I'm asked to draw a rectangle using the width and height (an easy task), and place the id at its center. The id must not overflow out of the rectangle it's contained it.
For single-character strings, this is also easy - set the font size to the height, play a bit with the x position maybe, and it's centered. The problem is when it's multi-character strings.
So given a width and height and a string, how can you determine what font-size the string should appear in? Assume you have every bit of information you need on the rectangle you're drawing the string in.
[Edit]: I'm using the Graphics 2D class to draw everything.
Start with selecting a Font at your preferred (i.e. maximum) size.
Grab the FontRenderContext from your Graphics2D object using getFontRenderContext.
Use getStringBounds() on the Font to be rendered to get a Rectangle2D object for the specific String to be rendered. That object describes the final size of the String using that Font
Check if the size specified by that Rectangle2D is small enough.
4a. If it is small enough, you're done. Use the last Font you've checked.
4b. If it is too big, use Font.derive() to produce a smaller version of the Font and continue to use that and loop back to 3.
Don't quite have the time to give you a full working example, but here are a couple pointers that should get you going in the right direction. The graphics object you are using to draw with has a getFontMetrics() method, one of the methods on FontMetrics is stringWidth(String str) which gives you the width of a string in the current Font.
If the width is too big for your rectangle set the Font on the Graphics object to the same font just with a smaller size until it fits.
To horizontally center a string in a container (learned long ago in typing class in high school):
(rectangleWidth / 2) - (stringWidth / 2)
http://download.oracle.com/javase/1.5.0/docs/api/java/awt/FontMetrics.html
To create a Font with a smaller size, something like:
Font font = graphics.getFont();
Font smallerFont = font.derive(font.getSize() - 1);
graphics.setFont(smallerFont);
Hope this gets you going in the right direction.
I would recommend for this problem to remove as many unknowns as possible. In this case, the problem chiefly is that font characters can vary in width... well most. That's why I would use a good monospace font like courier new for the ID, that way you know what the width of each character is, you know the width of your rectangle and you know the number of characters in your string. You can simply reduce the pixel size of each character will till your string fits the available width.
Example, if the width of each character is 12px and you have 10 characters in your ID, then you need 120px to fit everything in. If you only have 80px available, it's simple math 80/10 = 8px font-size (reduce half a pixel for padding if you want.
Just my suggestion.

Categories

Resources