How to set image size via HSSFWorkbook - java

I want to insert an image in my excel workbook using Apache Poi but I can't set size of image. I wrote this code but it's not what I want.
InputStream inputStream2=new FileInputStream("C:\\Users\\ftk1187\\Desktop\\tec.png");
byte[] imageBytes2 = IOUtils.toByteArray(inputStream2);
int pictureureIdx2 = wb.addPicture(imageBytes2, Workbook.PICTURE_TYPE_PNG);
inputStream2.close();
CreationHelper helper2 = wb.getCreationHelper();
Drawing drawing2 = sheet.createDrawingPatriarch();
ClientAnchor anchor2 = helper2.createClientAnchor();
anchor2.setDx1(0);
anchor2.setDy1(0);
anchor2.setDx2(100);
anchor2.setDy2(120);
anchor2.setCol1(8);
anchor2.setRow1(1);
Picture pict2 = drawing2.createPicture(anchor2, pictureureIdx2);
pict2.resize(2);
It scaling the image but I want to resize it with centimeters. I looked some forums but I didn't find anything to solve this problem. Also I want to align this picture to middle of cell. What can I try next?

This is not as simple as you might think. Not only that there are many different measurement units to take into account, unfortunately there also are big differences between binary *.xls and Office Open XML *.xlsx file formats.
Best measurement unit to work with here will be pixels. This can be converted to EMU using Units.EMU_PER_PIXEL. So instead of resizing the picture in centimeters, it should be done in pixels. But one can convert centimeter to pixels using following formula:
float pixels = cm / 2.54f * 72f * Units.PIXEL_DPI / Units.POINT_DPI
That is: 1 inch = 2.54 cm, so cm / 2.54 are inches, inches * 72 are points and points * pixel DPI / points DPI are pixels.
If we need working using pixels and want placing the picture horizontal and vertical centered over a cell, of course we also need having the cell width and the row height in pixels. Having this, we can calculate the horizontal and vertical start and end position of the picture over the cell. Then we can set picture's anchor as starting on top left of the cell plus dx1 = horizontal start position and plus dy1 = vertical start position. Also picture's anchor ends on top left of the cell plus dx2 = horizontal end position and plus dy2 = vertical end position.
The following complete example places the picture in size of 3 cm x 1.5 cm horizontal and vertical centered over cell B2 which is 100pt height and 50 default characters width. It works for HSSF as well as for XSSF.
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
class CreateExcelPictureOverCell {
public static void main(String[] args) throws Exception {
Workbook workbook = new HSSFWorkbook(); String filePath = "./Excel.xls";
//Workbook workbook = new XSSFWorkbook(); String filePath = "./Excel.xlsx";
Sheet sheet = workbook.createSheet();
Row row = sheet.createRow(1); // row 2
float rowHeightInPoints = 100f;
row.setHeightInPoints(rowHeightInPoints);
float rowHeightInPixels = rowHeightInPoints * Units.PIXEL_DPI / Units.POINT_DPI;
Cell cell = row.createCell(1); // col B
sheet.setColumnWidth(1, 50*256); // 50 default characters width
float colWidthInPixels = sheet.getColumnWidthInPixels(1);
InputStream inputStream = new FileInputStream("./logo.png");
byte[] imageBytes = IOUtils.toByteArray(inputStream);
int pictureureIdx = workbook.addPicture(imageBytes, Workbook.PICTURE_TYPE_PNG);
inputStream.close();
CreationHelper helper = workbook.getCreationHelper();
Drawing drawing = sheet.createDrawingPatriarch();
ClientAnchor anchor = helper.createClientAnchor();
//set start position of picture's anchor to top left B2
anchor.setRow1(1);
anchor.setCol1(1);
//create picture
Picture pict = drawing.createPicture(anchor, pictureureIdx);
//get picture's original size
int pictOriginalWidthInPixels = pict.getImageDimension().width;
int pictOriginalHeightInPixels = pict.getImageDimension().height;
//set picture's wanted size
float pictWidthInCm = 3f;
float pictWidthInPixels = pictWidthInCm / 2.54f * 72f * Units.PIXEL_DPI / Units.POINT_DPI;
//want scaling in aspect ratio?
//float scale = pictWidthInPixels / pictOriginalWidthInPixels;
//float pictHeightInPixels = pictOriginalHeightInPixels * scale;
//want explicit set height too?
float pictHeightInCm = 1.5f;
float pictHeightInPixels = pictHeightInCm / 2.54f * 72f * Units.PIXEL_DPI / Units.POINT_DPI;
//calculate the horizontal center position
int horCenterPosInPixels = Math.round(colWidthInPixels/2f - pictWidthInPixels/2f);
//set the horizontal center position as Dx1 of anchor
if (workbook instanceof XSSFWorkbook) {
anchor.setDx1(horCenterPosInPixels * Units.EMU_PER_PIXEL); //in unit EMU for XSSF
} else if (workbook instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
int DEFAULT_COL_WIDTH = 10 * 256;
anchor.setDx1(Math.round(horCenterPosInPixels * Units.DEFAULT_CHARACTER_WIDTH / 256f * 14.75f * DEFAULT_COL_WIDTH / colWidthInPixels));
}
//calculate the vertical center position
int vertCenterPosInPixels = Math.round(rowHeightInPixels/2f - pictHeightInPixels/2f);
//set the vertical center position as Dy1 of anchor
if (workbook instanceof XSSFWorkbook) {
anchor.setDy1(Math.round(vertCenterPosInPixels * Units.EMU_PER_PIXEL)); //in unit EMU for XSSF
} else if (workbook instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
float DEFAULT_ROW_HEIGHT = 12.75f;
anchor.setDy1(Math.round(vertCenterPosInPixels * Units.PIXEL_DPI / Units.POINT_DPI * 14.75f * DEFAULT_ROW_HEIGHT / rowHeightInPixels));
}
//set end position of picture's anchor to top left B2
anchor.setRow2(1);
anchor.setCol2(1);
//calculate the horizontal end position of picture
int horCenterEndPosInPixels = Math.round(horCenterPosInPixels + pictWidthInPixels);
//set the horizontal end position as Dx2 of anchor
if (workbook instanceof XSSFWorkbook) {
anchor.setDx2(horCenterEndPosInPixels * Units.EMU_PER_PIXEL); //in unit EMU for XSSF
} else if (workbook instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
int DEFAULT_COL_WIDTH = 10 * 256;
anchor.setDx2(Math.round(horCenterEndPosInPixels * Units.DEFAULT_CHARACTER_WIDTH / 256f * 14.75f * DEFAULT_COL_WIDTH / colWidthInPixels));
}
//calculate the vertical end position of picture
int vertCenterEndPosInPixels = Math.round(vertCenterPosInPixels + pictHeightInPixels);
//set the vertical end position as Dy2 of anchor
if (workbook instanceof XSSFWorkbook) {
anchor.setDy2(Math.round(vertCenterEndPosInPixels * Units.EMU_PER_PIXEL)); //in unit EMU for XSSF
} else if (workbook instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
float DEFAULT_ROW_HEIGHT = 12.75f;
anchor.setDy2(Math.round(vertCenterEndPosInPixels * Units.PIXEL_DPI / Units.POINT_DPI * 14.75f * DEFAULT_ROW_HEIGHT / rowHeightInPixels));
}
FileOutputStream out = new FileOutputStream(filePath);
workbook.write(out);
out.close();
workbook.close();
}
}

