天天看點

java doc轉pdf_java 完美解決 ppt/pptx 轉pdf 源碼

需要的pom檔案

java doc轉pdf_java 完美解決 ppt/pptx 轉pdf 源碼
java doc轉pdf_java 完美解決 ppt/pptx 轉pdf 源碼
java doc轉pdf_java 完美解決 ppt/pptx 轉pdf 源碼
java doc轉pdf_java 完美解決 ppt/pptx 轉pdf 源碼

第一個先來介紹pptx轉pdf

public class PptxToPDFConverter extends Converter{ // private static final String fontPath =PptxToPDFConverter.class.getClassLoader().getResource("").getPath()+"/simsun.ttc"; public PptxToPDFConverter(InputStream inStream, OutputStream outStream, boolean showMessages, boolean closeStreamsWhenComplete) { super(inStream, outStream, showMessages, closeStreamsWhenComplete); } private XSLFSlide[] slides; @Override public void convert() throws Exception { loading(); Dimension pgsize = processSlides(); processing(); double zoom = 2; // magnify it by 2 as typical slides are low res AffineTransform at = new AffineTransform(); at.setToScale(zoom, zoom); Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, outStream); document.open(); if(slides!=null){ for (int j = 0; j < getNumSlides(); j++) { for (XSLFShape shape : slides[j].getShapes()) { if (shape instanceof XSLFTextShape) { XSLFTextShape txtshape = (XSLFTextShape) shape; // System.out.println("txtshape" + (i+1) + ":" + txtshape.getShapeName()); //System.out.println("text:" +txtshape.getText()); for (XSLFTextParagraph textPara : txtshape.getTextParagraphs()) { List textRunList = textPara.getTextRuns(); for (XSLFTextRun textRun : textRunList) { textRun.setFontFamily("simsun.ttc"); } } } } } } for (int i = 0; i < getNumSlides(); i++) { BufferedImage bufImg = new BufferedImage((int)Math.ceil(pgsize.width*zoom), (int)Math.ceil(pgsize.height*zoom), BufferedImage.TYPE_INT_RGB); Graphics2D graphics = bufImg.createGraphics(); graphics.setTransform(at); //clear the drawing area graphics.setPaint(getSlideBGColor(i)); graphics.fill(new Rectangle2D.Float(0, 0, pgsize.width, pgsize.height)); try{ drawOntoThisGraphic(i, graphics); } catch(Exception e){ //Just ignore, draw what I have } Image image = Image.getInstance(bufImg, null); document.setPageSize(new Rectangle(image.getScaledWidth(), image.getScaledHeight())); document.newPage(); image.setAbsolutePosition(0, 0); document.add(image); } //Seems like I must close document if not output stream is not complete document.close(); //Not sure what repercussions are there for closing a writer but just do it. writer.close(); finished(); } protected Dimension processSlides() throws IOException{ InputStream iStream = inStream; XMLSlideShow ppt = new XMLSlideShow(iStream); Dimension dimension = ppt.getPageSize(); slides = ppt.getSlides(); return dimension; } protected int getNumSlides(){ return slides.length; } protected void drawOntoThisGraphic(int index, Graphics2D graphics){ slides[index].draw(graphics); } protected Color getSlideBGColor(int index){ return slides[index].getBackground().getFillColor(); }