Dmv
Dmv

Reputation: 23

Apache POI XWPFParagraph length in twips or points

Apologies if I have overlooked something: is there a way to get the length in twips or points of the text that is held in an XWPFParagraph. I could achieve it using Font And FontMetrics separately but that seems clunky. Any help will be much appreciated.

i I've searched what I hoped were the relevant Apache Javadocs.

Upvotes: 0

Views: 106

Answers (1)

Luke Poirrier
Luke Poirrier

Reputation: 166

While calculating text length using font metrics may seem a bit cumbersome, it's a common approach across various libraries and frameworks. However, if you're looking for a potentially less clunky method within Apache POI specifically, you might consider using the Graphics2D class from AWT (Abstract Window Toolkit) for font metrics. Here's the implementation in a simplified example:

import org.apache.poi.xwpf.usermodel.*;

import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.geom.AffineTransform;

public class ParagraphLength {
    public static void main(String[] args) {
        XWPFDocument doc = new XWPFDocument(); // Your XWPFDocument instance
        XWPFParagraph paragraph = doc.createParagraph(); // Your XWPFParagraph instance
        
        // Set your text here
        String text = "Your text goes here";
        paragraph.createRun().setText(text);
        
        int fontSize = 12; // Change this to match your font size
        int twips = getTextLengthTwips(paragraph, fontSize);
        System.out.println("Text length in twips: " + twips);
        
        float points = twips / 20f; // 1 twip = 1/20 point
        System.out.println("Text length in points: " + points);
    }
    
    public static int getTextLengthTwips(XWPFParagraph paragraph, int fontSize) {
        Graphics2D graphics2D = (Graphics2D) new BufferedImage(1, 1, BufferedImage.TYPE_INT_ARGB).getGraphics();
        Font font = new Font("Arial", Font.PLAIN, fontSize);
        graphics2D.setFont(font);
        FontMetrics fontMetrics = graphics2D.getFontMetrics();
        
        int totalWidth = 0;
        for (XWPFRun run : paragraph.getRuns()) {
            totalWidth += fontMetrics.stringWidth(run.text());
        }
        
        return totalWidth * 20; // Convert pixels to twips
    }
}

While it may not significantly reduce the clunkiness, it abstracts away some of the direct font manipulation and calculation, making the code slightly cleaner.

Upvotes: 0

Related Questions