try {
Resource resource = new ClassPathResource(IMAGE);
// FileInputStream obtains input bytes from the image file
java.io.InputStream inputStream = resource.getInputStream();
// Get the contents of an InputStream as a byte[].
byte[] bytes = IOUtils.toByteArray(inputStream);
// Adds a picture to the workbook
int pictureIdx = workbook.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
// close the input stream
inputStream.close();
// Returns an object that handles instantiating concrete classes
CreationHelper helper = workbook.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 top-left corner for the image
anchor.setCol1(0);
anchor.setDx1(100);
// Creates a picture
Picture pict = drawing.createPicture(anchor, pictureIdx);
// Reset the image to the original size
pict.resize();
} catch (Exception e) {
// TODO: handle exception
}

Related

How to put the image in the center of a cell of excel using java?

I want to put an image set in the center of a cell of excel, I use XSSFClientAnchor to anchor the picture position, but still not working like in picture 1.
How to set the image in the center of a cell, like in picture 2.
InputStream iStream = new FileInputStream(iList.get(q.getProductID()));
byte[] bytes = IOUtils.toByteArray(iStream);
int pictureIdx = wb.addPicture(bytes, Workbook.PICTURE_TYPE_PNG);
XSSFDrawing patriarch = sheet.createDrawingPatriarch();
XSSFClientAnchor anchor = new XSSFClientAnchor();
anchor.setCol1(1);
anchor.setRow1(row);
anchor.setCol2(2);
anchor.setRow2(row + 1);
Picture pic = patriarch.createPicture(anchor, pictureIdx);
pic.resize();
Images are not cell contents but hover over the sheet in a separate layer called drawing. They are anchored to the cells. A ClientAnchor provides following settings:
col1 = column index where left edge of picture is anchored on. So left edge of picture is anchored on left column edge of col1.
dx1 = difference in x direction. So left edge of picture is anchored on left column edge of col1 + dx1.
row1 = row index where top edge of picture is anchored on. So top edge of picture is anchored on top row edge of row1.
dy1 = difference in y direction. So top edge of picture is anchored on top row edge of row1 + dy1.
col2 = column index where right edge of picture is anchored on. So right edge of picture is anchored on left column edge of col2.
dx2 = difference in x direction. So right edge of picture is anchored on left column edge of col1 + dx2.
row2 = row index where bottom edge of picture is anchored on. So bottom edge of picture is anchored on top row edge of row2.
dy2 = difference in y direction. So bottom edge of picture is anchored on top row edge of row2 + dy2.
Thus, given a full two-cell-anchor, this determines the position of picture well as it's size.
If size of picture shall be it's native size, then only one-cell-anchor is needed. There col1+dx1 and row1+dy1 determines the position of top left edge of picture. The size is given by the native size of the picture.
If only col1 and row1 is set without dx1 and dy1, then top left edge of picture always is anchored to left edge of col1 and top edge of row1. So if centering over a cell is needed, then dx1 and dy1 needs to be calculated. To calculate dx1 and dy1 one needs to know the width and height of the picture as well as the width and height of the cell. Sounds simple but there are multiple different measurement units used for width and height of the cell and there are big differences between binary BIFF (*.xls) file system and Office Open XML (*.xlsx) file system.
The following code provides putPictureCentered method which puts a picture in sheet's drawing anchored to a cell given by colIdx and rowIdx. If possible, it calculates dx1 and dy1 so that the picture is anchored centered over the cell. It uses pixels as the common measurement unit. It considers differences between binary BIFF (*.xls) file system and Office Open XML (*.xlsx) file system. So it works for Sheet, may it be XSSFSheet or HSSFSheet.
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.util.IOUtils;
import org.apache.poi.util.Units;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
class CenterImageOverCell {
static void putPictureCentered(Sheet sheet, String picturePath, int pictureType, int colIdx, int rowIdx) throws Exception {
Workbook wb = sheet.getWorkbook();
//load the picture
InputStream inputStream = new FileInputStream(picturePath);
byte[] bytes = IOUtils.toByteArray(inputStream);
int pictureIdx = wb.addPicture(bytes, pictureType);
inputStream.close();
//create an anchor with upper left cell colIdx/rowIdx, only one cell anchor since bottom right depends on resizing
CreationHelper helper = wb.getCreationHelper();
ClientAnchor anchor = helper.createClientAnchor();
anchor.setCol1(colIdx);
anchor.setRow1(rowIdx);
//create a picture anchored to colIdx and rowIdx
Drawing drawing = sheet.createDrawingPatriarch();
Picture pict = drawing.createPicture(anchor, pictureIdx);
//get the picture width in px
int pictWidthPx = pict.getImageDimension().width;
//get the picture height in px
int pictHeightPx = pict.getImageDimension().height;
//get column width of column in px
float columnWidthPx = sheet.getColumnWidthInPixels(colIdx);
//get the height of row in px
Row row = sheet.getRow(rowIdx);
float rowHeightPt = row.getHeightInPoints();
float rowHeightPx = rowHeightPt * Units.PIXEL_DPI / Units.POINT_DPI;
//is horizontal centering possible?
if (pictWidthPx <= columnWidthPx) {
//calculate the horizontal center position
int horCenterPosPx = Math.round(columnWidthPx/2f - pictWidthPx/2f);
//set the horizontal center position as Dx1 of anchor
if (wb instanceof XSSFWorkbook) {
anchor.setDx1(horCenterPosPx * Units.EMU_PER_PIXEL); //in unit EMU for XSSF
} else if (wb instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
int DEFAULT_COL_WIDTH = 10 * 256;
anchor.setDx1(Math.round(horCenterPosPx * Units.DEFAULT_CHARACTER_WIDTH / 256f * 14.75f * DEFAULT_COL_WIDTH / columnWidthPx));
}
} else {
System.out.println("Picture is too width. Horizontal centering is not possible.");
//TODO: Log instead of System.out.println
}
//is vertical centering possible?
if (pictHeightPx <= rowHeightPx) {
//calculate the vertical center position
int vertCenterPosPx = Math.round(rowHeightPx/2f - pictHeightPx/2f);
//set the vertical center position as Dy1 of anchor
if (wb instanceof XSSFWorkbook) {
anchor.setDy1(Math.round(vertCenterPosPx * Units.EMU_PER_PIXEL)); //in unit EMU for XSSF
} else if (wb instanceof HSSFWorkbook) {
//see https://stackoverflow.com/questions/48567203/apache-poi-xssfclientanchor-not-positioning-picture-with-respect-to-dx1-dy1-dx/48607117#48607117 for HSSF
float DEFAULT_ROW_HEIGHT = 12.75f;
anchor.setDy1(Math.round(vertCenterPosPx * Units.PIXEL_DPI / Units.POINT_DPI * 14.75f * DEFAULT_ROW_HEIGHT / rowHeightPx));
}
} else {
System.out.println("Picture is too height. Vertical centering is not possible.");
//TODO: Log instead of System.out.println
}
//resize the picture to it's native size
pict.resize();
}
public static void main(String[] args) throws Exception {
//Workbook wb = new HSSFWorkbook(); String resultName = "CenterImageTest.xls";
Workbook wb = new XSSFWorkbook(); String resultName = "CenterImageTest.xlsx";
Sheet sheet = wb.createSheet("Sheet1");
int colIdx = 1;
int colWidth = 20; //in default character widths
int rowIdx = 1;
float rowHeight = 100; //in points
//========================prepare sheet
//create cell
Row row = sheet.createRow(rowIdx);
Cell cell = row.createCell(colIdx);
//set column width of colIdx in default character widths
sheet.setColumnWidth(colIdx, colWidth * 256);
//set row height of rowIdx in points
row.setHeightInPoints(rowHeight);
//========================end prepare sheet
//put image centered
String picturePath = "./pict100x100.png"; // small image
//String picturePath = "./pict100x200.png"; // image too height
//String picturePath = "./pict200x100.png"; // image too width
//String picturePath = "./pict200x200.png"; // image too big
putPictureCentered(sheet, picturePath, Workbook.PICTURE_TYPE_PNG, colIdx, rowIdx);
FileOutputStream fileOut = new FileOutputStream("./" + resultName);
wb.write(fileOut);
fileOut.close();
wb.close();
}
}

