POI - Fixed width of image in Excel cell - apache-poi

I followed the approach to add a new image with the POI.
cell.getRow().setHeight(img.getHeightForExcel());
sheet.setColumnWidth(cell.getColumnIndex(), img.getWidthForExcel());
final int picID = workBook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
/* Create the drawing container */
final XSSFDrawing drawing = (XSSFDrawing) sheet.createDrawingPatriarch();
// ========adding image START
final XSSFClientAnchor myAnchor = new XSSFClientAnchor();
myAnchor.setAnchorType(AnchorType.DONT_MOVE_AND_RESIZE);
/* Define top left corner, and we can resize picture suitable from there */
myAnchor.setCol1(cell.getColumnIndex()); // Column start
myAnchor.setRow1(rowNum - 1); // Row start
myAnchor.setCol2(cell.getColumnIndex() + 2); // Column end (covers two columns)
myAnchor.setRow2(rowNum); // Row end
/* Invoke createPicture and pass the anchor point and ID */
final XSSFPicture myPicture = drawing.createPicture(myAnchor, picID);
In principal this works quite well. I specify the width of the column at the beginning with the width of the image. (The height as well).
The major problem I'm facing is that as soon as I run autoadjust like
for (; i < max; i++) {
xlsWorkbook.getSheet().autoSizeColumn(i);
}
I get the problem that the first two columns are resized as well. But with this the width of the image is resized as well. Since the width might be quite long (or quite narrow) I don't want to affect the image size.
Is there a way to set the width of the image despite the column width?

If you don't want resizing the image when column widths are changing, then you cannot using that approach. This approach explicitly tells that the image shall be sized as the cell size it is anchored to. So if that cell size changes, the pictures size changes too.
You might think that ClientAnchor.AnchorType.DONT_MOVE_AND_RESIZE should protect the image from resizing. But this only is valuable when opened in Excel GUI. Apache poi does not respect ClientAnchor.AnchorType while auto sizing the columns. May be this will change in later versions. But in current version apache poi 5.0.0 it does not.
So to fulfill your requirement you set only a one cell anchor. That is only anchor.setCol1 and anchor.setRow1 as the upper left position of the picture. Then you need resizing the picture later to set the bottom right position. You must do that resizing after all column widths and row heights are set. So after auto sizing the columns. Else the resizing the columns will resizing the picture again.
Complete example:
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.util.IOUtils;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
class ImageTest {
public static void main(String[] args) throws Exception {
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet("My Sample Excel");
//FileInputStream obtains input bytes from the image file
InputStream inputStream = new FileInputStream("./logo.png");
//Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
//Adds a picture to the workbook
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
//close the input stream
inputStream.close();
//Returns an object that handles instantiating concrete classes
CreationHelper helper = wb.getCreationHelper();
//Creates the top-level drawing patriarch.
Drawing drawing = sheet.createDrawingPatriarch();
//Create an anchor that is attached to the worksheet
ClientAnchor anchor = helper.createClientAnchor();
//Set anchor type; only valuable in Excel GUI
anchor.setAnchorType(ClientAnchor.AnchorType.MOVE_DONT_RESIZE);
//Create an anchor with upper left cell only
anchor.setCol1(1); //Column B
anchor.setRow1(2); //Row 3
//Create a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
//Reset the image to the original size
//pict.resize(); // don't do this before autosize column
//Create cell in column B to auto sizing that column
Cell cell = sheet.createRow(0).createCell(1);
cell.setCellValue("12345678901234567890");
sheet.autoSizeColumn(1);
//Reset the image to the original size
//pict.resize();
//Reset the image to half the original size
pict.resize(0.5);
//Write the Excel file
FileOutputStream fileOut = null;
fileOut = new FileOutputStream("./myFile.xlsx");
wb.write(fileOut);
fileOut.close();
}
}

Related

Increasing height merged cells Apache POI

