在这里,我有一些Excel文件,我想将包含形状的图纸转换为图像。但不幸的是,没有接口支持这种功能。图像的形状不同,它们是矢量,我只能得到一些有关文本或数学的信息。我无法获取它们的字节值,也无法在图像或HTML文件中呈现它们。如果我将excel转换为pdf,形状将受到不同程度的损坏。我已经尝试了近一个月,并进行了大量搜索。但是没有什么可以满足这样的要求。
我该怎么做才能做到?
这是寻求帮助的代码。
@SuppressWarnings("unchecked")
public static void xlsToImage(HSSFSheet sheet,String userAccount) {
HSSFPatriarch hp = sheet.getDrawingPatriarch();
List<HSSFShape> shapes = hp.getChildren();
if(shapes.size() > 0) {// I need help from here.
for(HSSFShape hssfShape : shapes)
{
hssfShape.getAnchor().getDx1();
}
}
}
这是将excel文件转换为pdf文件的代码。
public class Test {
/**
* 获取license
*
* @return
*/
public static boolean getLicense() {
boolean result = false;
try {
InputStream is = Test.class.getClassLoader().getResourceAsStream("\\license.xml");
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
/**
* 支持DOC, DOCX, OOXML, RTF, HTML, OpenDocument, PDF, EPUB, XPS, SWF等相互转换<br>
*
* @param args
*/
public static void main(String[] args) {
// 验证License
if (!getLicense()) {
return;
}
try {
long old = System.currentTimeMillis();
Workbook wb = new Workbook("C:\\Users\\Administrator\\Desktop\\1.逻辑结构图-灾备.xls");// 原始excel路径
File pdfFile = new File("C:\\Users\\Administrator\\Desktop\\test2.pdf");// 输出路径
FileOutputStream fileOS = new FileOutputStream(pdfFile);
wb.save(fileOS, SaveFormat.PDF);
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
}
任何答案将不胜感激。
最佳答案
所需的罐子
poi-3.17.jar
poi-examples-3.17.jar
poi-excelant-3.17.jar
poi-ooxml-3.17.jar
poi-ooxml-schemas-3.15.0.jar
dom4j-1.6.1.jar
poi-scratchpad-3.17.jar
xmlbeans-2.6.0.jar
/**
* filetype
*/
if("DOC".equals(filetype)){
FileUtil.folderfilehtml(ctxPath + filelocalname, zid, ctxPath);
}else if("XLS".equals(filetype)||"XLSX".equals(filetype)){
FileUtil.folderfileExceltohtml(ctxPath + filelocalname, zid, ctxPath);
}else if("PDF".equals(filetype)){
FileUtil.pdf2html("C:\\application\\pdf2htmlEX-v1.0\\pdf2htmlEX.exe",ctxPath + filelocalname,application.getRealPath("/")+DOWNLOADPATH.get("folderpdf"),zid+".html");
}else if("PPT".equals(filetype)){
FileUtil.pptToHtml(ctxPath + filelocalname, zid, ctxPath,webpath);
}
/**
* word to HTML
*
*/
public static void folderfilehtml(String filename, String htmlid, String ctxPath) throws IOException, ParserConfigurationException, TransformerException{
InputStream input = new FileInputStream(filename);
HWPFDocument wordDocument = new HWPFDocument(input);
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 suggestedName;
}
});
wordToHtmlConverter.processDocument(wordDocument);
List pics = wordDocument.getPicturesTable().getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get(i);
try {
pic.writeImageContent(new FileOutputStream(ctxPath
+ pic.suggestFullFileName()));
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument = wordToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource(htmlDocument);
StreamResult streamResult = new StreamResult(outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty(OutputKeys.ENCODING, "GB2312");
serializer.setOutputProperty(OutputKeys.INDENT, "yes");
serializer.setOutputProperty(OutputKeys.METHOD, "html");
serializer.transform(domSource, streamResult);
outStream.close();
String content = new String(outStream.toByteArray());
String conut =content.substring(0,content.lastIndexOf("</head>"));
String countend=content.substring(content.indexOf("</head>")-1,content.length());
conut+="<input type="+"button"+" value="+"Print"+" href="+"javascript:void(0);"+" onclick="+"window.print();"+" class="+"noprint"+" style="+"height:30px;width: 60px; padding-right:5px;align:right;float:left;FONT-WEIGHT: bold;FONT-SIZE: 12pt;COLOR: #000000;FONT-FAMILY: Arial"+">";
content=conut+countend;
FileUtils.writeStringToFile(new File(ctxPath, htmlid+".html"), content);
}
/**
* Excel to HTML
*
*/
public static void folderfileExceltohtml(String filename, String htmlid, String ctxPath) throws IOException, ParserConfigurationException, TransformerException{
InputStream input=new FileInputStream(filename);
HSSFWorkbook excelBook=new HSSFWorkbook(input);
ExcelToHtmlConverter excelToHtmlConverter = new ExcelToHtmlConverter (DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument() );
excelToHtmlConverter.processWorkbook(excelBook);
List pics = excelBook.getAllPictures();
if (pics != null) {
for (int i = 0; i < pics.size(); i++) {
Picture pic = (Picture) pics.get (i);
try {
pic.writeImageContent (new FileOutputStream (ctxPath + pic.suggestFullFileName() ) );
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
Document htmlDocument =excelToHtmlConverter.getDocument();
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
DOMSource domSource = new DOMSource (htmlDocument);
StreamResult streamResult = new StreamResult (outStream);
TransformerFactory tf = TransformerFactory.newInstance();
Transformer serializer = tf.newTransformer();
serializer.setOutputProperty (OutputKeys.ENCODING, "GB2312");
serializer.setOutputProperty (OutputKeys.INDENT, "yes");
serializer.setOutputProperty (OutputKeys.METHOD, "html");
serializer.transform (domSource, streamResult);
outStream.close();
String content = new String (outStream.toByteArray() );
String conut =content.substring(0,content.lastIndexOf("</head>"));
String countend=content.substring(content.indexOf("</head>")-1,content.length());
conut+="<input type="+"button"+" value="+"打印"+" href="+"javascript:void(0);"+" onclick="+"window.print();"+" class="+"noprint"+" style="+"height:30px;width: 60px; padding-right:5px;align:right;float:left;FONT-WEIGHT: bold;FONT-SIZE: 12pt;COLOR: #000000;FONT-FAMILY: Arial"+">";
content=conut+countend;
FileUtils.writeStringToFile(new File (ctxPath, htmlid+".html"), content);
}
/**
* PDF to HTML
*/
/**
* @param ises
* @return
* @throws IOException
*/
/**
*
* @param exeFilePath
* @param pdfFile
* @param [destDir]
* @param htmlName
* @return
*/
public static boolean pdf2html(String exeFilePath, String pdfFile,
String destDir, String htmlFileName) {
if (!(exeFilePath != null && !"".equals(exeFilePath) && pdfFile != null
&& !"".equals(pdfFile) && htmlFileName != null && !""
.equals(htmlFileName))) {
System.out.println("传递的参数有误!");
return false;
}
Runtime rt = Runtime.getRuntime();
StringBuilder command = new StringBuilder();
command.append(exeFilePath).append(" ");
if (destDir != null && !"".equals(destDir.trim()))
command.append("--dest-dir ").append(destDir.replace(" ", "\" \""))
.append(" ");
command.append("--optimize-text 1 ");
command.append("--zoom 1.4 ");
command.append("--process-outline 0 ");
command.append("--font-format woff ");
// ttf,otf,woff,svg
command.append(pdfFile.replace(" ", "\" \"")).append(" ");
if (htmlFileName != null && !"".equals(htmlFileName.trim())) {
command.append(htmlFileName);
if (htmlFileName.indexOf(".html") == -1)
command.append(".html");
}
try {
Process p = rt.exec(command.toString());
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(),
"ERROR");
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(),
"STDOUT");
outGobbler.start();
int w = p.waitFor();
int v = p.exitValue();
if (w == 0 && v == 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
public static boolean pdf2html_linux(String pdfFile, String destDir,
String htmlFileName) {
if (!(pdfFile != null && !"".equals(pdfFile) && htmlFileName != null && !""
.equals(htmlFileName))) {
System.out.println("传递的参数有误!");
return false;
}
Runtime rt = Runtime.getRuntime();
StringBuilder command = new StringBuilder();
command.append("pdf2htmlEX").append(" ");
if (destDir != null && !"".equals(destDir.trim()))
command.append("--dest-dir ").append(destDir.replace(" ", "\" \""))
.append(" ");
command.append("--optimize-text 1 ");
command.append("--process-outline 0 ");
command.append("--font-format woff ");
// ttf,otf,woff,svg
command.append(pdfFile.replace(" ", "\" \"")).append(" ");
if (htmlFileName != null && !"".equals(htmlFileName.trim())) {
command.append(htmlFileName);
if (htmlFileName.indexOf(".html") == -1)
command.append(".html");
}
try {
Process p = rt.exec(command.toString());
StreamGobbler errorGobbler = new StreamGobbler(p.getErrorStream(),
"ERROR");
errorGobbler.start();
StreamGobbler outGobbler = new StreamGobbler(p.getInputStream(),
"STDOUT");
outGobbler.start();
int w = p.waitFor();
int v = p.exitValue();
if (w == 0 && v == 0) {
return true;
}
} catch (Exception e) {
e.printStackTrace();
}
return false;
}
/**
* PPT to HTML
* @param path
* @param filename
* @return
*/
public static void pptToHtml(String sourcePath, String id, String targetDir,String webpath) {
File pptFile = new File(sourcePath);
if (pptFile.exists()) {
try {
String type = com.util.FileUtils.GetFileExt(sourcePath);
if ("ppt".equals(type)) {
String htmlStr = toImage2003(sourcePath, targetDir,id,webpath);
com.util.FileUtils.writeFile(htmlStr, targetDir + "\\"+id+".html");
} else if ("pptx".equals(type)) {
String htmlStr = toImage2007(sourcePath, targetDir, id,webpath);
com.util.FileUtils.writeFile(htmlStr, targetDir + "\\"+id+".html");
} else {
System.out.println("the file is not a ppt");
}
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
System.out.println("file does not exist!");
}
}
public static String toImage2007(String sourcePath, String targetDir, String pptFileName, String webpath) throws Exception {
String htmlStr = "";
FileInputStream is = new FileInputStream(sourcePath);
XMLSlideShow ppt = new XMLSlideShow(is);
is.close();
com.util.FileUtils.createDir(targetDir);// create html dir
Dimension pgsize = ppt.getPageSize();
System.out.println(pgsize.width + "--" + pgsize.height);
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ppt.getSlides().size(); i++) {
try {
// 防止中文乱码
for (XSLFShape shape : ppt.getSlides().get(i).getShapes()) {
if (shape instanceof XSLFTextShape) {
XSLFTextShape tsh = (XSLFTextShape) shape;
for (XSLFTextParagraph p : tsh) {
for (XSLFTextRun r : p) {
r.setFontFamily("宋体");
}
}
}
}
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
ppt.getSlides().get(i).draw(graphics);
// save the output
String imageDir = targetDir + pptFileName + "\\";
com.util.FileUtils.createDir(imageDir);// create image dir
String imagePath = imageDir + pptFileName + "-" + (i + 1) + ".png";
String imagewebpath = webpath+pptFileName+"\\"+ pptFileName + "-" + (i + 1) + ".png";
sb.append("<html>");
sb.append("<body>");
sb.append("<input type=button value=Print href="+"javascript:void(0);"+" onclick="+"window.print();"+" class="+"noprint"+" style="+"height:30px;width: 60px; padding-right:5px;align:right;float:left;FONT-WEIGHT: bold;FONT-SIZE: 12pt;COLOR: #000000;FONT-FAMILY: Arial"+">");
sb.append("<br />");
sb.append("<p style=text-align:center;>");
sb.append("<img src=" + "\"" + imagewebpath + "\"" + "/>");
sb.append("</p>");
sb.append("<br />");
sb.append("</html>");
sb.append("</body>");
FileOutputStream out = new FileOutputStream(imagePath);
javax.imageio.ImageIO.write(img, "png", out);
out.close();
} catch (Exception e) {
System.out.println("第" + i + "张ppt转换出错");
}
}
System.out.println("success");
htmlStr = sb.toString();
return htmlStr;
}
public static String toImage2003(String sourcePath, String targetDir, String pptFileName,String webpath) {
String htmlStr = "";
try {
HSLFSlideShow ppt = new HSLFSlideShow(new HSLFSlideShowImpl(sourcePath));
com.util.FileUtils.createDir(targetDir);// create html dir
Dimension pgsize = ppt.getPageSize();
StringBuffer sb = new StringBuffer();
for (int i = 0; i < ppt.getSlides().size(); i++) {
// 防止中文乱码
for (HSLFShape shape : ppt.getSlides().get(i).getShapes()) {
if (shape instanceof HSLFTextShape) {
HSLFTextShape tsh = (HSLFTextShape) shape;
for (HSLFTextParagraph p : tsh) {
for (HSLFTextRun r : p) {
r.setFontFamily("宋体");
}
}
}
}
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
ppt.getSlides().get(i).draw(graphics);
String imageDir = targetDir + pptFileName + "\\";
com.util.FileUtils.createDir(imageDir);// create image dir
String imagePath = imageDir + pptFileName + "-" + (i + 1) + ".png";
String imagewebpath = webpath +pptFileName+"\\"+ pptFileName + "-" + (i + 1) + ".png";
sb.append("<html>");
sb.append("<body>");
sb.append("<input type="+"button"+" value="+"Print"+" href="+"javascript:void(0);"+" onclick="+"window.print();"+" class="+"noprint"+" style="+"height:30px;width: 60px; padding-right:5px;align:right;float:left;FONT-WEIGHT: bold;FONT-SIZE: 12pt;COLOR: #000000;FONT-FAMILY: Arial"+">");
sb.append("<br />");
sb.append("<p style=text-align:center;>");
sb.append("<img src=" + "\"" + imagewebpath + "\"" + "/>");
sb.append("</p>");
sb.append("<br />");
sb.append("</html>");
sb.append("</body>");
FileOutputStream out = new FileOutputStream(imagePath);
javax.imageio.ImageIO.write(img, "png", out);
out.close();
}
System.out.println("success");
htmlStr = sb.toString();
} catch (Exception e) {
}
return htmlStr;
}