Boxable if cell height is changed text don't appear

I have created BaseTable according to example from https://github.com/dhorions/boxable/wiki
float margin = 50;
float yStartNewPage = myPage.getMediaBox().getHeight() - (2 * margin);
float tableWidth = myPage.getMediaBox().getWidth() - (2 * margin);
boolean drawContent = true;
float yStart = yStartNewPage;
float bottomMargin = 70;
float yPosition = 550;
BaseTable table = new BaseTable(yPosition, yStartNewPage, bottomMargin, tableWidth, margin, mainDocument, myPage, true, drawContent);
Row<PDPage> headerRow = table.createRow(15f);
Cell<PDPage> cell = headerRow.createCell(100, "Header");
table.addHeaderRow(headerRow);
Row<PDPage> row = table.createRow(12);
cell = row.createCell(30, "Data 1");
cell = row.createCell(70, "Some value");
table.draw();
contentStream.close();
mainDocument.addPage(myPage);
mainDocument.save("testfile.pdf");
mainDocument.close();
Table looks fine
but when I want change cell height like this
cell.setHeight(5f);
Content is not drawn in cell
I was trying with changing row height, font size change, but it didn't help.
Do You know how to fix it?
After some debugging I've noticed that the cell height can be changed like this:
cell.setHeight(cell.getTextHeight() + 0.5f);
It's important to pick cell.getTextHeight() and then add Your value, if You only put some number like 12f it won't work

