热门标签 | HotTags
当前位置:  开发笔记 > 前端 > 正文

Java实现Word/Pdf/TXT转html的实例代码

本文主要介绍了Java实现WordPdfTXT转html的实例代码,代码简单易懂,非常不错,具有一定的参考借鉴价值,需要的朋友可以参考下

引言:

最近公司在做一个教育培训学习及在线考试的项目,本人主要从事网络课程模块,主要做课程分类,课程,课件的创建及在线学习和统计的功能,因为课件涉及到多种类型,像视频,音频,图文,外部链接及文档类型.其中就涉及到一个问题,就是文档型课件课程在网页上的展示和学习问题,因为要在线统计学习的课程,学习的人员,学习的时长,所以不能像传统做法将文档下载到本地学习,那样就不受系统控制了,所以最终的方案是,在上传文档型课件的时候,将其文件对应的转换成HTML文件,以便在网页上能够浏览学习

下边主要针对word,pdf和txt文本文件进行转换

一:Java实现将word转换为html

1:引入依赖

 
  fr.opensagres.xdocreport
  fr.opensagres.xdocreport.document
  1.0.5
 
  
  fr.opensagres.xdocreport 
  org.apache.poi.xwpf.converter.xhtml 
  1.0.5 
 
  
  org.apache.poi
  poi
  3.12
 
 
  org.apache.poi
  poi-scratchpad
  3.12
 

2:代码demo

package com.svse.controller;
  
  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 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.xwpf.converter.core.BasicURIResolver;
 import org.apache.poi.xwpf.converter.core.FileImageExtractor;
 import org.apache.poi.xwpf.converter.core.FileURIResolver;
 import org.apache.poi.xwpf.converter.core.IURIResolver;
 import org.apache.poi.xwpf.converter.core.IXWPFConverter;
 import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
 import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
 import org.apache.poi.xwpf.usermodel.XWPFDocument;
 /**
 * word 转换成html
 */
public class TestWordToHtml {
 
  public static final String STORAGEPATH="C://works//files//";
   public static final String IP="192.168.30.222";
   public static final String PORT="8010";
  public static void main(String[] args) throws IOException, TransformerException, ParserConfigurationException {
   TestWordToHtml wt=new TestWordToHtml();
    //wt.Word2003ToHtml("甲骨文考证.doc");
    wt.Word2007ToHtml("甲骨文考证.docx");

  }
    
