[英]How to resize picture to paragraph size using Apache POI?
I'm trying to add a picture to a docx file using Apache POI, but the picture is larger than paragraph size. 我正在尝试使用Apache POI将图片添加到docx文件中,但是该图片大于段落大小。 Is there a way to know paragraph size so I can resize image to fit paragraph?
有没有办法知道段落大小,以便我可以调整图像大小以适合段落? Below is how I attempt to add the picture.
以下是我尝试添加图片的方式。
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));
After some investigation I found that, by default, the paper size and margins are not set when creating a docx file. 经过一番调查,我发现默认情况下,创建docx文件时未设置纸张尺寸和边距。 So it is necessary to set them and to use the same value for setting image size.
因此,有必要设置它们并使用相同的值来设置图像尺寸。
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.