JFree PIE CHART Enhancements

I want to draw Pie_chart for small data set has this form.
I used these code
DefaultPieDataset my_pie_chart_data = new DefaultPieDataset();
for(int i =1; i<9; i++) {
row = my_sheet.getRow(0);
cell = row.getCell(i);
chart_label=cell.getStringCellValue();
row = my_sheet.getRow(1);
cell = row.getCell(i);
chart_data=cell.getNumericCellValue();
my_pie_chart_data.setValue(chart_label,chart_data);
}
JFreeChart myPieChart=ChartFactory.createPieChart("PIE",my_pie_chart_data,true,true,false);
int width=640; /* Width of the chart */
int height=480; /* Height of the chart */
float quality=1; /* Quality factor */
ByteArrayOutputStream chart_out = new ByteArrayOutputStream();
ChartUtilities.writeChartAsJPEG(chart_out,quality,myPieChart,width,height);
int my_picture_id = my_workbook.addPicture(chart_out.toByteArray(), Workbook.PICTURE_TYPE_JPEG);
chart_out.close();
XSSFDrawing drawing = my_sheet.createDrawingPatriarch();
ClientAnchor my_anchor = new XSSFClientAnchor();
my_anchor.setCol1(4);
my_anchor.setRow1(5);
XSSFPicture my_picture = drawing.createPicture(my_anchor, my_picture_id);
my_picture.resize();
chart_file_input.close();
}
the resulting chart has these label on it, which is confusing, specially when the values are small because, they all refer to the same section. And I can live with the legend definition below.
Does anybody know how can I delete them ?

JTable multiple header with new lines

