Writing Graphics2D to BufferedImage - Poor Font resolution - java

So I'm trying to create labels for a generalized purpose by drawing to a Graphics2D object in a BufferedImage and then using ImageIO.write() to write this to a file. Unfortunately I'm encountering an issue where I can't figure out how to make the quality of the Font not 'blurred' (i can't think of the word in English, the edges are a bit cut or jagged, sort of indicative of low render resolution I guess). Is there a way to set it so that the Font renders at a certain DPI/Quality/Resolution?
This is what I get when I render the image. Notice the barcode I generated separately is not 'blurred' per se but the Font is.
/**
*
* #param data Array of Strings passed into label, where data[0] is the string to be barcoded
* #param titles Array of Strings passed into label parallel to data array, containing appropriate titles
* #throws IOException If
* #throws WriterException
*/
public static File createSeedBag(String[] titles,String[] data, Font[] fonts) throws IOException, WriterException{
/**
* TODO: Array of Fonts to customize Font
* Size customization
*/
BufferedImage theLabel;
BufferedImage theBarcode;
Graphics2D theGraphics;
File imageFile,
theFile;
FontMetrics titleMetrics,
theMetrics;
int width = 300;
int height = 450;
theLabel = new BufferedImage(width,height, BufferedImage.TYPE_BYTE_GRAY);
imageFile = LabelPrinter.writeBarCode(data[0], BarcodeSpecs.LARGE);
theGraphics = theLabel.createGraphics();
theGraphics.setPaint(Color.WHITE);
theGraphics.fillRect(0, 0, theLabel.getWidth(), theLabel.getHeight());
theGraphics.setPaint(Color.BLACK);
theGraphics.drawRect(0, 0, theLabel.getWidth()-1, theLabel.getHeight()-1);
/**
* Font objects
*/
fonts[0] = new Font("Bodoni 72", Font.BOLD, 40);
theGraphics.setFont(fonts[0]);
/**
* 1) Read Image File and set to bottom of label
*
* 2)
*/
theBarcode = ImageIO.read(imageFile);
theGraphics.drawImage(theBarcode, 1, height - 61, null);
titleMetrics = theGraphics.getFontMetrics(fonts[0]);
theGraphics.drawString(data[data.length-1], (width/2) - ((titleMetrics.stringWidth(data[data.length-1])) / 2), 50);
fonts[1]= new Font("Bodoni 72",0,20);
theMetrics = theGraphics.getFontMetrics(fonts[1]);
int stringHeight = theMetrics.getAscent();
theGraphics.setFont(fonts[1]);
for(int i = 1; i< data.length; i++) {
theGraphics.drawString(titles[i] + ": " + data[i], 5, 50 + (stringHeight * (i+1)));
}
theFile = new File("currentLabel.png");
ImageIO.write(theLabel, "png", theFile);
imageFile.deleteOnExit();
return theFile;
}

Related

Unit testing a complex renderer class (Best Practices)