   /**
   * 2003版本word转换成html
   * @throws IOException
   * @throws TransformerException
   * @throws ParserConfigurationException
    */
  public void Word2003ToHtml(String fileName) throws IOException, TransformerException, ParserConfigurationException {
    
     final String imagepath = STORAGEPATH+"fileImage/";//解析时候如果doc文件中有图片 图片会保存在此路径
    final String strRanString=getRandomNum();
    String filepath =STORAGEPATH;
    String htmlName =fileName.substring(0, fileName.indexOf("."))+ "2003.html";
    final String file = filepath + fileName;
    InputStream input = new FileInputStream(new File(file));
    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) {
        File imgPath = new File(imagepath);
        if(!imgPath.exists()){//图片目录不存在则创建
          imgPath.mkdirs();
        }
         
        File file = new File(imagepath +strRanString+suggestedName);
        try {
           OutputStream os = new FileOutputStream(file);
           os.write(content);
           os.close();
        } catch (FileNotFoundException e) {
           e.printStackTrace();
         } catch (IOException e) {
           e.printStackTrace();
        }
         
        return "http://"+IP+":"+PORT+"//uploadFile/fileImage/"+strRanString+suggestedName;
       // return imagepath +strRanString+suggestedName;
      }
    });
    
     //解析word文档
    wordToHtmlConverter.processDocument(wordDocument);
     Document htmlDocument = wordToHtmlConverter.getDocument();
     
     File htmlFile = new File(filepath +strRanString+htmlName);
    OutputStream outStream = new FileOutputStream(htmlFile);
     

     DOMSource domSource = new DOMSource(htmlDocument);
    StreamResult streamResult = new StreamResult(outStream);
 
    TransformerFactory factory = TransformerFactory.newInstance();
     Transformer serializer = factory.newTransformer();
    serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
    serializer.setOutputProperty(OutputKeys.INDENT, "yes");
    serializer.setOutputProperty(OutputKeys.METHOD, "html");
    
    serializer.transform(domSource, streamResult);
     outStream.close();
     
    System.out.println("生成html文件路径:"+ "http://"+IP+":"+PORT+"//uploadFile/"+strRanString+htmlName);
   }
   /**
   * 2007版本word转换成html
   * @throws IOException
   */
   public void Word2007ToHtml(String fileName) throws IOException {
    final String strRanString=getRandomNum();
     String filepath = STORAGEPATH+strRanString;
     String htmlName =fileName.substring(0, fileName.indexOf("."))+ "2007.html";
     File f = new File(STORAGEPATH+fileName); 
     if (!f.exists()) { 
       System.out.println("Sorry File does not Exists!"); 
     } else { 
       if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) { 
         try {
           // 1) 加载word文档生成 XWPFDocument对象 
           InputStream in = new FileInputStream(f); 
           XWPFDocument document = new XWPFDocument(in); 
           // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录) 
           File imageFolderFile = new File(filepath); 
           XHTMLOptions optiOns= XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile)); 
           options.setExtractor(new FileImageExtractor(imageFolderFile)); 
           options.URIResolver(new IURIResolver() {
             public String resolve(String uri) {
               //http://192.168.30.222:8010//uploadFile/....
               return "http://"+IP+":"+PORT+"//uploadFile/"+strRanString +"/"+ uri;
             }
           });
           options.setIgnoreStylesIfUnused(false); 
           options.setFragment(true); 
           // 3) 将 XWPFDocument转换成XHTML 
           OutputStream out = new FileOutputStream(new File(filepath + htmlName)); 
           IXWPFConverter cOnverter= XHTMLConverter.getInstance();
           converter.convert(document,out, options);
           //XHTMLConverter.getInstance().convert(document, out, options); 
           System.out.println("html路径:"+"http://"+IP+":"+PORT+"//uploadFile/"+strRanString+htmlName);
         } catch (Exception e) {
           e.printStackTrace();
         }
       } else { 
         System.out.println("Enter only MS Office 2007+ files"); 
       } 
     } 
   } 
   /**
   *功能说明:生成时间戳
   *创建人:zsq
   *创建时间:2019年12月7日 下午2:37:09
   *
   */
   public static String getRandomNum(){
     Date dt = new Date();
     SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); 
     String str=sdf.format(dt);
     return str;
   }
  }

二:Java实现将Pdf转换为html

1: 引入依赖

 
       net.sf.cssbox
       pdf2dom
       1.7
      
     
       org.apache.pdfbox
       pdfbox
       2.0.12
     
     
       org.apache.pdfbox
       pdfbox-tools
       2.0.12
 

2:代码Demo

 public class PdfToHtml { 
  /*
   pdf转换html
   */
   public void pdfToHtmlTest(String inPdfPath,String outputHtmlPath) {
     // String outputPath = "C:\\works\\files\\ZSQ保密知识测试题库.html";
       //try() 写在()里面会自动关闭流
     try{
       BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputHtmlPath)),"utf-8"));
       //加载PDF文档
       //PDDocument document = PDDocument.load(bytes);
       PDDocument document = PDDocument.load(new File(inPdfPath));
       PDFDomTree pdfDomTree = new PDFDomTree();
       pdfDomTree.writeText(document,out);
     } catch (Exception e) {
       e.printStackTrace();
     }
   }
   public static void main(String[] args) throws IOException {
     PdfToHtml ph=new PdfToHtml();
     String pdfPath="C:\\works\\files\\武研中心行政考勤制度.pdf";
     String outputPath="C:\\works\\files\\武研中心行政考勤制度.html";
     ph.pdfToHtmlTest(pdfPath,outputPath);
  }
 }