In java swing JTable, I want to print multiple header with new lines from MessageFormat.
MessageFormat header = new MessageFormat("Products Details" + '\n' + "xyz suppliers");
MessageFormat footer = new MessageFormat("Page{1,number,integer}");
tbl_country.print(JTable.PrintMode.FIT_WIDTH, header, footer);
I had try lot of codes but new lines header does not work.
Finally i found answer to print multiple header with new line of JTable data as below:-
My TablePrintable.java
import javax.swing.table.*;
import java.awt.*;
import java.awt.print.*;
import java.awt.geom.*;
import java.text.MessageFormat;
import javax.swing.JTable;
/**
* An implementation of <code>Printable</code> for printing
* <code>JTable</code>s.
* <p>
* This implementation spreads table rows naturally in sequence across multiple
* pages, fitting as many rows as possible per page. The distribution of
* columns, on the other hand, is controlled by a printing mode parameter passed
* to the constructor. When <code>JTable.PrintMode.NORMAL</code> is used, the
* implementation handles columns in a similar manner to how it handles rows,
* spreading them across multiple pages (in an order consistent with the table's
* <code>ComponentOrientation</code>). When
* <code>JTable.PrintMode.FIT_WIDTH</code> is given, the implementation scales
* the output smaller if necessary, to ensure that all columns fit on the page.
* (Note that width and height are scaled equally, ensuring that the aspect
* ratio remains the same).
* <p>
* The portion of table printed on each page is headed by the appropriate
* section of the table's <code>JTableHeader</code>.
* <p>
* Header and footer text can be added to the output by providing
* <code>MessageFormat</code> instances to the constructor. The printing code
* requests Strings from the formats by calling their <code>format</code> method
* with a single parameter: an <code>Object</code> array containing a single
* element of type <code>Integer</code>, representing the current page number.
* <p>
* There are certain circumstances where this <code>Printable</code> cannot fit
* items appropriately, resulting in clipped output. These are:
* <ul>
* <li>In any mode, when the header or footer text is too wide to fit completely
* in the printable area. The implementation prints as much of the text as
* possible starting from the beginning, as determined by the table's
* <code>ComponentOrientation</code>.
* <li>In any mode, when a row is too tall to fit in the printable area. The
* upper most portion of the row is printed and no lower border is shown.
* <li>In <code>JTable.PrintMode.NORMAL</code> when a column is too wide to fit
* in the printable area. The center of the column is printed and no left and
* right borders are shown.
* </ul>
* <p>
* It is entirely valid for a developer to wrap this <code>Printable</code>
* inside another in order to create complex reports and documents. They may
* even request that different pages be rendered into different sized printable
* areas. The implementation was designed to handle this by performing most of
* its calculations on the fly. However, providing different sizes works best
* when <code>JTable.PrintMode.FIT_WIDTH</code> is used, or when only the
* printable width is changed between pages. This is because when it is printing
* a set of rows in <code>JTable.PrintMode.NORMAL</code> and the implementation
* determines a need to distribute columns across pages, it assumes that all of
* those rows will fit on each subsequent page needed to fit the columns.
* <p>
* It is the responsibility of the developer to ensure that the table is not
* modified in any way after this <code>Printable</code> is created (invalid
* modifications include changes in: size, renderers, or underlying data). The
* behavior of this <code>Printable</code> is undefined if the table is changed
* at any time after creation.
*
* #author Shannon Hickey
* #version 1.41 11/17/05
*/
class MyTablePrintable implements Printable {
/**
* The table to print.
*/
private JTable table;
/**
* For quick reference to the table's header.
*/
private JTableHeader header;
/**
* For quick reference to the table's column model.
*/
private TableColumnModel colModel;
/**
* To save multiple calculations of total column width.
*/
private int totalColWidth;
/**
* The printing mode of this printable.
*/
private JTable.PrintMode printMode;
/**
* Provides the header text for the table.
*/
private MessageFormat[] headerFormat;
/**
* Provides the footer text for the table.
*/
private MessageFormat[] footerFormat;
/**
* The most recent page index asked to print.
*/
private int last = -1;
/**
* The next row to print.
*/
private int row = 0;
/**
* The next column to print.
*/
private int col = 0;
/**
* Used to store an area of the table to be printed.
*/
private final Rectangle clip = new Rectangle(0, 0, 0, 0);
/**
* Used to store an area of the table's header to be printed.
*/
private final Rectangle hclip = new Rectangle(0, 0, 0, 0);
/**
* Saves the creation of multiple rectangles.
*/
private final Rectangle tempRect = new Rectangle(0, 0, 0, 0);
/**
* Vertical space to leave between table and header/footer text.
*/
private static final int H_F_SPACE = 8;
/**
* Font size for the header text.
*/
private static final float HEADER_FONT_SIZE = 15.0f;
/**
* Font size for the footer text.
*/
private static final float FOOTER_FONT_SIZE = 10.0f;
/**
* The font to use in rendering header text.
*/
private Font headerFont;
/**
* The font to use in rendering footer text.
*/
private Font footerFont;
/**
* Create a new <code>TablePrintable</code> for the given
* <code>JTable</code>. Header and footer text can be specified using the
* two <code>MessageFormat</code> parameters. When called upon to provide a
* String, each format is given the current page number.
*
* #param table the table to print
* #param printMode the printing mode for this printable
* #param headerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a header, or null for none
* #param footerFormat a <code>MessageFormat</code> specifying the text to
* be used in printing a footer, or null for none
* #throws IllegalArgumentException if passed an invalid print mode
*/
public MyTablePrintable(JTable table,
JTable.PrintMode printMode,
MessageFormat[] headerFormat,
MessageFormat[] footerFormat) {
this.table = table;
header = table.getTableHeader();
colModel = table.getColumnModel();
totalColWidth = colModel.getTotalColumnWidth();
if (header != null) {
// the header clip height can be set once since it's unchanging
hclip.height = header.getHeight();
}
this.printMode = printMode;
this.headerFormat = headerFormat;
this.footerFormat = footerFormat;
// derive the header and footer font from the table's font
headerFont = table.getFont().deriveFont(Font.BOLD,
HEADER_FONT_SIZE);
footerFont = table.getFont().deriveFont(Font.PLAIN,
FOOTER_FONT_SIZE);
}
/**
* Prints the specified page of the table into the given {#link Graphics}
* context, in the specified format.
*
* #param graphics the context into which the page is drawn
* #param pageFormat the size and orientation of the page being drawn
* #param pageIndex the zero based index of the page to be drawn
* #return PAGE_EXISTS if the page is rendered successfully, or NO_SUCH_PAGE
* if a non-existent page index is specified
* #throws PrinterException if an error causes printing to be aborted
*/
public int print(Graphics graphics, PageFormat pageFormat, int pageIndex)
throws PrinterException {
// for easy access to these values
final int imgWidth = (int) pageFormat.getImageableWidth();
final int imgHeight = (int) pageFormat.getImageableHeight();
if (imgWidth <= 0) {
throw new PrinterException("Width of printable area is too small.");
}
// to pass the page number when formatting the header and footer text
Object[] pageNumber = new Object[]{new Integer(pageIndex + 1)};
// fetch the formatted header text, if any
String[] headerText = null;
if (headerFormat != null) {
headerText = new String[headerFormat.length];
for (int i = 0; i < headerFormat.length; i++) {
headerText[i] = headerFormat[i].format(pageNumber);
}
}
// fetch the formatted footer text, if any
String[] footerText = null;
if (footerFormat != null) {
footerText = new String[footerFormat.length];
for (int i = 0; i < footerFormat.length; i++) {
footerText[i] = footerFormat[i].format(pageNumber);
}
}
// to store the bounds of the header and footer text
Rectangle2D[] hRect = null;
Rectangle2D[] fRect = null;
// the amount of vertical space needed for the header and footer text
int headerTextSpace = 15;
int footerTextSpace = 0;
// the amount of vertical space available for printing the table
int availableSpace = imgHeight;
// if there's header text, find out how much space is needed for it
// and subtract that from the available space
if (headerText != null) {
graphics.setFont(headerFont);
hRect = new Rectangle2D[headerText.length];
for (int i = 0; i < headerText.length; i++) {
hRect[i] = graphics.getFontMetrics().getStringBounds(headerText[i], graphics);
headerTextSpace += (int) Math.ceil(hRect[i].getHeight());
}
availableSpace -= headerTextSpace + H_F_SPACE;
}
// if there's footer text, find out how much space is needed for it
// and subtract that from the available space
if (footerText != null) {
graphics.setFont(footerFont);
fRect = new Rectangle2D[footerText.length];
for (int i = 0; i < footerText.length; i++) {
fRect[i] = graphics.getFontMetrics().getStringBounds(footerText[i], graphics);
footerTextSpace += (int) Math.ceil(fRect[i].getHeight());
}
availableSpace -= footerTextSpace + H_F_SPACE;
}
if (availableSpace <= 0) {
throw new PrinterException("Height of printable area is too small.");
}
// depending on the print mode, we may need a scale factor to
// fit the table's entire width on the page
double sf = 1.0D;
if (printMode == JTable.PrintMode.FIT_WIDTH
&& totalColWidth > imgWidth) {
// if not, we would have thrown an acception previously
assert imgWidth > 0;
// it must be, according to the if-condition, since imgWidth > 0
assert totalColWidth > 1;
sf = (double) imgWidth / (double) totalColWidth;
}
// dictated by the previous two assertions
assert sf > 0;
// This is in a loop for two reasons:
// First, it allows us to catch up in case we're called starting
// with a non-zero pageIndex. Second, we know that we can be called
// for the same page multiple times. The condition of this while
// loop acts as a check, ensuring that we don't attempt to do the
// calculations again when we are called subsequent times for the
// same page.
while (last < pageIndex) {
// if we are finished all columns in all rows
if (row >= table.getRowCount() && col == 0) {
return NO_SUCH_PAGE;
}
// rather than multiplying every row and column by the scale factor
// in findNextClip, just pass a width and height that have already
// been divided by it
int scaledWidth = (int) (imgWidth / sf);
int scaledHeight = (int) ((availableSpace - hclip.height) / sf);
// calculate the area of the table to be printed for this page
findNextClip(scaledWidth, scaledHeight);
last++;
}
// translate into the co-ordinate system of the pageFormat
Graphics2D g2d = (Graphics2D) graphics;
g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());
// to save and store the transform
AffineTransform oldTrans;
// if there's footer text, print it at the bottom of the imageable area
if (footerText != null) {
oldTrans = g2d.getTransform();
g2d.translate(0, imgHeight - footerTextSpace);
for (int i = 0; i < footerText.length; i++) {
printText(g2d, footerText[i], fRect[i], footerFont, i, imgWidth);
}
g2d.setTransform(oldTrans);
}
// if there's header text, print it at the top of the imageable area
// and then translate downwards
if (headerText != null) {
for (int i = 0; i < headerText.length; i++) {
printText(g2d, headerText[i], hRect[i], headerFont, i, imgWidth);
}
g2d.translate(0, headerTextSpace + H_F_SPACE);
}
// constrain the table output to the available space
tempRect.x = 0;
tempRect.y = 0;
tempRect.width = imgWidth;
tempRect.height = availableSpace;
g2d.clip(tempRect);
// if we have a scale factor, scale the graphics object to fit
// the entire width
if (sf != 1.0D) {
g2d.scale(sf, sf);
// otherwise, ensure that the current portion of the table is
// centered horizontally
} else {
int diff = (imgWidth - clip.width) / 2;
g2d.translate(diff, 0);
}
// store the old transform and clip for later restoration
oldTrans = g2d.getTransform();
Shape oldClip = g2d.getClip();
// if there's a table header, print the current section and
// then translate downwards
if (header != null) {
hclip.x = clip.x;
hclip.width = clip.width;
g2d.translate(-hclip.x, 0);
g2d.clip(hclip);
header.print(g2d);
// restore the original transform and clip
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
// translate downwards
g2d.translate(0, hclip.height);
}
// print the current section of the table
g2d.translate(-clip.x, -clip.y);
g2d.clip(clip);
table.print(g2d);
// restore the original transform and clip
g2d.setTransform(oldTrans);
g2d.setClip(oldClip);
// draw a box around the table
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
return PAGE_EXISTS;
}
/**
* A helper method that encapsulates common code for rendering the header
* and footer text.
*
* #param g2d the graphics to draw into
* #param text the text to draw, non null
* #param rect the bounding rectangle for this text, as calculated at the
* given font, non null
* #param font the font to draw the text in, non null
* #param imgWidth the width of the area to draw into
*/
private void printText(Graphics2D g2d,
String text,
Rectangle2D rect,
Font font,
int textIndex,
int imgWidth) {
//int tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth); // for right allign
int tx = 0; // for left allign
int ty = textIndex * (int) Math.ceil(Math.abs(rect.getY()));
g2d.setColor(Color.BLACK);
g2d.setFont(font);
g2d.drawString(text, tx, ty);
}
/**
* Calculate the area of the table to be printed for the next page. This
* should only be called if there are rows and columns left to print.
*
* To avoid an infinite loop in printing, this will always put at least one
* cell on each page.
*
* #param pw the width of the area to print in
* #param ph the height of the area to print in
*/
private void findNextClip(int pw, int ph) {
final boolean ltr = table.getComponentOrientation().isLeftToRight();
// if we're ready to start a new set of rows
if (col == 0) {
if (ltr) {
// adjust clip to the left of the first column
clip.x = 0;
} else {
// adjust clip to the right of the first column
clip.x = totalColWidth;
}
// adjust clip to the top of the next set of rows
clip.y += clip.height;
// adjust clip width and height to be zero
clip.width = 0;
clip.height = 0;
// fit as many rows as possible, and at least one
int rowCount = table.getRowCount();
int rowHeight = table.getRowHeight(row);
do {
clip.height += rowHeight;
if (++row >= rowCount) {
break;
}
rowHeight = table.getRowHeight(row);
} while (clip.height + rowHeight <= ph);
}
// we can short-circuit for JTable.PrintMode.FIT_WIDTH since
// we'll always fit all columns on the page
if (printMode == JTable.PrintMode.FIT_WIDTH) {
clip.x = 0;
clip.width = totalColWidth;
return;
}
if (ltr) {
// adjust clip to the left of the next set of columns
clip.x += clip.width;
}
// adjust clip width to be zero
clip.width = 0;
// fit as many columns as possible, and at least one
int colCount = table.getColumnCount();
int colWidth = colModel.getColumn(col).getWidth();
do {
clip.width += colWidth;
if (!ltr) {
clip.x -= colWidth;
}
if (++col >= colCount) {
// reset col to 0 to indicate we're finished all columns
col = 0;
break;
}
colWidth = colModel.getColumn(col).getWidth();
} while (clip.width + colWidth <= pw);
}
}
To print while print buttom clicked
String name = lblCompanyName.getText();
String address = lblAddress.getText();
try {
PrinterJob job = PrinterJob.getPrinterJob();
MessageFormat[] header = new MessageFormat[3];
header[0] = new MessageFormat("line 1");
header[1] = new MessageFormat(" " + name);
header[2] = new MessageFormat(" " + address);
MessageFormat[] footer = new MessageFormat[2];
footer[0] = new MessageFormat("");
footer[1] = new MessageFormat("-{1}-");
job.setPrintable(new MyTablePrintable(table, JTable.PrintMode.FIT_WIDTH, header, footer));
job.printDialog();
job.print();
} catch (Exception ex) {
}
result

