⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 slideshow.java

📁 java 读写word excel ppt
💻 JAVA
📖 第 1 页 / 共 2 页
字号:
/* ====================================================================   Licensed to the Apache Software Foundation (ASF) under one or more   contributor license agreements.  See the NOTICE file distributed with   this work for additional information regarding copyright ownership.   The ASF licenses this file to You under the Apache License, Version 2.0   (the "License"); you may not use this file except in compliance with   the License.  You may obtain a copy of the License at       http://www.apache.org/licenses/LICENSE-2.0   Unless required by applicable law or agreed to in writing, software   distributed under the License is distributed on an "AS IS" BASIS,   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.   See the License for the specific language governing permissions and   limitations under the License.==================================================================== */        package org.apache.poi.hslf.usermodel;import java.util.*;import java.awt.Dimension;import java.io.*;import org.apache.poi.ddf.EscherBSERecord;import org.apache.poi.ddf.EscherContainerRecord;import org.apache.poi.ddf.EscherOptRecord;import org.apache.poi.ddf.EscherRecord;import org.apache.poi.hslf.*;import org.apache.poi.hslf.model.*;import org.apache.poi.hslf.model.Notes;import org.apache.poi.hslf.model.Slide;import org.apache.poi.hslf.record.SlideListWithText.*;import org.apache.poi.hslf.record.*;import org.apache.poi.hslf.exceptions.CorruptPowerPointFileException;import org.apache.poi.hslf.exceptions.HSLFException;import org.apache.poi.util.ArrayUtil;import org.apache.poi.util.POILogFactory;import org.apache.poi.util.POILogger;/** * This class is a friendly wrapper on top of the more scary HSLFSlideShow. * * TODO: *  - figure out how to match notes to their correct sheet *    (will involve understanding DocSlideList and DocNotesList) *  - handle Slide creation cleaner *  * @author Nick Burch * @author Yegor kozlov */public class SlideShow{  // What we're based on  private HSLFSlideShow _hslfSlideShow;  // Low level contents, as taken from HSLFSlideShow  private Record[] _records;  // Pointers to the most recent versions of the core records  //  (Document, Notes, Slide etc)  private Record[] _mostRecentCoreRecords;  // Lookup between the PersitPtr "sheet" IDs, and the position  //  in the mostRecentCoreRecords array  private Hashtable _sheetIdToCoreRecordsLookup;  // Used when adding new core records  private int _highestSheetId;    // Records that are interesting  private Document _documentRecord;  // Friendly objects for people to deal with  private SlideMaster[] _masters;  private TitleMaster[] _titleMasters;  private Slide[] _slides;  private Notes[] _notes;  private FontCollection _fonts;  // For logging  private POILogger logger = POILogFactory.getLogger(this.getClass());    /* ===============================================================   *                       Setup Code   * ===============================================================   */    /**   * Constructs a Powerpoint document from the underlying    * HSLFSlideShow object. Finds the model stuff from this   *   * @param hslfSlideShow the HSLFSlideShow to base on   */  public SlideShow(HSLFSlideShow hslfSlideShow) throws IOException  {	// Get useful things from our base slideshow    _hslfSlideShow = hslfSlideShow;	_records = _hslfSlideShow.getRecords();		// Handle Parent-aware Reocrds	for(int i=0; i<_records.length; i++) {		handleParentAwareRecords(_records[i]);	}	// Find the versions of the core records we'll want to use	findMostRecentCoreRecords();		// Build up the model level Slides and Notes	buildSlidesAndNotes();  }    /**   * Constructs a new, empty, Powerpoint document.   */  public SlideShow() throws IOException {	this(new HSLFSlideShow());  }    /**     * Constructs a Powerpoint document from an input stream.     */    public SlideShow(InputStream inputStream) throws IOException {      this(new HSLFSlideShow(inputStream));    }  /**   * Find the records that are parent-aware, and tell them   *  who their parent is   */  private void handleParentAwareRecords(Record baseRecord) {	  // Only need to do something if this is a container record	  if(baseRecord instanceof RecordContainer) {		RecordContainer br = (RecordContainer)baseRecord;		Record[] childRecords = br.getChildRecords();				// Loop over child records, looking for interesting ones		for(int i=0; i<childRecords.length; i++) {			Record record = childRecords[i];			// Tell parent aware records of their parent			if(record instanceof ParentAwareRecord) {				((ParentAwareRecord)record).setParentRecord(br);			}			// Walk on down for the case of container records			if(record instanceof RecordContainer) {				handleParentAwareRecords(record);			}		}	  }  }  /**   * Use the PersistPtrHolder entries to figure out what is   *  the "most recent" version of all the core records   *  (Document, Notes, Slide etc), and save a record of them.   * Do this by walking from the oldest PersistPtr to the newest,   *  overwriting any references found along the way with newer ones   */  private void findMostRecentCoreRecords() {	// To start with, find the most recent in the byte offset domain	Hashtable mostRecentByBytes = new Hashtable();	for(int i=0; i<_records.length; i++) {		if(_records[i] instanceof PersistPtrHolder) {			PersistPtrHolder pph = (PersistPtrHolder)_records[i];			// If we've already seen any of the "slide" IDs for this 			//  PersistPtr, remove their old positions			int[] ids = pph.getKnownSlideIDs();			for(int j=0; j<ids.length; j++) {				Integer id = new Integer(ids[j]);				if( mostRecentByBytes.containsKey(id)) {					mostRecentByBytes.remove(id);				}				}			// Now, update the byte level locations with their latest values			Hashtable thisSetOfLocations = pph.getSlideLocationsLookup();			for(int j=0; j<ids.length; j++) {				Integer id = new Integer(ids[j]);				mostRecentByBytes.put(id, thisSetOfLocations.get(id));			}		}	}	// We now know how many unique special records we have, so init	//  the array	_mostRecentCoreRecords = new Record[mostRecentByBytes.size()];		// We'll also want to be able to turn the slide IDs into a position	//  in this array	_sheetIdToCoreRecordsLookup = new Hashtable();	int[] allIDs = new int[_mostRecentCoreRecords.length];	Enumeration ids = mostRecentByBytes.keys();	for(int i=0; i<allIDs.length; i++) {		Integer id = (Integer)ids.nextElement();		allIDs[i] = id.intValue();	}	Arrays.sort(allIDs);	for(int i=0; i<allIDs.length; i++) {		_sheetIdToCoreRecordsLookup.put(new Integer(allIDs[i]), new Integer(i));	}	// Capture the ID of the highest sheet	_highestSheetId = allIDs[(allIDs.length-1)];	// Now convert the byte offsets back into record offsets	for(int i=0; i<_records.length; i++) {		if(_records[i] instanceof PositionDependentRecord) {			PositionDependentRecord pdr = (PositionDependentRecord)_records[i];			Integer recordAt = new Integer(pdr.getLastOnDiskOffset());			// Is it one we care about?			for(int j=0; j<allIDs.length; j++) {				Integer thisID = new Integer(allIDs[j]);				Integer thatRecordAt = (Integer)mostRecentByBytes.get(thisID);				if(thatRecordAt.equals(recordAt)) {					// Bingo. Now, where do we store it?					Integer storeAtI = 						(Integer)_sheetIdToCoreRecordsLookup.get(thisID);					int storeAt = storeAtI.intValue();										// Tell it its Sheet ID, if it cares					if(pdr instanceof PositionDependentRecordContainer) {						PositionDependentRecordContainer pdrc = 							(PositionDependentRecordContainer)_records[i];						pdrc.setSheetId(thisID.intValue());					}										// Finally, save the record					_mostRecentCoreRecords[storeAt] = _records[i];				}			}		}	}		// Now look for the interesting records in there	for(int i=0; i<_mostRecentCoreRecords.length; i++) {		// Check there really is a record at this number		if(_mostRecentCoreRecords[i] != null) {			// Find the Document, and interesting things in it			if(_mostRecentCoreRecords[i].getRecordType() == RecordTypes.Document.typeID) {				_documentRecord = (Document)_mostRecentCoreRecords[i];				_fonts = _documentRecord.getEnvironment().getFontCollection();			}		} else {			// No record at this number			// Odd, but not normally a problem		}	}  }    	/**  	 * For a given SlideAtomsSet, return the core record, based on the refID from the  	 *  SlidePersistAtom  	 */	private Record getCoreRecordForSAS(SlideAtomsSet sas) {		SlidePersistAtom spa = sas.getSlidePersistAtom();		int refID = spa.getRefID();		return getCoreRecordForRefID(refID);	}  	/**   	 * For a given refID (the internal, 0 based numbering scheme), return the	 *  core record	 * @param refID the refID	 */	private Record getCoreRecordForRefID(int refID) {		Integer coreRecordId = (Integer)			_sheetIdToCoreRecordsLookup.get(new Integer(refID));		if(coreRecordId != null) {			Record r = _mostRecentCoreRecords[coreRecordId.intValue()];			return r;		} else {			logger.log(POILogger.ERROR, "We tried to look up a reference to a core record, but there was no core ID for reference ID " + refID);			return null;		}	}  /**   * Build up model level Slide and Notes objects, from the underlying   *  records.   */  private void buildSlidesAndNotes() {	// Ensure we really found a Document record earlier	// If we didn't, then the file is probably corrupt	if(_documentRecord == null) {		throw new CorruptPowerPointFileException("The PowerPoint file didn't contain a Document Record in its PersistPtr blocks. It is probably corrupt.");	}	// Fetch the SlideListWithTexts in the most up-to-date Document Record	//	// As far as we understand it:	//  * The first SlideListWithText will contain a SlideAtomsSet	//     for each of the master slides	//  * The second SlideListWithText will contain a SlideAtomsSet	//     for each of the slides, in their current order	//    These SlideAtomsSets will normally contain text	//  * The third SlideListWithText (if present), will contain a	//     SlideAtomsSet for each Notes	//    These SlideAtomsSets will not normally contain text	//	// Having indentified the masters, slides and notes + their orders,	//  we have to go and find their matching records	// We always use the latest versions of these records, and use the	//  SlideAtom/NotesAtom to match them with the StyleAtomSet 	SlideListWithText masterSLWT = _documentRecord.getMasterSlideListWithText();	SlideListWithText slidesSLWT = _documentRecord.getSlideSlideListWithText();	SlideListWithText notesSLWT  = _documentRecord.getNotesSlideListWithText();    // Find master slides	// These can be MainMaster records, but oddly they can also be	//  Slides or Notes, and possibly even other odd stuff....	// About the only thing you can say is that the master details are in	//  the first SLWT.    SlideAtomsSet[] masterSets = new SlideAtomsSet[0];    if (masterSLWT != null){        masterSets = masterSLWT.getSlideAtomsSets();		ArrayList mmr = new ArrayList();        ArrayList tmr = new ArrayList();		for(int i=0; i<masterSets.length; i++) {			Record r = getCoreRecordForSAS(masterSets[i]);            SlideAtomsSet sas = masterSets[i];            int sheetNo = sas.getSlidePersistAtom().getSlideIdentifier();			if(r instanceof org.apache.poi.hslf.record.Slide) {                TitleMaster master = new TitleMaster((org.apache.poi.hslf.record.Slide)r, sheetNo);                master.setSlideShow(this);                tmr.add(master);			} else if(r instanceof org.apache.poi.hslf.record.MainMaster) {                SlideMaster master = new SlideMaster((org.apache.poi.hslf.record.MainMaster)r, sheetNo);                master.setSlideShow(this);                mmr.add(master);            }		}        _masters = new SlideMaster[mmr.size()];        mmr.toArray(_masters);        _titleMasters = new TitleMaster[tmr.size()];        tmr.toArray(_titleMasters);    }	// Having sorted out the masters, that leaves the notes and slides	// Start by finding the notes records to go with the entries in	//  notesSLWT	org.apache.poi.hslf.record.Notes[] notesRecords;	SlideAtomsSet[] notesSets = new SlideAtomsSet[0];	Hashtable slideIdToNotes = new Hashtable();	if(notesSLWT == null) {		// None		notesRecords = new org.apache.poi.hslf.record.Notes[0]; 	} else {		// Match up the records and the SlideAtomSets		notesSets = notesSLWT.getSlideAtomsSets();		ArrayList notesRecordsL = new ArrayList();		for(int i=0; i<notesSets.length; i++) {			// Get the right core record			Record r = getCoreRecordForSAS(notesSets[i]);			// Ensure it really is a notes record			if(r instanceof org.apache.poi.hslf.record.Notes) {                org.apache.poi.hslf.record.Notes notesRecord = (org.apache.poi.hslf.record.Notes)r;				notesRecordsL.add( notesRecord );				// Record the match between slide id and these notes                SlidePersistAtom spa = notesSets[i].getSlidePersistAtom();                Integer slideId = new Integer(spa.getSlideIdentifier());                slideIdToNotes.put(slideId, new Integer(i));			} else {

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -