tags:

views:

33

answers:

0

I'm trying to create an an image file (eg. .bmp) with text printed on it, so that when chosen for print on paper it occupies all the paper (but for a narrow margin). How do you approach such a problem? This is essentially how I've been doing.

final BufferedImage img = new BufferedImage(3500, 2480, BufferedImage.TYPE_BYTE_INDEXED);
    final Graphics2D g2D = img.createGraphics();
    g2D.setBackground(Color.white);
    g2D.clearRect(0, 0, width, height);

    int xPos = 20;
    int yPos = 0;

    int j = 0;
    final int maxMengHeight = height / linesNo;

    int maxFontSize = maxMengHeight;

    while (g2D.getFontMetrics(tempFont).getHeight() > maxMengHeight) {
        tempFont = new Font(font.getFontName(), Font.BOLD, --maxFontSize);
    }
    tempFont = null;

    for (Set<Meaning> batch : testMemo) {
        for (Meaning meng : batch) {
            int fontSize = maxFontSize;

            while ((xPos + g2D.getFontMetrics(expFont).stringWidth(word) + g2D.getFontMetrics(defFont).stringWidth(defLine)) > img.getWidth()) {
                expFont = new Font(font.getFontName(), Font.BOLD, --fontSize);
                defFont = new Font(font.getFontName(), Font.PLAIN, fontSize);
            }
            g2D.setFont(expFont);
            yPos += g2D.getFontMetrics().getAscent();
                g2D.drawString(prefixedExp, xPos, yPos);
                xPos += g2D.getFontMetrics().stringWidth(prefixedExp);
            }
            yPos +=  g2D.getFontMetrics().getDescent();
            xPos = 20;
        }