After days and days of working on the same 20 lines of code I finally managed to get printing support for FlexGantt up and running. Why did it take so long? Because printing is one of the worst documented features of Java. I was not able to find any books on the topic (O'Reilly where are you?) and even web searches were not fruitful. The pages that I did find would never cover more than the most basic features. But printing a Gantt chart is a non-trivial task and multi-page printing only makes it harder. Anyway, I did manage to get it all together. The snapshot below shows what it looks like now.
Some of the code needed for realizing this preview dialog is listed below. This is only the implementation of the Printable interface, which is implemented by the Gantt chart. The code renders the content of the individual pages, so for example a page in row 2 and column 3. The number of horizontal and vertical pages gets determined by two helper methods (getVerticalPages(), getHorizontalPages()).public int print(Graphics g, PageFormat pageFormat, int pageIndex)
throws PrinterException {
int horizontalPages = getHorizontalPages();
int verticalPages = getVerticalPages();
int pageCount = horizontalPages * verticalPages;
if (pageIndex <> pageCount - 1) {
return NO_SUCH_PAGE;
}
Graphics2D g2d = (Graphics2D) g;
double iw = pageFormat.getImageableWidth();
double ih = pageFormat.getImageableHeight();
double ix = pageFormat.getImageableX();
double iy = pageFormat.getImageableY();
if (iw <= 0) {
throw new PrinterException("Width of printable area is too small.");
}
if (ih <= 0) {
throw new PrinterException("Height of printable area is too small.");
}
double sfWidth = iw / getWidth() * horizontalPages;
double sfHeight = ih / getHeight() * verticalPages;
double sf = Math.min(sfWidth, sfHeight);
//
// Store current transformation
//
AffineTransform oldTransform = g2d.getTransform();
//
// Print the Gantt chart.
//
int column = pageIndex % horizontalPages;
int row = pageIndex / horizontalPages;
int tx = column * (int) iw;
int ty = row * (int) ih;
g2d.translate(ix, iy);
g2d.translate(-tx, -ty);
if (previewDialog.isFillPage()) {
g2d.scale(sfWidth, sfHeight);
} else {
g2d.scale(sf, sf);
}
print(g2d);
//
// Restore old settings
//
g2d.setTransform(oldTransform);
return PAGE_EXISTS;
}
