如何使用Apache POI将图片调整为段落大小?

时间:2019-05-10 16:24:26

标签: java apache-poi

我正在尝试使用Apache POI将图片添加到docx文件中,但是该图片大于段落大小。有没有办法知道段落大小,以便我可以调整图像大小以适合段落?下面是我尝试添加图片的方式。

XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();

String imgFile = "img.png";
BufferedImage img = ImageIO.read(new FileInputStream(imgFile));
int width = img.getWidth();
int height = img.getHeight();
double scaling = 1.0;
// Calculate scaling based on width and paragraph size
XWPFRun run = paragraph.createRun();
run.addPicture(new FileInputStream(imgFile), 
        XWPFDocument.PICTURE_TYPE_PNG, 
        imgFile, 
        Units.toEMU(width*scaling), 
        Units.toEMU(height*scaling));

1 个答案:

答案 0 :(得分:0)

经过一番调查,我发现默认情况下,创建docx文件时未设置纸张尺寸和边距。因此,有必要设置它们并使用相同的值来设置图像大小。

int pageW = 500;
int pageH = 1000;
int pageM = 100;

CTDocument1 ctDoc = document.getDocument();
CTBody body = ctDoc.getBody();
if (!body.isSetSectPr()) {
    CTSectPr section = body.addNewSectPr();
    if (!section.isSetPgSz()) {
        CTPageSz size = section.addNewPgSz();
        size.setW(BigInteger.valueOf(pageW));
        size.setH(BigInteger.valueOf(pageH));
    }

    if (!section.isSetPgMar()) {
        CTPageMar margin = section.addNewPgMar();
        margin.setBottom(BigInteger.valueOf(pageM));
        margin.setTop(BigInteger.valueOf(pageM));
        margin.setLeft(BigInteger.valueOf(pageM));
        margin.setRight(BigInteger.valueOf(pageM));
    }
}

XWPFParagraph paragraph = document.createParagraph();
XWPFRun run = paragraph.createRun();
String imgFile = "img.png";
FileInputStream fis = new FileInputStream(imgFile);
BufferedImage img = ImageIO.read(fis);
int width = img.getWidth();
int height = img.getHeight();
double scaling = 1.0;
if (width > pageW - 2*pageM) {
    scaling = ((double)(pageW - 2*pageM)) / width;
}
run.addPicture(new FileInputStream(imgFile), 
        XWPFDocument.PICTURE_TYPE_PNG, 
        imgFile, 
        Units.toEMU(width * scaling / 20), 
        Units.toEMU(height * scaling / 20));
相关问题