java poi附件预览
来源:互联网 发布:编程软件cimit怎么样 编辑:程序博客网 时间:2024/05/16 09:08
(附件以二进制的形式存储在数据库将其转file,file转html),支持doc\docx\wps\xls\xlsx\et\ppt\dps\txt多种格式的文件预览
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.InputStream;import java.io.OutputStream;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import javax.sql.DataSource;import oracle.sql.BLOB;import uncertain.ocm.IObjectRegistry;public class Blob2File {public static String blob2File(IObjectRegistry registry, int attachment_id, String previewpath) { Connection conn = null; PreparedStatement ps = null; ResultSet rs = null; String filepath = ""; try { DataSource ds = (DataSource)registry .getInstanceOfType(DataSource.class); conn = ds.getConnection(); String sql = "select * from FND_ATM_ATTACHMENT t where t.attachment_id =?"; ps = conn.prepareStatement(sql); ps.setLong(1, attachment_id); rs = ps.executeQuery(); while (rs.next()) { String file_name = rs.getString("file_name"); String prefix = file_name.substring(file_name.lastIndexOf(".")); filepath = previewpath + attachment_id + prefix; System.out.println(filepath); File f = new File(filepath); if(!f.exists()){System.out.println("not exists");BLOB blob = (BLOB) rs.getBlob("content");InputStream in = blob.getBinaryStream();FileOutputStream file = new FileOutputStream(filepath);int len = (int) blob.length();byte[] buffer = new byte[len];while ((len = in.read(buffer)) != -1) {file.write(buffer, 0, len);}file.close();in.close(); } } } catch (Exception e) { e.printStackTrace(); try { if (rs != null) { rs.close(); } if (ps != null) { ps.close(); } if (conn != null) { conn.close(); } System.out.println("数据库连接已关闭!"); } catch (Exception ee) { ee.printStackTrace(); } try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); System.out.println("数据库连接已关闭!"); } catch (Exception e1) { e1.printStackTrace(); } } finally { try { if (rs != null) rs.close(); if (ps != null) ps.close(); if (conn != null) conn.close(); System.out.println("数据库连接已关闭!"); } catch (Exception e) { e.printStackTrace(); } } return filepath; }}
import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.io.OutputStreamWriter;import java.sql.Connection;import java.sql.DriverManager;import java.sql.PreparedStatement;import java.sql.ResultSet;import java.util.List;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.parsers.ParserConfigurationException;import javax.xml.transform.OutputKeys;import javax.xml.transform.Transformer;import javax.xml.transform.TransformerException;import javax.xml.transform.TransformerFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import oracle.sql.BLOB;import org.apache.commons.io.output.ByteArrayOutputStream;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.converter.PicturesManager;import org.apache.poi.hwpf.converter.WordToHtmlConverter;import org.apache.poi.hwpf.model.PicturesTable;import org.apache.poi.hwpf.usermodel.CharacterRun;import org.apache.poi.hwpf.usermodel.Paragraph;import org.apache.poi.hwpf.usermodel.Picture;import org.apache.poi.hwpf.usermodel.PictureType;import org.apache.poi.hwpf.usermodel.Range;import org.apache.poi.hwpf.usermodel.Table;import org.apache.poi.hwpf.usermodel.TableCell;import org.apache.poi.hwpf.usermodel.TableIterator;import org.apache.poi.hwpf.usermodel.TableRow;import org.apache.poi.poifs.filesystem.OfficeXmlFileException;import org.apache.poi.xwpf.converter.core.FileImageExtractor;import org.apache.poi.xwpf.converter.core.FileURIResolver;import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;import org.apache.poi.xwpf.usermodel.XWPFDocument;import org.w3c.dom.Document;/** */public class Word2Html {public static void main(String argv[]) throws TransformerException, IOException, ParserConfigurationException {word2Html("D:\\test\\a.wps", "D:\\test\\a.html","D:\\test\\","D:\\test\\");} public static void writeFile(String content, String path) {FileOutputStream fos = null;BufferedWriter bw = null;try {File file = new File(path);fos = new FileOutputStream(file);bw = new BufferedWriter(new OutputStreamWriter(fos, "UTF-8"));bw.write(content);} catch (FileNotFoundException fnfe) {fnfe.printStackTrace();} catch (IOException ioe) {ioe.printStackTrace();} finally {try {if (bw != null)bw.close();if (fos != null)fos.close();} catch (IOException ie) {}}}public static void word2Html(String fileName, String outPutFile,final String imgPath, String imgSavePath) throws TransformerException, IOException,ParserConfigurationException {try{HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));// WordToHtmlUtils.loadDoc(new// FileInputStream(inputFile));WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());wordToHtmlConverter.setPicturesManager(new PicturesManager() {public String savePicture(byte[] content, PictureType pictureType,String suggestedName, float widthInches, float heightInches) {return imgPath + suggestedName;}});wordToHtmlConverter.processDocument(wordDocument);// save picturesList pics = wordDocument.getPicturesTable().getAllPictures();if (pics != null) {for (int i = 0; i < pics.size(); i++) {Picture pic = (Picture) pics.get(i);System.out.println();try {pic.writeImageContent(new FileOutputStream(imgPath+ pic.suggestFullFileName()));} catch (FileNotFoundException e) {e.printStackTrace();}}}Document htmlDocument = wordToHtmlConverter.getDocument();ByteArrayOutputStream out = new ByteArrayOutputStream();DOMSource domSource = new DOMSource(htmlDocument);StreamResult streamResult = new StreamResult(out);TransformerFactory tf = TransformerFactory.newInstance();Transformer serializer = tf.newTransformer();serializer.setOutputProperty(OutputKeys.ENCODING, "UTF-8");serializer.setOutputProperty(OutputKeys.INDENT, "yes");serializer.setOutputProperty(OutputKeys.METHOD, "html");serializer.transform(domSource, streamResult);out.close();System.out.println("生成的图片路径:"+imgPath); System.out.println("替换的图片路径:"+imgSavePath); String temp = new String(out.toByteArray()).replace(imgPath, imgSavePath);writeFile(temp, outPutFile);}catch (OfficeXmlFileException e) { // 1) Load DOCX into XWPFDocument InputStream in = new FileInputStream(new File(fileName)); XWPFDocument document = new XWPFDocument(in); // 2) Prepare XHTML options (here we set the IURIResolver to // load images from a "word/media" folder) File imageFolderFile = new File(imgPath); XHTMLOptions options = XHTMLOptions.create().URIResolver( new FileURIResolver(imageFolderFile)); options.setExtractor(new FileImageExtractor(imageFolderFile)); options.setIgnoreStylesIfUnused(false); options.setFragment(true); // 3) Convert XWPFDocument to XHTML // OutputStream out = new FileOutputStream(new File( // "d:/test.htm")); ByteArrayOutputStream out = new ByteArrayOutputStream(); XHTMLConverter.getInstance().convert(document, out, options); out.close(); System.out.println("生成的图片路径:"+imgPath.substring(0, imgPath.length()-1)+"/word/media/"); System.out.println("替换的图片路径:"+imgSavePath+"word/media/"); String temp = new String(out.toByteArray()).replace(imgPath.substring(0, imgPath.length()-1)+"/word/media/", imgSavePath+"word/media/"); writeFile(temp, outPutFile); //return new String(out.toByteArray()); } /*catch (IllegalArgumentException e) { // TODO Auto-generated catch block e.printStackTrace(); //return ""; } catch (FileNotFoundException e) { // TODO Auto-generated catch block e.printStackTrace(); // return ""; } catch (TransformerFactoryConfigurationError e) { // TODO Auto-generated catch block e.printStackTrace(); //return ""; }*/}}
import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.text.DecimalFormat;import java.text.SimpleDateFormat;import java.util.Date;import java.util.HashMap;import java.util.Map;import javax.xml.parsers.DocumentBuilderFactory;import javax.xml.transform.dom.DOMSource;import javax.xml.transform.stream.StreamResult;import org.apache.commons.io.FileUtils;import org.apache.commons.io.output.ByteArrayOutputStream;import org.apache.poi.hssf.usermodel.HSSFCellStyle;import org.apache.poi.hssf.usermodel.HSSFDataFormat;import org.apache.poi.hssf.usermodel.HSSFDateUtil;import org.apache.poi.hssf.usermodel.HSSFFont;import org.apache.poi.hssf.usermodel.HSSFPalette;import org.apache.poi.hssf.usermodel.HSSFWorkbook;import org.apache.poi.hssf.util.HSSFColor;import org.apache.poi.hwpf.HWPFDocument;import org.apache.poi.hwpf.converter.PicturesManager;import org.apache.poi.hwpf.converter.WordToHtmlConverter;import org.apache.poi.hwpf.usermodel.PictureType;import org.apache.poi.ss.usermodel.Cell;import org.apache.poi.ss.usermodel.CellStyle;import org.apache.poi.ss.usermodel.Row;import org.apache.poi.ss.usermodel.Sheet;import org.apache.poi.ss.usermodel.Workbook;import org.apache.poi.ss.usermodel.WorkbookFactory;import org.apache.poi.ss.util.CellRangeAddress;import org.apache.poi.xssf.usermodel.XSSFCellStyle;import org.apache.poi.xssf.usermodel.XSSFColor;import org.apache.poi.xssf.usermodel.XSSFFont;import org.apache.poi.xssf.usermodel.XSSFWorkbook;import org.w3c.dom.Document;/** * @功能描述 POI 读取 Excel 转 HTML 支持 03xls 和 07xlsx 版本 包含样式 */public class POIReadExcelToHtml { /** * 测试 * @param args */public static void saveToFile (String str,String url){ try {File txt = new File(url);if (!txt.exists()) {txt.createNewFile();}byte bytes[] = new byte[5024];bytes = str.getBytes(); //新加的int b = str.length(); //改FileOutputStream fos = new FileOutputStream(txt);fos.write(bytes, 0, b);fos.close();} catch (Exception e) {// TODO: handle exception}}public static void main(String argv[]) {//String fileName = "C:\\Users\\Administrator\\Desktop\\分批上线清单0331.xlsx";String fileName = "D:\\test\\b.et";String outPutFile = "D:\\test\\b.html";convert2Html(fileName, outPutFile);} public static void convert2Html(String fileName, String outPutFile) { /*String path = "C:\\Users\\Administrator\\Desktop\\"; String file = "分批上线清单0331.xlsx";*/ InputStream is = null; String htmlExcel = null; try { File sourcefile = new File(fileName); is = new FileInputStream(sourcefile); Workbook wb = WorkbookFactory.create(is);//此WorkbookFactory在POI-3.10版本中使用需要添加dom4j if (wb instanceof XSSFWorkbook) { XSSFWorkbook xWb = (XSSFWorkbook) wb; htmlExcel = POIReadExcelToHtml.getExcelInfo(xWb,true); }else if(wb instanceof HSSFWorkbook){ HSSFWorkbook hWb = (HSSFWorkbook) wb; htmlExcel = POIReadExcelToHtml.getExcelInfo(hWb,true); } //System.out.println(htmlExcel); saveToFile(htmlExcel, outPutFile); //String str = "zhaozhu"; //System.out.println(htmlExcel.substring(0, 10000)); //FileUtils.writeStringToFile(new File (path, "2.1土地信息表.html"), htmlExcel, "utf-8"); } catch (Exception e) { e.printStackTrace(); }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } /** * 程序入口方法 * @param filePath 文件的路径 * @param isWithStyle 是否需要表格样式 包含 字体 颜色 边框 对齐方式 * @return ... 字符串 */ public String readExcelToHtml(String filePath , boolean isWithStyle){ InputStream is = null; String htmlExcel = null; try { File sourcefile = new File(filePath); is = new FileInputStream(sourcefile); Workbook wb = WorkbookFactory.create(is); if (wb instanceof XSSFWorkbook) { XSSFWorkbook xWb = (XSSFWorkbook) wb; htmlExcel = POIReadExcelToHtml.getExcelInfo(xWb,isWithStyle); }else if(wb instanceof HSSFWorkbook){ HSSFWorkbook hWb = (HSSFWorkbook) wb; htmlExcel = POIReadExcelToHtml.getExcelInfo(hWb,isWithStyle); } } catch (Exception e) { e.printStackTrace(); }finally{ try { is.close(); } catch (IOException e) { e.printStackTrace(); } } return htmlExcel; } public static String getExcelInfo(Workbook wb,boolean isWithStyle){ StringBuffer sb = new StringBuffer(); Sheet sheet = wb.getSheetAt(0);//获取第一个Sheet的内容 int lastRowNum = sheet.getLastRowNum(); Mapmap[] = getRowSpanColSpanMap(sheet); sb.append(""); Row row = null; //兼容 Cell cell = null; //兼容 for (int rowNum = sheet.getFirstRowNum(); rowNum <= lastRowNum; rowNum++) { row = sheet.getRow(rowNum); if (row == null) { sb.append(" "); continue; } sb.append(""); int lastColNum = row.getLastCellNum(); for (int colNum = 0; colNum < lastColNum; colNum++) { cell = row.getCell(colNum); if (cell == null) { //特殊情况 空白的单元格会返回null sb.append(" "); continue; } String stringValue = getCellValue(cell); if (map[0].containsKey(rowNum + "," + colNum)) { String pointString = map[0].get(rowNum + "," + colNum); map[0].remove(rowNum + "," + colNum); int bottomeRow = Integer.valueOf(pointString.split(",")[0]); int bottomeCol = Integer.valueOf(pointString.split(",")[1]); int rowSpan = bottomeRow - rowNum + 1; int colSpan = bottomeCol - colNum + 1; sb.append(""); if (stringValue == null || "".equals(stringValue.trim())) { sb.append(" "); } else { // 将ascii码为160的空格转换为html下的空格( ) sb.append(stringValue.replace(String.valueOf((char) 160)," ")); } sb.append(""); } sb.append(""); } sb.append(""); return sb.toString(); } private static Map [] getRowSpanColSpanMap(Sheet sheet) { Map map0 = new HashMap (); Map map1 = new HashMap (); int mergedNum = sheet.getNumMergedRegions(); CellRangeAddress range = null; for (int i = 0; i < mergedNum; i++) { range = sheet.getMergedRegion(i); int topRow = range.getFirstRow(); int topCol = range.getFirstColumn(); int bottomRow = range.getLastRow(); int bottomCol = range.getLastColumn(); map0.put(topRow + "," + topCol, bottomRow + "," + bottomCol); // System.out.println(topRow + "," + topCol + "," + bottomRow + "," + bottomCol); int tempRow = topRow; while (tempRow <= bottomRow) { int tempCol = topCol; while (tempCol <= bottomCol) { map1.put(tempRow + "," + tempCol, ""); tempCol++; } tempRow++; } map1.remove(topRow + "," + topCol); } Map[] map = { map0, map1 }; return map; } /** * 获取表格单元格Cell内容 * @param cell * @return */ private static String getCellValue(Cell cell) { String result = new String(); switch (cell.getCellType()) { case Cell.CELL_TYPE_NUMERIC:// 数字类型 if (HSSFDateUtil.isCellDateFormatted(cell)) {// 处理日期格式、时间格式 SimpleDateFormat sdf = null; if (cell.getCellStyle().getDataFormat() == HSSFDataFormat.getBuiltinFormat("h:mm")) { sdf = new SimpleDateFormat("HH:mm"); } else {// 日期 sdf = new SimpleDateFormat("yyyy-MM-dd"); } Date date = cell.getDateCellValue(); result = sdf.format(date); } else if (cell.getCellStyle().getDataFormat() == 58) { // 处理自定义日期格式:m月d日(通过判断单元格的格式id解决,id的值是58) SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd"); double value = cell.getNumericCellValue(); Date date = org.apache.poi.ss.usermodel.DateUtil .getJavaDate(value); result = sdf.format(date); } else { double value = cell.getNumericCellValue(); CellStyle style = cell.getCellStyle(); DecimalFormat format = new DecimalFormat(); String temp = style.getDataFormatString(); // 单元格设置成常规 if (temp.equals("General")) { format.applyPattern("#"); } result = format.format(value); } break; case Cell.CELL_TYPE_STRING:// String类型 result = cell.getRichStringCellValue().toString(); break; case Cell.CELL_TYPE_BLANK: result = ""; break; default: result = ""; break; } return result; } /** * 处理表格样式 * @param wb * @param sheet * @param cell * @param sb */ private static void dealExcelStyle(Workbook wb,Sheet sheet,Cell cell,StringBuffer sb){ CellStyle cellStyle = cell.getCellStyle(); if (cellStyle != null) { short alignment = cellStyle.getAlignment(); sb.append("align='" + convertAlignToHtml(alignment) + "' ");//单元格内容的水平对齐方式 short verticalAlignment = cellStyle.getVerticalAlignment(); sb.append("valign='"+ convertVerticalAlignToHtml(verticalAlignment)+ "' ");//单元格中内容的垂直排列方式 if (wb instanceof XSSFWorkbook) { XSSFFont xf = ((XSSFCellStyle) cellStyle).getFont(); short boldWeight = xf.getBoldweight(); sb.append("style='"); sb.append("font-weight:" + boldWeight + ";"); // 字体加粗 sb.append("font-size: " + xf.getFontHeight() / 2 + "%;"); // 字体大小 int columnWidth = sheet.getColumnWidth(cell.getColumnIndex()) ; sb.append("width:" + columnWidth + "px;"); XSSFColor xc = xf.getXSSFColor(); if (xc != null && !"".equals(xc)) { sb.append("color:#" + xc.getARGBHex().substring(2) + ";"); // 字体颜色 } XSSFColor bgColor = (XSSFColor) cellStyle.getFillForegroundColorColor(); //System.out.println("************************************"); //System.out.println("BackgroundColorColor: "+cellStyle.getFillBackgroundColorColor()); //System.out.println("ForegroundColor: "+cellStyle.getFillForegroundColor());//0 //System.out.println("BackgroundColorColor: "+cellStyle.getFillBackgroundColorColor()); //System.out.println("ForegroundColorColor: "+cellStyle.getFillForegroundColorColor()); //String bgColorStr = bgColor.getARGBHex(); //System.out.println("bgColorStr: "+bgColorStr); if (bgColor != null && !"".equals(bgColor)) { sb.append("background-color:#" + bgColor.getARGBHex().substring(2) + ";"); // 背景颜色 } sb.append(getBorderStyle(0,cellStyle.getBorderTop(), ((XSSFCellStyle) cellStyle).getTopBorderXSSFColor())); sb.append(getBorderStyle(1,cellStyle.getBorderRight(), ((XSSFCellStyle) cellStyle).getRightBorderXSSFColor())); sb.append(getBorderStyle(2,cellStyle.getBorderBottom(), ((XSSFCellStyle) cellStyle).getBottomBorderXSSFColor())); sb.append(getBorderStyle(3,cellStyle.getBorderLeft(), ((XSSFCellStyle) cellStyle).getLeftBorderXSSFColor())); }else if(wb instanceof HSSFWorkbook){ HSSFFont hf = ((HSSFCellStyle) cellStyle).getFont(wb); short boldWeight = hf.getBoldweight(); short fontColor = hf.getColor(); sb.append("style='"); HSSFPalette palette = ((HSSFWorkbook) wb).getCustomPalette(); // 类HSSFPalette用于求的颜色的国际标准形式 HSSFColor hc = palette.getColor(fontColor); sb.append("font-weight:" + boldWeight + ";"); // 字体加粗 sb.append("font-size: " + hf.getFontHeight() / 2 + "%;"); // 字体大小 String fontColorStr = convertToStardColor(hc); if (fontColorStr != null && !"".equals(fontColorStr.trim())) { sb.append("color:" + fontColorStr + ";"); // 字体颜色 } int columnWidth = sheet.getColumnWidth(cell.getColumnIndex()) ; sb.append("width:" + columnWidth + "px;"); short bgColor = cellStyle.getFillForegroundColor(); hc = palette.getColor(bgColor); String bgColorStr = convertToStardColor(hc); if (bgColorStr != null && !"".equals(bgColorStr.trim())) { sb.append("background-color:" + bgColorStr + ";"); // 背景颜色 } sb.append( getBorderStyle(palette,0,cellStyle.getBorderTop(),cellStyle.getTopBorderColor())); sb.append( getBorderStyle(palette,1,cellStyle.getBorderRight(),cellStyle.getRightBorderColor())); sb.append( getBorderStyle(palette,3,cellStyle.getBorderLeft(),cellStyle.getLeftBorderColor())); sb.append( getBorderStyle(palette,2,cellStyle.getBorderBottom(),cellStyle.getBottomBorderColor())); } sb.append("' "); } } /** * 单元格内容的水平对齐方式 * @param alignment * @return */ private static String convertAlignToHtml(short alignment) { String align = "left"; switch (alignment) { case CellStyle.ALIGN_LEFT: align = "left"; break; case CellStyle.ALIGN_CENTER: align = "center"; break; case CellStyle.ALIGN_RIGHT: align = "right"; break; default: break; } return align; } /** * 单元格中内容的垂直排列方式 * @param verticalAlignment * @return */ private static String convertVerticalAlignToHtml(short verticalAlignment) { String valign = "middle"; switch (verticalAlignment) { case CellStyle.VERTICAL_BOTTOM: valign = "bottom"; break; case CellStyle.VERTICAL_CENTER: valign = "center"; break; case CellStyle.VERTICAL_TOP: valign = "top"; break; default: break; } return valign; } private static String convertToStardColor(HSSFColor hc) { StringBuffer sb = new StringBuffer(""); if (hc != null) { if (HSSFColor.AUTOMATIC.index == hc.getIndex()) { return null; } sb.append("#"); for (int i = 0; i < hc.getTriplet().length; i++) { sb.append(fillWithZero(Integer.toHexString(hc.getTriplet()[i]))); } } return sb.toString(); } private static String fillWithZero(String str) { if (str != null && str.length() < 2) { return "0" + str; } return str; } static String[] bordesr={"border-top:","border-right:","border-bottom:","border-left:"}; static String[] borderStyles={"solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid ","solid","solid","solid","solid","solid"}; private static String getBorderStyle( HSSFPalette palette ,int b,short s, short t){ if(s==0)return bordesr[b]+borderStyles[s]+"#d0d7e5 1px;";; String borderColorStr = convertToStardColor( palette.getColor(t)); borderColorStr=borderColorStr==null|| borderColorStr.length()<1?"#000000":borderColorStr; return bordesr[b]+borderStyles[s]+borderColorStr+" 1px;"; } private static String getBorderStyle(int b,short s, XSSFColor xc){ if(s==0)return bordesr[b]+borderStyles[s]+"#d0d7e5 1px;";; if (xc != null && !"".equals(xc)) { String borderColorStr = xc.getARGBHex();//t.getARGBHex(); borderColorStr=borderColorStr==null|| borderColorStr.length()<1?"#000000":borderColorStr.substring(2); return bordesr[b]+borderStyles[s]+borderColorStr+" 1px;"; } return ""; }}
import java.awt.Dimension;import java.awt.Graphics2D;import java.awt.geom.Rectangle2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.FileInputStream;import java.io.FileOutputStream;import java.io.IOException;import java.io.InputStream;import java.io.OutputStream;import java.util.ArrayList;import java.util.List;import javax.imageio.ImageIO;import org.apache.poi.hslf.model.TextRun;import org.apache.poi.hslf.usermodel.RichTextRun;import org.apache.poi.hslf.usermodel.SlideShow; public class Ppt2Image {private static final int SEPARATE_DISTANCE = 100;public static void main(String[] args) throws Exception { String pptFilePath = "D:\\test\\22.dps";String imageFilePath = "D:\\test\\22.html";convertPPT2Image(pptFilePath,imageFilePath); } public static void convertPPT2Image(String pptFilePath,String imageFilePath) throws IOException { File pptFile = new File(pptFilePath); File imageFile = new File(imageFilePath); File imageFileParent = new File(imageFile.getParent()); ListmultiImageFiles = new ArrayList ();//因为一张幻灯片生成一张图片,需要将所有的图片保存起来,供后面拼装成一张图片 InputStream is = null; OutputStream out = null; try{ if(pptFile.exists()){ if(!imageFileParent.exists()){ imageFileParent.mkdirs(); } is = new FileInputStream(pptFile); SlideShow ppt = new SlideShow(is); Dimension pgSize = ppt.getPageSize(); org.apache.poi.hslf.model.Slide[] slide = ppt.getSlides(); for(int i = 0 ; i < slide.length; i++){ TextRun[] textRuns = slide[i].getTextRuns(); for(int k = 0; k < textRuns.length; k++){ RichTextRun[] richTextRuns = textRuns[k].getRichTextRuns(); for(int j = 0; j < richTextRuns.length; j++){ richTextRuns[j].setFontIndex(1); richTextRuns[j].setFontName("宋体"); } } BufferedImage image = new BufferedImage(pgSize.width,pgSize.height,BufferedImage.TYPE_INT_RGB); Graphics2D graphics = image.createGraphics(); graphics.fill(new Rectangle2D.Float(0,0,pgSize.width,pgSize.height)); slide[i].draw(graphics); String tempFileName = imageFile.getParent()+"/"+i+imageFile.getName(); out = new FileOutputStream(tempFileName); multiImageFiles.add(new File(tempFileName)); ImageIO.write(image, "jpg", out); out.close(); is.close(); } mergeMultiImageFiles(multiImageFiles,imageFile);//该方法将多个图片拼装为一张图片 } }finally{ try{ if(is != null){ is.close(); } if(out != null){ out.close(); } }catch(IOException e){ e.printStackTrace(); } } } public static void mergeMultiImageFiles(List imageFiles,File image) throws IOException { if(imageFiles != null && imageFiles.size() > 0){ BufferedImage imageNew = null; for(int i = 0 ; i < imageFiles.size(); i++){ BufferedImage imageBuffer = ImageIO.read(imageFiles.get(i)); int width = imageBuffer.getWidth(); int height = imageBuffer.getHeight(); if(imageNew == null){ imageNew = new BufferedImage(width,(height + SEPARATE_DISTANCE)* imageFiles.size(),BufferedImage.TYPE_INT_RGB); } int[] imageRgbArray = new int[width * height]; imageRgbArray = imageBuffer.getRGB(0, 0, width, height, imageRgbArray, 0, width); imageNew.setRGB(0, (height+SEPARATE_DISTANCE) * i, width, height, imageRgbArray, 0, width);//SEPARATE_DISTANCE表示两张图片的间隔距离 } ImageIO.write(imageNew, "jpg", image); } } }
import java.io.BufferedReader;import java.io.BufferedWriter;import java.io.File;import java.io.FileInputStream;import java.io.FileWriter;import java.io.IOException;import java.io.InputStreamReader; public class Txt2Html { String textHtml = ""; String color = "#00688B"; //读取文件 public void ReadFile(String filePath) { BufferedReader bu = null; InputStreamReader in = null; try { File file = new File(filePath); if (file.isFile() && file.exists()) { in = new InputStreamReader(new FileInputStream(file)); bu = new BufferedReader(in); String lineText = null; textHtml = ""; while ((lineText = bu.readLine()) != null) { lineText = changeToHtml(lineText); lineText += ""; textHtml += lineText; } textHtml += ""; } else { System.out.println("文件不存在"); } } catch (Exception e) { e.printStackTrace(); } finally { try { bu.close(); } catch (IOException e) { e.printStackTrace(); } } } //输出文件 public void writerFile(String writepath) { File file = new File(writepath); BufferedWriter output = null; try { output = new BufferedWriter(new FileWriter(file)); System.out.println(textHtml); output.write(textHtml); } catch (IOException e) { e.printStackTrace(); } finally { try { output.close(); } catch (IOException e) { e.printStackTrace(); } } } //文件转换 public String changeToHtml(String text) { text = text.replace("&", "&"); text = text.replace(" ", " "); text = text.replace("<", "<"); text = text.replace(">", ">"); //text = text.replace("\"", """); text = text.replace(" ", " "); text = text.replace("public", "public"); text = text.replace("class", "class"); text = text.replace("static", "static"); text = text.replace("void", "void"); String t = text.replace("//", "//"); if (!text.equals(t)) { System.out.println("t:"+t); text = t + ""; } return text; } /*String filename = "D:\\test\\新建文本文档.txt";String outPutFile = "D:\\test\\新建文本文档.html";*/ public static void txt2Html(String filename,String outPutFile) { Txt2Html c = new Txt2Html(); c.ReadFile(filename); c.writerFile(outPutFile); }}
阅读全文
0 0
- java poi附件预览
- POI 附件在线预览
- java实现附件预览(openoffice+swfTools+FlexPaper)
- java实现附件预览(openoffice+swfTools+FlexPaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+PDF.js)
- Java实现在线预览附件 office转换PDF
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- java实现附件预览(openoffice+swftools+flexpaper)
- mantis附件图片预览
- 网页开发预览附件
- Android 附件预览
- 理解Golang包导入
- 温州嵌入式培训机构
- 计算机系统基础(bomb实验报告)
- android studio如何查看 e.printStackTrace()
- selenium工作原理
- java poi附件预览
- js及jQuery中的各种宽高
- 多校第四场1004 HDU 6070 Dirt Ratio
- java继承实质、父类引用指向子类对象(多态)、声明时类型、运行时类型
- Java进阶(三)多线程开发关键技术
- 深入理解Java集合框架系列-第四章java中的队列
- 53/152 Maximum Product Subarray /Maximum Subarray(子序列之 和/积 最大)
- 8.1~8.12eg刷题记录
- Git版本控制学习(二)