当尝试通过POI版本3.8提供的XSLFSlide.draw()
将.pptx文件转换为.png图像时,我遇到了一个问题。也就是说,由于我在同一张幻灯片中生成了XSLFTextBox
和XSLFTable
,因此slide.draw()
方法仅转换文本框,而忽略该表。这是我的代码。
XMLSlideShow ppt = new XMLSlideShow();
try {
XSLFSlide slide = ppt.createSlide();
XSLFTable tbl = slide.createTable();
XSLFTextBox tbox = slide.createTextBox();
XSLFTextRun trun = tbox.addNewTextParagraph().addNewTextRun();
trun.setText("111");
trun.setFontSize(40);
tbox.setAnchor(new Rectangle(0, 0, 100, 50));
tbl.setAnchor(new Rectangle(50, 50, 450, 300));
int numColumns = 3;
int numRows = 5;
XSLFTableRow headerRow = tbl.addRow();
headerRow.setHeight(50.0D);
int rownum;
for (rownum = 0; rownum < numColumns; ++rownum) {
XSLFTableCell th = headerRow.addCell();
XSLFTextParagraph p = th.addNewTextParagraph();
p.setTextAlign(TextAlign.CENTER);
XSLFTextRun r = p.addNewTextRun();
r.setText("Header " + (rownum + 1));
r.setBold(true);
r.setFontColor(Color.white);
th.setFillColor(new Color(79, 129, 189));
tbl.setColumnWidth(rownum, 150.0D);
}
for (rownum = 0; rownum < numRows; ++rownum) {
XSLFTableRow tr = tbl.addRow();
tr.setHeight(50.0D);
for (int i = 0; i < numColumns; ++i) {
XSLFTableCell cell = tr.addCell();
XSLFTextParagraph p = cell.addNewTextParagraph();
XSLFTextRun r = p.addNewTextRun();
r.setText("Cell " + (i + 1));
if (rownum % 2 == 0) {
cell.setFillColor(new Color(208, 216, 232));
} else {
cell.setFillColor(new Color(233, 247, 244));
}
}
}
FileOutputStream out = new FileOutputStream("table.pptx");
ppt.write(out);
BufferedImage img = new BufferedImage(ppt.getPageSize().width, ppt.getPageSize().height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
graphics.fill(new Rectangle(0, 0, ppt.getPageSize().width, ppt.getPageSize().height));
graphics.setPaint(Color.BLUE);
slide.draw(graphics);
FileOutputStream fos = new FileOutputStream("test.png");
ImageIO.write(img, "PNG", fos);
} catch (IOException e) {
e.printStackTrace();
}