I am using Apache POI SXSSF to generate xlsx document. The document uses Times New Roman sizes 9 and 11, and the default cell width and height have been changed. The question is how to calculate the height of the merged cells so that all the text fits (the height of the cell must be dynamically set according to the given text)? The server running the application does not have a display, and this code is running in the IBM Integration Bus.
The solution from How to get the needed height of a multi line rich-text field (any font, any font size) having defined width using Java? is not suitable. The server running the application is missing a display and the string int ppi = java.awt.Toolkit.getDefaultToolkit().getScreenResolution(); returns an exception, and manually picking the ppi value is also not possible. If there is a display, everything works correctly.
And is there any way to use the "align center selection" function somehow?
I found that centering a selection gives a similar result as merging multiple cells horizontally, but I couldn't find an answer anywhere on how to use this in Apache POI. As a result, experimentally, I found out that in order to achieve this effect, you need to do the following things:
Create CellStyle; specify setWrapText(true) and setAlignment(HorizontalAlignment.CENTER_SELECTION) for it
Apply the style created in step 1 to all cells that need to be merged
Specify the value in the first cell
Code example:
Font font = wb.createFont(); // where wb - is SXSSFWorkbook object
font.setFontName("Times New Roman");
font.setFontHeightInPoints((short) 11);
CellStyle style = wb.createCellStyle();
style.setFont(font);
style.setWrapText(true);
style.setAlignment(HorizontalAlignment.CENTER_SELECTION);
for (int i = 0; i <= endCellNum - firstCellNum; i++){ // where endCellNum - number of last cell of selection and firstCellNum is number of first cell of selection
Cell cell = curRow.createCell(firstCellNum + i);
cell.setCellStyle(cs);
if (i == 0){
firstCell = cell;
}
}
firstCell.setCellValue(value);

How can I prevent my image from changing size when placing it on a spreadsheet (Aspose Cells)?

I have an image that is embedded in my solution and is used on the main form of a Winforms app, and also for pasting into a spreadsheet. The image size is 156X121.
I put it on the sheet like so:
var ms = new MemoryStream();
_logo.Save(ms, ImageFormat.Png);
ms.Position = 0;
pivotTableSheet.Pictures.Add(0, _grandTotalsColumnPivotTable, ms);
Yet when it is on the sheet, it stretches out and spills into neighboring cells, partially obscuring other data:
As you can see, the size is no longer 156X121. The height has been increased by 25%. Why? And how can I prevent that?
This code:
MessageBox.Show(string.Format("image height is {0}", _logo.Height));
MessageBox.Show(string.Format("image width is {0}", _logo.Width));
...showed me "126" as the height and "151" as the width, matching the image as it is in the project. So why is the original size changed? Is there a property I can set to leave the size alone and not stretch it? Or how can I prevent this gumbification of the image?
It's bizarre to me that the image is one size (126X151), its original size is purported to be 1.26" X 1.63", and its size after being scaled is 1.57" X 1.63".
Who or what is allowing this 25% increase in Height?
NOTE: If I select the "Reset" button in the image's "Size and Properties" dialog, it shrinks up as I want it to be, setting the Height "back" to 100% from 125%. Is there a way to do this "Reset" programmatically?
UPDATE
Based on the answer, I tried this:
var ms = new MemoryStream();
//_logo.Height = 121; <= cannot set; Height is a readonly property
_logo.Save(ms, ImageFormat.Png);
ms.Position = 0;
pivotTableSheet.Pictures.Add(0, _grandTotalsColumnPivotTable, ms);
Picture pic = pivotTableSheet.Pictures[0];
//Workbook.Worksheets[0].Pictures[0]; <= does not compile
pic.HeightScale = 100;
pic.WidthScale = 100;
(Workbook.Worksheets[0] does not compile for me).
It makes no difference; the image is still stretching vertically.
UPDATE 2
I realized I needed "Workbook" to be "workBook" due to this:
private static Workbook workBook;
...and so I tried this:
Picture pic = workBook.Worksheets[1].Pictures[0]; // Worksheet 0 is the data sheet that feeds the PivotTable and subsequently gets hidden, so need to use 1
pic.Height = 121;
pic.WidthScale = 100;
...but it still gumbifies the image vertically. So does replacing "pic.Height = 121" with "pic.HeightScale = 100;"
So this is the code currently, which adds the image, but in a vertically gumbified manner:
var ms = new MemoryStream();
//_logo.Height = 121; readonly
_logo.Save(ms, ImageFormat.Png);
ms.Position = 0;
pivotTableSheet.Pictures.Add(0, _grandTotalsColumnPivotTable, ms);
Picture pic = workBook.Worksheets[1].Pictures[0]; // Worksheet 0 is the data sheet that feeds the PivotTable
//pic.Height = 121;
pic.HeightScale = 100;
pic.WidthScale = 100;
Please use this code to reset it to original height.
Picture pic = wb.Worksheets[0].Pictures[0];
pic.HeightScale = 100;
pic.WidthScale = 100;
Note: I am working as Developer Evangelist at Aspose

Apache POI insert image without anchor

I'm creating Excel file in Java using Apache POI, it works but the inserted image is anchored to columns / rows. There are 2 issues with this method:
The image doesn't keep the original size (get stretched a little bit).
When resizing the columns/rows the image get stretched. Is there any way to insert an image to Excel without anchor? (same as using Excel / Insert / Picture)
I'm using the following example from Apache POI document page:
//create a new workbook
Workbook wb = new XSSFWorkbook(); //or new HSSFWorkbook();
//add picture data to this workbook.
InputStream is = new FileInputStream("image1.jpeg");
byte[] bytes = IOUtils.toByteArray(is);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_JPEG);
is.close();
CreationHelper helper = wb.getCreationHelper();
//create sheet
Sheet sheet = wb.createSheet();
// Create the drawing patriarch. This is the top level container for all shapes.
Drawing drawing = sheet.createDrawingPatriarch();
//add a picture shape
ClientAnchor anchor = helper.createClientAnchor();
//set top-left corner of the picture,
//subsequent call of Picture#resize() will operate relative to it
anchor.setCol1(3);
anchor.setRow1(2);
Picture pict = drawing.createPicture(anchor, pictureIdx);
//auto-size picture relative to its top-left corner
pict.resize();
//save workbook
String file = "picture.xls";
if(wb instanceof XSSFWorkbook) file += "x";
FileOutputStream fileOut = new FileOutputStream(file);
wb.write(fileOut);
fileOut.close();
Thanks for your answer.
Proably that because of this comment in method 'resize' javadoc:
Please note, that this method works correctly only for workbooks with the default font size (Arial 10pt for .xls and Calibri 11pt for .xlsx). If the default font is changed the resized image can be streched vertically or horizontally.

iText: add SVG tile as page to new PDF file

I'm trying to create a new PDF file using iText, and the new file should be composed of pages that are generated from an area within an SVG file (tile). And each generated page needs to have a 'drawing border' superimposed upon it, so that it appears as the top layer of each generated page. I think the superimposing can be achieved with the iText stamper, but examples I see work only with an existing PDF, which I don't have as I want to do all this on-the-fly to reduce the time required to generate the resulting PDF. I have a one page PDF file that represents the PDF layer to superimpose upon each page generated in the PDF.
I found an example on the net that divides the SVG canvas into tiles and creates separate PDF files from each tile. However, creating intermediate PDF files wastes time, as I need to read them in again to create the file I am trying to create (with the superimposed layer for each page).
I don't want to dump loads of code here, but here is the code sample that I used to generate one page PDF files for each SVG tile:
http://people.apache.org/~clay/batik/rasterizerTutorial.pdf (see page 5: SaveAsJPEGTiles.java)
As I am an iText newbie, maybe someone here has achieved something similar, or knows how to do this?
Thanks.
I'm using a ByteArrayOutputStream instead of the FileOutputStream, but when I try to combine this with iText's Document type, I keep getting an exception saying no pages in document - see code below. I think I need to add the ByteArrayOutputStream for each tile to the iText document so that it creates a new page for each tile, but I can't see how to do that from the iText API. Here's my code so far, but doesn't quite work:
package examples.aoi;
import java.io.*;
import java.awt.*;
import org.apache.batik.transcoder.TranscoderInput;
import org.apache.batik.transcoder.TranscoderOutput;
import org.apache.fop.svg.PDFTranscoder;
import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.pdf.PdfWriter;
public class FromCanvasToPDFPages {
PDFTranscoder trans = new PDFTranscoder();
public FromCanvasToPDFPages() {
}
public void tile(TranscoderInput input, TranscoderOutput output, Rectangle aoi) throws Exception {
trans.addTranscodingHint(PDFTranscoder.KEY_WIDTH, new Float(aoi.width));
trans.addTranscodingHint(PDFTranscoder.KEY_HEIGHT, new Float(aoi.height));
trans.addTranscodingHint(PDFTranscoder.KEY_AOI, aoi);
trans.transcode(input, output);
}
public static void main(String [] args) throws Exception {
FromCanvasToPDFPages p = new FromCanvasToPDFPages();
String in = "C:\\Documents and Settings/krell/My Documents/1.svg";
String svgURI = new File(in).toURL().toString();
TranscoderInput input = new TranscoderInput(svgURI);
String outputFilename = "canvasPages.pdf";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
TranscoderOutput output = new TranscoderOutput(baos);
int A4_landscape_width = 1103; // use proper dimensions from class when found
int A4_landscape_height = 780; // use proper dimensions from class when found
int documentWidth = 3309; // read this directly from canvas file (svg)
int documentHeight = 1560; // read this directly from canvas file (svg)
int columns = documentWidth / A4_landscape_width;
int rows = documentHeight / A4_landscape_height;
int tile_width = A4_landscape_width;
int tile_height = A4_landscape_height;
System.err.println(">>> Canvas document width = "+documentWidth);
System.err.println(">>> Canvas document height = "+documentHeight);
System.err.println(">>> A4 width = "+A4_landscape_width);
System.err.println(">>> A4 height = "+A4_landscape_height);
System.err.println(">>> canvas columns = "+columns);
System.err.println(">>> canvas rows = "+rows);
System.err.println(">>> tile_width = "+tile_width);
System.err.println(">>> tile_height = "+tile_height);
// Create A4 document to write tile data into
Document document = new Document(PageSize.A4_LANDSCAPE, 10, 10, 10, 10);
PdfWriter writer = PdfWriter.getInstance(document, baos);
// open the document
document.open();
// now process each tile, row by row, column by column until done
for (int row = 0; row < rows; row++) {
for (int column = 0; column < columns; column++) {
// get tile coordinates
Rectangle tile = new Rectangle(column*tile_width, row*tile_height, (column+1)*tile_width, (row+1)*tile_height);
p.tile(input, output, tile);
}
}
// now write the baos to disk:
OutputStream fileOutputStream = new FileOutputStream(outputFilename);
baos.writeTo(fileOutputStream);
// close stuff
fileOutputStream.flush();
fileOutputStream.close();
document.close();
baos.close();
System.exit(0);
}
}

