1

Possible Duplicate:
Problems with newline in Graphics2D.drawString

String eol =System.lineSeparator();  
        String sampleText =epcURNText +eol+studentName+eol+DelayComments+eol+ArrivalMethodComments+eol;
        System.out.println(sampleText);
        Font font = new Font("Tahoma", Font.PLAIN, 11);
        FontRenderContext frc = new FontRenderContext(null, true, true);

        //get the height and width of the text
        Rectangle2D bounds = font.getStringBounds(sampleText, frc);
        int w = (int) bounds.getWidth();
        int h = (int) bounds.getHeight();

        //create a BufferedImage object
        BufferedImage image = new BufferedImage(w, h,
                BufferedImage.TYPE_INT_RGB);

        //calling createGraphics() to get the Graphics2D
        Graphics2D g = image.createGraphics();

        //set color and other parameters
        g.setColor(Color.WHITE);
        g.fillRect(0, 0, w, h);
        g.setColor(Color.BLACK);
        g.setFont(font);

        g.drawString(sampleText, (float) bounds.getX(),
                (float) -bounds.getY());

        //releasing resources
        g.dispose();



        // define the format of print document
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "gif", os);
        File f = new File("MyFile.jpg");
        ImageIO.write(image, "JPEG", f);

Within the aforementioned code I am trying to print a string with newline characters within an image. However the newline character is omitted thus my text is presented within a single line? Does anybody have any idea on how to fix this?

Community
  • 1
  • 1
obelix
  • 880
  • 2
  • 16
  • 43

1 Answers1

2

Render the text in a JLabel with HTML formatting as shown the LabelRenderTest source in this answer.

It provides something better than line-breaks - the style for body width. Better in the sense that we do not need to manually calculate where to put line breaks for text (which also might be rendered in fonts that are not fixed width).

Community
  • 1
  • 1
Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433