簡體   English   中英

如何使用Apache POI將圖片調整為段落大小?

[英]How to resize picture to paragraph size using 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));

經過一番調查,我發現默認情況下,創建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));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM