Chinese characters are converted to squares when using APACHE POI to convert PPT to Image

I am having a problem when I am trying to use an Apache POI project to convert mine PPT

to Images. My code looks like this:

FileInputStream is = new FileInputStream("test.ppt");

SlideShow ppt = new SlideShow(is);


is.close();

Dimension pgsize = ppt.getPageSize();

Slide[] slide = ppt.getSlides();

for (int i = 0; i < slide.length; i++) {

BufferedImage img = new BufferedImage(pgsize.width, pgsize.height,
BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = img.createGraphics();
//clear the drawing area
graphics.setPaint(Color.white);
graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height));

//render
slide[i].draw(graphics);

//save the output
FileOutputStream out = new FileOutputStream("slide-" + (i+1) + ".png");
javax.imageio.ImageIO.write(img, "png", out);
out.close();

      

It works great, except all Chinese words are converted to some squares. Then how can I fix this?

+2


a source to share


3 answers


This seems to be a bug with apache POI. I added it to bugzilla



https://issues.apache.org/bugzilla/show_bug.cgi?id=54880

+3


a source


The problem is not with the POI, but with the JVM's font setting.

You need to set the font to a list in the JVM ( /usr/lib/jvm/jdk1.8.0_20/jre/lib/fonts

or similar) font list , like simsun.ttc.



XSLFTextShape[] phs = slide[i].getPlaceholders();
for (XSLFTextShape ts : phs) {
  java.util.List<XSLFTextParagraph> tpl = ts.getTextParagraphs();
  for(XSLFTextParagraph tp: tpl) {
    java.util.List<XSLFTextRun> trs = tp.getTextRuns();
    for(XSLFTextRun tr: trs) {
      logger.info(tr.getFontFamily());
      tr.setFontFamily("SimSun");
    }
  }
}

      

+2


a source


The problem lies in using FileOuputStream, which will always write data to the file using the default system encoding, which is most likely ISO-8859_1 for Windows. This encoding is not supported by Chinese characters. You need to create a stream where you can write using UTF-8 encoding, which needs a reader to be created. I looked at the API but couldn't find any methods that read the reader as an argument. But check if ImageOutputStream helps you.

+1


a source







All Articles