三:Java实现将TXT转换为html

 /*
    * txt文档转html
     filePath:txt原文件路径
     htmlPosition:转化后生成的html路径
   */
   public static void txtToHtml(String filePath, String htmlPosition) {
     try {
       //String encoding = "GBK";
       File file = new File(filePath);
       if (file.isFile() && file.exists()) { // 判断文件是否存在
         InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
         // 考虑到编码格式
         BufferedReader bufferedReader = new BufferedReader(read);
         // 写文件
         FileOutputStream fos = new FileOutputStream(new File(htmlPosition));
         OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
         BufferedWriter bw = new BufferedWriter(osw);
         String lineTxt = null;
         while ((lineTxt = bufferedReader.readLine()) != null) {
           bw.write("  "+lineTxt + "
"); } bw.close(); osw.close(); fos.close(); read.close(); } else { System.out.println("找不到指定的文件"); } } catch (Exception e) { System.out.println("读取文件内容出错"); e.printStackTrace(); } }

总结

到此这篇关于Java实现Word/Pdf/TXT转html的实例代码的文章就介绍到这了,更多相关java word pdf txt 转html内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!


推荐阅读
  • 解决JAX-WS动态客户端工厂弃用问题并迁移到XFire
    在处理Java项目中的JAR包冲突时,我们遇到了JaxWsDynamicClientFactory被弃用的问题,并成功将其迁移到org.codehaus.xfire.client。本文详细介绍了这一过程及解决方案。 ... [详细]
  • PHP 5.5.0rc1 发布:深入解析 Zend OPcache
    2013年5月9日,PHP官方发布了PHP 5.5.0rc1和PHP 5.4.15正式版,这两个版本均支持64位环境。本文将详细介绍Zend OPcache的功能及其在Windows环境下的配置与测试。 ... [详细]
  • QUIC协议:快速UDP互联网连接
    QUIC(Quick UDP Internet Connections)是谷歌开发的一种旨在提高网络性能和安全性的传输层协议。它基于UDP,并结合了TLS级别的安全性,提供了更高效、更可靠的互联网通信方式。 ... [详细]
  • 深入理解OAuth认证机制
    本文介绍了OAuth认证协议的核心概念及其工作原理。OAuth是一种开放标准,旨在为第三方应用提供安全的用户资源访问授权,同时确保用户的账户信息(如用户名和密码)不会暴露给第三方。 ... [详细]
  • 2023 ARM嵌入式系统全国技术巡讲旨在分享ARM公司在半导体知识产权(IP)领域的最新进展。作为全球领先的IP提供商,ARM在嵌入式处理器市场占据主导地位,其产品广泛应用于90%以上的嵌入式设备中。此次巡讲将邀请来自ARM、飞思卡尔以及华清远见教育集团的行业专家,共同探讨当前嵌入式系统的前沿技术和应用。 ... [详细]
  • 国内BI工具迎战国际巨头Tableau,稳步崛起
    尽管商业智能(BI)工具在中国的普及程度尚不及国际市场,但近年来,随着本土企业的持续创新和市场推广,国内主流BI工具正逐渐崭露头角。面对国际品牌如Tableau的强大竞争,国内BI工具通过不断优化产品和技术,赢得了越来越多用户的认可。 ... [详细]
  • 本文详细分析了JSP(JavaServer Pages)技术的主要优点和缺点,帮助开发者更好地理解其适用场景及潜在挑战。JSP作为一种服务器端技术,广泛应用于Web开发中。 ... [详细]
  • 本文介绍如何在 Xcode 中使用快捷键和菜单命令对多行代码进行缩进,包括右缩进和左缩进的具体操作方法。 ... [详细]
  • 本文详细介绍了 Java 中 org.apache.xmlbeans.SchemaType 类的 getBaseEnumType() 方法,提供了多个代码示例,并解释了其在不同场景下的使用方法。 ... [详细]
  • 本文介绍如何在Java项目中使用Log4j库进行日志记录。我们将详细说明Log4j库的引入、配置及简单应用,帮助开发者快速上手。 ... [详细]
  • 本文详细介绍了如何解决MyBatis中常见的BindingException错误,提供了多种排查和修复方法,确保Mapper接口与XML文件的正确配置。 ... [详细]
  • 基于KVM的SRIOV直通配置及性能测试
    SRIOV介绍、VF直通配置,以及包转发率性能测试小慢哥的原创文章,欢迎转载目录?1.SRIOV介绍?2.环境说明?3.开启SRIOV?4.生成VF?5.VF ... [详细]
  • 本文探讨了在通过 API 端点调用时,使用猫鼬(Mongoose)的 findOne 方法总是返回 null 的问题,并提供了详细的解决方案和建议。 ... [详细]
  • 探讨如何真正掌握Java EE,包括所需技能、工具和实践经验。资深软件教学总监李刚分享了对毕业生简历中常见问题的看法,并提供了详尽的标准。 ... [详细]
  • 探讨了小型企业在构建安全网络和软件时所面临的挑战和机遇。本文介绍了如何通过合理的方法和工具,确保小型企业能够有效提升其软件的安全性,从而保护客户数据并增强市场竞争力。 ... [详细]
author-avatar
平凡随缘2010
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有