Apache POI XWPFP段落长度(以缇或点为单位)

问题描述 投票:0回答:1

如果我忽略了一些事情,我深表歉意:有没有办法获得 XWPFParagraph 中文本的长度(以缇或点为单位)。我可以分别使用 Font 和 FontMetrics 来实现它,但这看起来很笨重。任何帮助将不胜感激。

我 我已经搜索了相关的 Apache Javadocs。

java apache apache-poi xwpf
1个回答
0
投票

虽然使用字体指标计算文本长度可能看起来有点麻烦,但这是各种库和框架的常见方法。但是,如果您正在 Apache POI 中寻找一种可能不那么笨重的方法,您可以考虑使用 AWT(Abstract Window Toolkit)中的 Graphics2D 类来实现字体度量。这是一个简化示例的实现:

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
    }
}

虽然它可能不会显着减少笨重感,但它抽象了一些直接的字体操作和计算,使代码稍微干净一些。

© www.soinside.com 2019 - 2024. All rights reserved.