Is there a way to add big images to xls files using Apache POI?

I generate some quite big .png images in my app (say, 40000x10000 pixels). To avoid excessive memory usage, I exploited the fact that ImageIO writes line-by-line, thus I only need to keep 40000 pixels in memory at once (I actually keep a bit more - 100 lines, but still not the full image).
Afterwards, I add an image to POI Workbook using the following code:
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(img, "png", baos);
int pictureIdx = workbook.addPicture(baos.toByteArray, Workbook.PICTURE_TYPE_PNG);
CreationHelper helper = workbook.getCreationHelper();
Sheet sh = workbook.createSheet("Picture");
Drawing patriarch = sh.createDrawingPatriarch();
ClientAnchort anchor = helper.createClientAnchor();
anchor.setCol1(0);
anchor.setRow1(0);
Picture picture = patriarch.createPicture(anchor, pictureIdx);
picture.resize(); // here's the trouble :(
The picture.resize() call is the biggest problem here. To determine "preferred" image size, it attempts to load the whole image into memory - and our example image takes ~1.6GB of memory when uncompressed. Attempting to allocate 1.6GB of memory on some of user machines results in OOM exception.
If I omit the call to picture.resize(), the image just doesn't show up in resulting xls - it is inside the file, judging by the size, but it is not visible in table.
Is there some way to skip loading of the whole image in memory? Maybe I can manually provide preferred image size to Picture?
I found a way to work-around this problem - basically by copying the code from POI source and removing call to getImageDimension(). Note that this code assumes way too much about HSSF internals, and is likely to break during updates.
The following is my solution (scala syntax):
/** Applies resizing to HSSFPicture - without loading the whole image into memory. */
private def safeResize(pic: HSSFPicture, width: Double, height: Double, sheet: HSSFSheet) {
val anchor = pic.getAnchor.asInstanceOf[HSSFClientAnchor]
anchor.setAnchorType(2)
val pref: HSSFClientAnchor = {
val PX_DEFAULT = 32f
val PX_MODIFIED = 36.56f
val PX_ROW = 15
def getPixelWidth(column: Int): Float = {
val default = sheet.getDefaultColumnWidth*256
val cw = sheet.getColumnWidth(column)
if (default == cw) PX_DEFAULT else PX_MODIFIED
}
def getColumnWidthInPixels(column: Int): Float = {
val cw = sheet.getColumnWidth(column)
cw / getPixelWidth(column)
}
def getRowHeightInPixels(i: Int): Float = {
val row = sheet.getRow(i)
val height: Float = if (row != null) row.getHeight else sheet.getDefaultRowHeight
height / PX_ROW
}
var w = 0f
//space in the leftmost cell
w += getColumnWidthInPixels(anchor.getCol1)*(1 - anchor.getDx1.toFloat/1024)
var col2 = (anchor.getCol1 + 1).toShort
var dx2 = 0
while(w < width){
w += getColumnWidthInPixels(col2)
col2 = (col2 + 1).toShort
}
if (w > width) {
//calculate dx2, offset in the rightmost cell
col2 = (col2 - 1).toShort
val cw = getColumnWidthInPixels(col2)
val delta = w - width
dx2 = ((cw-delta)/cw*1024).toInt
}
anchor.setCol2(col2)
anchor.setDx2(dx2)
var h = 0f
h += (1 - anchor.getDy1.toFloat/256)* getRowHeightInPixels(anchor.getRow1)
var row2 = anchor.getRow1 + 1
var dy2 = 0
while (h < height){
h += getRowHeightInPixels(row2)
row2+=1
}
if(h > height) {
row2-=1
val ch = getRowHeightInPixels(row2)
val delta = h - height
dy2 = ((ch-delta)/ch*256).toInt
}
anchor.setRow2(row2)
anchor.setDy2(dy2)
anchor
}
val row2 = anchor.getRow1 + (pref.getRow2 - pref.getRow1)
val col2 = anchor.getCol1 + (pref.getCol2 - pref.getCol1)
anchor.setCol2(col2.toShort)
anchor.setDx1(0)
anchor.setDx2(pref.getDx2)
anchor.setRow2(row2)
anchor.setDy1(0)
anchor.setDy2(pref.getDy2)
}

Categories