LWUIT Table Layout embedded TextAreas

my goal is to display a Table through parsing an XML file.
I'm using a SAX Parser and the content has multirows and I want
the table width to fit to the display. Of course Y_AXIS scrolling would be ok.
Right now, I'm using the HTMLTableModel of src/com/sun/lwuit/html/ and it's corresponding HTMLTable. For this I declared it's methods public so I can access them. This works fine so far. This allows me to declare tables without knowing their size prematurely.
To allow multirows, I'm embedding TextAreas in the Cells.
Now the problem: The HTMLTable t needs t.setScrollableY(true), or else not all rows are shown.
This causes the table to be a bit to large in X direction, so the right border isn't shown.
Also the bottom border isn't shown all the time.
The container in which the table is embedded has BorderLayout.Y_AXIS.
Things I tried:
t.setPreferredW(mainContainer.getLayoutWidth()); This does reduce the size of the table, but then the table doesn't show all it's rows, like without t.setScrollableY(true).
t.setLayout(new BoxLayout(BoxLayout.Y_AXIS)) this causes an java/lang/ClassCastException.
Any ideas? Thanks in advance.
Excerpt from my code:
} else if (qName.equalsIgnoreCase("td")) {
if (sb.length() > 0) {
String sbt = new String(sb);
sb.delete(0, sb.length());
TextArea c = new TextArea(sbt);
c.setEditable(false);
c.getStyle().setFont(smallFont);
table.addCell(c, false, null);
}
} else if (qName.equalsIgnoreCase("tr")) {
debugPrint("Row closed.");
table.commitRow();
} else if (qName.equalsIgnoreCase("table")) {
HTMLTable t = new HTMLTable(table);
//without scrollable Y not all table rows are shown
t.setScrollableY(true);
//t.setPreferredW(screenWidth);
//this is verboten.
t.setLayout(new BoxLayout(BoxLayout.Y_AXIS));
mainContainer.addComponent(t);
tableBool = false;
You can't change the layout of the table from table layout otherwise it will not be a table.
It should be possible to get the table to fill the width of a parent BoxLayout_Y by assigning width percentages to table columns up to 100% e.g. for a 3 column table return assign 33, 33 & 44.
This can be achieved by subclassing table and overriding the method:
protected TableLayout.Constraint createCellConstraint(Object value, int row, int column) {
TableLayout.Constraint c = super.createCellConstraint(value, row, column);
c.setWidthPercentage(whateverYouWant);
return c;
}

Resources