I'm trying to test a class which purpose is taking a specification of what to do with a BufferedImage array and proccess it.
I'm concerned about how to aproach this task, it makes no sense to me just duplicate the function code on the test in order to generate a "expected bufferedImage array" and check if the generated BufferedImages are equals to the returned by the class methods.
I've read some slightly similar questions here, but the answers was "charge expected images from file and check with returned ones by class methods" but that sounds real hard to maintain if the proccess changes, new methods are added to the renderer class, it's hard or imposible pregenerate a resulting image or simply the class is refactorized and functions are splitted.
My actual question might be: Is there a little more elegant, "better to maintain" way to do that. I haven't so much experience with unit testing so i'm not sure about how to do this.
EDIT: sorry for the long code, i simplified and translated it. Excuse me if i did a bad translation. english it's not my main language.
public class Renderer extends SwingWorker<BufferedImage[], Integer>
{
private Device device;
private Main main;
private Controller controller;
public static final int FPS = 25;
public Renderer(Device device, Main main, Controller controller)
{
this.device = device;
this.main = main;
this.controller = controller;
}
#Override
protected BufferedImage[] doInBackground() throws Exception
{
// rendering image array
BufferedImage[] output = renderize(main.getActualEscene());
LOG.log.log(Level.INFO, "Rendering");
// getting how many times should repeat
String stringRepeat =
main.getActualEscene().getProperties().get(TextProperties.REPEAT.toString());
int repeat = (stringRepeat == null) ? 1 : Integer.parseInt(stringRepeat);
// getting text speed
String stringFps =
main.getActualEscene().getProperties().get(TextProperties.TEXT_SPEED.toString());
int fps = (stringFps == null) ? FPS : Integer.parseInt(stringFps);
if (!this.isCancelled()) // if this task is not cancelled
{
// we create a pre-viewer
controller.setPreviewer(
new Previewer(controller, repeat, fps, main.getActualEscene()));
SwingUtilities.invokeLater(new Runnable()
{// sincronizing this code with AWT thread
#Override
public void run()
{ // if it's not cancelled
if (controller.getPreviewer() != null
&& !controller.getPreviewer().isCancelled())
{
controller.getPreviewer().execute(); //execute the task
}
}
});
}
return output;
}
/**
* Renders a scene and transforms it in a image array, then save it to the scene
*
* #param scene -> scene
* #return an array with the scene frames
*/
public BufferedImage[] renderize(Scene scene)
{
BufferedImage[] output = null; // end result
BufferedImage[] base = new BufferedImage[1]; // base image
BufferedImage[] animationImages = null; // animation layer
BufferedImage[] textLayer = null; // text layer
BufferedImage[] overLayer = null; // overlayer
// omitted long process to retrieve image properties
// once the text properties are retrieved if it's not null it will be rendered
if (text != null)
{
String backgroundColorString =
scene.getProperties().get(TextProperties.BACKGROUND_COLOR.toString());
int backGroundcolorInt = Integer.parseInt(backgroundColorString);
if (animationImages != null) // if there is an animation layer we create a same size text layer
{
textLayer = new BufferedImage[animationImages.length];
} else
{
textLayer = new BufferedImage[1];
}
for (int i = 0; i < textLayer.length; i++)
{
textLayer[i] = new BufferedImage(device.getWidth(), device.getHeight(),
BufferedImage.TYPE_INT_ARGB);
}
String font = scene.getProperties().get(TextProperties.FONT.toString());
int lettersHeigth = device.getHeight() / 3;
int colorNumber =
Integer.parseInt(scene.getProperties().get(TextProperties.TEXT_COLOR.toString()));
textLayer = addTextToAImage(text, font, lettersHeigth, new Color(colorNumber),
new Color(backGroundcolorInt), textLayer);
}
// has it overlayer?
if (scene.getProperties().containsKey(AnimationProperties.OVER.toString())) // if it has over
{
String over = scene.getProperties().get(AnimationProperties.OVER.toString());
overLayer =
this.readingImagesFromAnimation(OverLibrary.getInstance().getOverByName(over));
}
// mixing layers
output = base; // adding base base
if (animationImages != null) // if there is animation layer we add it
{
output = mixingTwoImages(output, animationImages);
}
if (textLayer != null) // if there is text layer
{
output = mixingTwoImages(output, textLayer);
}
if (overLayer != null) //if there is overlayer
{
output = mixingTwoImages(output, overLayer);
}
// delimiting image operative zone.
output = delimite(output, device);
main.getActualEscene().setPreview(new Preview(output));
LOG.log.log(Level.INFO, "Rendering scene finished: " + scene.getNombre());
return output;
}
/**
* Apply the device mask to an image. Delimiting the scene operative zone.
*
* #param input -> BufferedImage array which need to be delimited
* #param device -> device which it mask need to be applied
* #return An BufferedImage array with a delimited image for the device.
*/
private BufferedImage[] delimite(BufferedImage[] input, Device device)
{
BufferedImage[] output = new BufferedImage[input.length];
for (int i = 0; i < output.length; i++) // copy all original frames
{
output[i] = new BufferedImage(device.getWidth(), device.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D graphics = output[i].createGraphics();
graphics.drawImage(input[i], 0, 0, null);
}
for (int i = 0; i < output.length; i++) // for each frame
{
for (int j = 0; j < output[i].getHeight(); j++) // for each row
{
for (int k = 0; k < output[i].getWidth(); k++) // for each column
{
if (!device.estaEnZonaOperativa(j, k)) // if the coordinate is not in the operative zone
{
int pixel = 0x00000000; // we create a transparent pixel
output[i].setRGB(j, k, pixel); // set the original pixel with this new one
}
}
}
}
return output;
}
/**
* method that reads an animation images and returns it into an array
*
* #param animation -> animaciĆ³n de la que obtendremos sus image
* #return array de BufferedImage con los frames de la animaciĆ³n ordenados por orden de lectura
* ascendente.
*/
private BufferedImage[] readingImagesFromAnimation(Animation animation)
{
BufferedImage[] output = new BufferedImage[animation.getData().length];
for (int i = 0; i < animation.getData().length; i++) // for each frame
{
try
{
File ruta = animation.getData()[i]; // getting its path
output[i] = ImageIO.read(ruta); // reading from the path and save it into output
} catch (IOException e)
{
LOG.log.log(Level.SEVERE, "error reading animation file: " + animation.getData()[i],
e);
}
}
return output;
}
/**
* create a text layer an add it to the image parameter center
*
* #param text -> text to include
* #param font -> font of the text
* #param size -> size
* #param color -> text color
* #param image -> image you want to add text
* #return a text layer that need to be mixed with original one.
*/
private BufferedImage[] addTextToAImage(String text, String font, int size, Color color,
Color backgroundColor, BufferedImage[] image)
{
// we set the size of the output as the same of the original image
BufferedImage[] output = new BufferedImage[image.length];
for (int i = 0; i < image.length; i++) // for each frame
{
output[i] = new BufferedImage(image[i].getWidth(), image[i].getHeight(),
BufferedImage.TYPE_INT_ARGB); // we create a single new image
Graphics2D graphics = output[i].createGraphics(); // get its graphics
// calculate for metrics
Font font = new Font(font, Font.PLAIN, size); // create a font
graphics.setFont(font); // setting it into the graphics
FontMetrics fontMetrics = graphics.getFontMetrics(font); // generating metric object
// calculate the text coordinates
int x = (image[i].getWidth() - fontMetrics.stringWidth(text)) / 2;
int y = ((image[i].getHeight() - fontMetrics.getAscent() - fontMetrics.getDescent()) / 2)
+ fontMetrics.getAscent();
int width = fontMetrics.stringWidth(text); // usefull metric to set a brackground
int height = fontMetrics.getAscent() + fontMetrics.getDescent();
// setting a background
graphics.setColor(backgroundColor);
graphics.fill(new Rectangle(x, y - fontMetrics.getAscent(), width, height));
// drawing text
graphics.setColor(color); // setting a color for text
graphics.drawString(text, x, y);
}
return output;
}
/**
* method to join two bufferedImage arrays and mix them. The shortest array will be played on loop
*
* WARNIN: the images needs to has the same resolution
*
* #param image -> image mixed as background
* #param image2 -> image mixed as foreground
* #return a mixed image array.
*/
private BufferedImage[] mixingTwoImages(BufferedImage[] image, BufferedImage[] image2)
{
// checking no empty images.
if (image.length == 0 || image2.length == 0)
{
RuntimeException exception =
new RuntimeException("empty images");
LOG.log.log(Level.SEVERE, exception.getMessage(), exception);
throw exception;
}
int width = Math.max(image[0].getWidth(), image2[0].getWidth());
int height = Math.max(image[0].getHeight(), image2[0].getHeight());
// creating a sequence of the longest size of them
BufferedImage[] output = new BufferedImage[Math.max(image.length, image2.length)];
for (int i = 0; i < output.length; i++) // for each frame
{
// we create a frame
output[i] = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = output[i].getGraphics();
// mixing the frame
if (image.length > image2.length) // if the first array is longer
{
g.drawImage(image[i], 0, 0, null);
g.drawImage(image2[i % image2.length], 0, 0, null);
} else if (image.length < image2.length) // if the second array is longer
{
g.drawImage(image[i % image.length], 0, 0, null);
g.drawImage(image2[i], 0, 0, null);
} else // bot of the same size
{
g.drawImage(image[i], 0, 0, null);
g.drawImage(image2[i], 0, 0, null);
}
}
return output;
}

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

Font width of non-English fonts

I am trying to draw characters from Hindi on a plain white background and store the resulting image as a jpeg. I need to size the image dynamically so that it fits the text. Currently, image height is fixed by assuming a size of 35 pixels (font size has been set to 22). How do I fix image width?
So far, I have tried to set the image width to 35 pixels times the maximum length of the different lines of text. That has not worked and the images saved are very wide. I am using drawString method of the graphics class in Java.
The function that creates images:
public static void printImages_temp(List<String> list) {
/* Function to print translations contained in list to images.
* Steps:
* 1. Take plain white image.
* 2. Write English word on top.
* 3. Take each translation and print one to each line.
*/
String dest = tgtDir + "\\" + list.get(0) + ".jpg"; //destination file image.
int imgWidth_max = 410;
int imgHeight_max = 230;
int fontSize = 22;
Font f = new Font("SERIF", Font.BOLD, fontSize);
//compute height and width of image.
int img_height = list.size() * 35 + 20;
int img_width = 0;
int max_length = 0;
for(int i = 0; i < list.size(); i++) {
if(list.get(i).length() > max_length) {
max_length = list.get(i).length();
}
}
img_width = max_length * 20;
System.out.println("New dimensions of image = " + img_width + " " + img_height);
BufferedImage img = new BufferedImage(img_width, img_height, BufferedImage.TYPE_INT_RGB);
Graphics g = img.getGraphics();
g.setColor(Color.WHITE);
g.fillRect(0, 0, img_width, img_height);
//image has to be written to another file.
for(int i = 0; i < list.size(); i++) {
g.setColor(Color.BLACK);
g.setFont(f);
g.drawString(list.get(i), 10, (i + 1) * 35);
}
//g.drawString(translation, 10, fontWidth); //a 22pt font is approx. 35 pixels long.
g.dispose();
try {
ImageIO.write(img, "jpeg", new File(dest));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
System.out.println("File written successfully to " + dest);
}
My questions:
How do I get width of a non-Latin type character, given that the fonts used to render the text are generic?
Is there a way to get the width that applies to all UTF-8 characters?

Resizing image to fit frame

A part of my application is working as a tutorial. For that purpose I got JPanels that display a JLabel that has an image as content. Although when the image is larger than what fits the screen it will just cut what doesn't fit. What I need to do is resize the image so that I will fit the space the JLabel is given. Also tried using JScrollPanes but didn't make any difference(although I prefer to resize image).
I tried getting a scaled instance of the image using
Image scaledImg = myPicture.getScaledInstance(width, height, Image.SCALE_SMOOTH);
but it didn't make any difference.
This is the current code :
private JLabel getTutorialLabel(int type) {
String path = "/Images/Tutorial/test" + type + ".png";
try {
BufferedImage tutorialPic = ImageIO.read(getClass().getResource(path));
// int height = (int) (screenDim.height * 0.9);
// int width = (int) (screenDim.width * 0.9);
// Image scaledImg = myPicture.getScaledInstance(width, height, Image.SCALE_SMOOTH);
JLabel picLabel = new JLabel(new ImageIcon(tutorialPic));
return picLabel;
} catch (IOException ex) {
Logger.getLogger(Tutorial.class.getName()).log(Level.SEVERE, null, ex);
}
return null;
}
How I get the image to display properly?
Please note that there are other components displayed along with the JLabel(JMenuBar and some buttons on bottom of screen) so I need to image to fill the space JLabel is given.
Edit: updated the method
You could try this method in the Java Helper Library.
Or, here's the method itself:
/**
* This method resizes the given image using Image.SCALE_SMOOTH.
*
* #param image the image to be resized
* #param width the desired width of the new image. Negative values force the only constraint to be height.
* #param height the desired height of the new image. Negative values force the only constraint to be width.
* #param max if true, sets the width and height as maximum heights and widths, if false, they are minimums.
* #return the resized image.
*/
public static Image resizeImage(Image image, int width, int height, boolean max) {
if (width < 0 && height > 0) {
return resizeImageBy(image, height, false);
} else if (width > 0 && height < 0) {
return resizeImageBy(image, width, true);
} else if (width < 0 && height < 0) {
PrinterHelper.printErr("Setting the image size to (width, height) of: ("
+ width + ", " + height + ") effectively means \"do nothing\"... Returning original image");
return image;
//alternatively you can use System.err.println("");
//or you could just ignore this case
}
int currentHeight = image.getHeight(null);
int currentWidth = image.getWidth(null);
int expectedWidth = (height * currentWidth) / currentHeight;
//Size will be set to the height
//unless the expectedWidth is greater than the width and the constraint is maximum
//or the expectedWidth is less than the width and the constraint is minimum
int size = height;
if (max && expectedWidth > width) {
size = width;
} else if (!max && expectedWidth < width) {
size = width;
}
return resizeImageBy(image, size, (size == width));
}
/**
* Resizes the given image using Image.SCALE_SMOOTH.
*
* #param image the image to be resized
* #param size the size to resize the width/height by (see setWidth)
* #param setWidth whether the size applies to the height or to the width
* #return the resized image
*/
public static Image resizeImageBy(Image image, int size, boolean setWidth) {
if (setWidth) {
return image.getScaledInstance(size, -1, Image.SCALE_SMOOTH);
} else {
return image.getScaledInstance(-1, size, Image.SCALE_SMOOTH);
}
}

Printing the data of a JTable without any border

I need to print the data in a JTable without any borders around, I have tried to achieve this by using an empty border for the JTable but still it prints a border around the table.
dataTable = new javax.swing.JTable();
dataTable.setBorder(BorderFactory.createEmptyBorder());
dataTable.setShowHorizontalLines(false); dataTable.setShowVerticalLines(false);
dataTable.setModel(new javax.swing.table.DefaultTableModel( new Object [][] { }, new String [] { "Item ID", "Company Name", "Qty.", "Price", "Total" } ));
jScrollPane1.setViewportView(dataTable);
jScrollPane1.setViewportBorder(BorderFactory.createEmptyBorder());
jScrollPane1.setBorder(BorderFactory.createEmptyBorder());
You can copy the Code from TablePrintable to a own class (MyPrintable) and remove following lines:
// draw a box around the table
g2d.setColor(Color.BLACK);
g2d.drawRect(0, 0, clip.width, hclip.height + clip.height);
And Override the getPrintable-Method in your JTable.
dataTable = new javax.swing.JTable(){
#Override
public Printable getPrintable( PrintMode printMode, MessageFormat headerFormat, MessageFormat footerFormat ) {
return new MyPrintable( this, printMode, headerFormat, footerFormat );
}
};
MyPrintable
/*
* #(#)TablePrintable.java 1.41 05/11/17
*
* Copyright 2006 Sun Microsystems, Inc. All rights reserved.
* SUN PROPRIETARY/CONFIDENTIAL. Use is subject to license terms.
*/
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Rectangle;
import java.awt.Shape;
import java.awt.geom.AffineTransform;
import java.awt.geom.Rectangle2D;
import java.awt.print.PageFormat;
import java.awt.print.Printable;
import java.awt.print.PrinterException;
import java.text.MessageFormat;
import javax.swing.JTable;
import javax.swing.table.JTableHeader;
import javax.swing.table.TableColumnModel;
/**
* 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 TablePrintable 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 = 18.0f;
/** Font size for the footer text. */
private static final float FOOTER_FONT_SIZE = 12.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 TablePrintable(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
*/
#Override
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 = headerFormat.format(pageNumber);
}
// fetch the formatted footer text, if any
String footerText = null;
if (footerFormat != null) {
footerText = footerFormat.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 = 0;
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 = graphics.getFontMetrics().getStringBounds(headerText,
graphics);
headerTextSpace = (int)Math.ceil(hRect.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 = graphics.getFontMetrics().getStringBounds(footerText,
graphics);
footerTextSpace = (int)Math.ceil(fRect.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);
printText(g2d, footerText, fRect, footerFont, 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) {
printText(g2d, headerText, hRect, headerFont, 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 imgWidth) {
int tx;
// if the text is small enough to fit, center it
if (rect.getWidth() < imgWidth) {
tx = (int)((imgWidth - rect.getWidth()) / 2);
// otherwise, if the table is LTR, ensure the left side of
// the text shows; the right can be clipped
} else if (table.getComponentOrientation().isLeftToRight()) {
tx = 0;
// otherwise, ensure the right side of the text shows
} else {
tx = -(int)(Math.ceil(rect.getWidth()) - imgWidth);
}
int ty = (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);
}
}

Categories