展开菜单
首页 精品内容 本月促销 装机必备 Windows PDF教程 macOS软件 IOS软件 Android AI 专题
全部分类

当前位置:

首页 > 编程开发 > Java怎么实现Word/Pdf/TXT转html

Java怎么实现Word/Pdf/TXT转html

一:Java实现将word转换为html1:引入依赖12fr.opensagres.xdocreport3fr.opensagres.xdocreport.document41.0.5567fr.opensagres.xdocreport8org.apache.poi.xwpf.converter.xhtml91.0.5101112org.apache.poi13poi143.12151617org.apache.poi18poi-scratchpad193.12202:代码demo1packagecom

本文目录

    一:Java实现将word转换为html

       1:引入依赖

     1 
     2   fr.opensagres.xdocreport
     3   fr.opensagres.xdocreport.document
     4   1.0.5
     5 
     6  
     7   fr.opensagres.xdocreport 
     8   org.apache.poi.xwpf.converter.xhtml 
     9   1.0.5 
    10 
    11   
    12   org.apache.poi
    13   poi
    14   3.12
    15 
    16 
    17   org.apache.poi
    18   poi-scratchpad
    19   3.12
    20 

      2:代码demo

      1 package com.svse.controller;
      2 
      3 import javax.xml.parsers.DocumentBuilderFactory;
      4 import javax.xml.parsers.ParserConfigurationException;
      5 import javax.xml.transform.OutputKeys;
      6 import javax.xml.transform.Transformer;
      7 import javax.xml.transform.TransformerException;
      8 import javax.xml.transform.TransformerFactory;
      9 import javax.xml.transform.dom.DOMSource;
     10 import javax.xml.transform.stream.StreamResult;
     11 
     12 import org.apache.poi.hwpf.HWPFDocument;
     13 import org.apache.poi.hwpf.converter.PicturesManager;
     14 import org.apache.poi.hwpf.converter.WordToHtmlConverter;
     15 import org.apache.poi.hwpf.usermodel.PictureType;
     16 import org.apache.poi.xwpf.converter.core.BasicURIResolver;
     17 import org.apache.poi.xwpf.converter.core.FileImageExtractor;
     18 import org.apache.poi.xwpf.converter.core.FileURIResolver;
     19 import org.apache.poi.xwpf.converter.core.IURIResolver;
     20 import org.apache.poi.xwpf.converter.core.IXWPFConverter;
     21 import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
     22 import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
     23 import org.apache.poi.xwpf.usermodel.XWPFDocument;
     24 /**
     25  * word 转换成html
     26  */
     27 public class TestWordToHtml {
     28 
     29     public static  final String STORAGEPATH="C://works//files//";
     30     public static  final String IP="192.168.30.222";
     31     public static  final String PORT="8010";
     32     public static void main(String[] args) throws IOException, TransformerException, ParserConfigurationException {
     33         TestWordToHtml wt=new TestWordToHtml();
     34         //wt.Word2003ToHtml("甲骨文考证.doc");
     35         wt.Word2007ToHtml("甲骨文考证.docx");
     36 
     37     }
     38       
     39      /**
     40      * 2003版本word转换成html
     41      * @throws IOException
     42      * @throws TransformerException
     43      * @throws ParserConfigurationException
     44      */
     45     public void Word2003ToHtml(String fileName) throws IOException, TransformerException, ParserConfigurationException {
     46        
     47         final String imagepath = STORAGEPATH+"fileImage/";//解析时候如果doc文件中有图片  图片会保存在此路径
     48         final String strRanString=getRandomNum();
     49         String filepath =STORAGEPATH;
     50         String htmlName =fileName.substring(0, fileName.indexOf("."))+ "2003.html";
     51         final String file = filepath + fileName;
     52         InputStream input = new FileInputStream(new File(file));
     53         HWPFDocument wordDocument = new HWPFDocument(input);
     54         WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
     55         //设置图片存放的位置
     56         wordToHtmlConverter.setPicturesManager(new PicturesManager() {
     57             public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches, float heightInches) {
     58                 File imgPath = new File(imagepath);
     59                 if(!imgPath.exists()){//图片目录不存在则创建
     60                     imgPath.mkdirs();
     61                 }
     62                 
     63                 File file = new File(imagepath +strRanString+suggestedName);
     64                 try {
     65                     OutputStream os = new FileOutputStream(file);
     66                     os.write(content);
     67                     os.close();
     68                 } catch (FileNotFoundException e) {
     69                     e.printStackTrace();
     70                 } catch (IOException e) {
     71                     e.printStackTrace();
     72                 }
     73                 
     74                 return  "http://"+IP+":"+PORT+"//uploadFile/fileImage/"+strRanString+suggestedName;
     75                // return imagepath +strRanString+suggestedName;
     76             }
     77         });
     78         
     79         //解析word文档
     80         wordToHtmlConverter.processDocument(wordDocument);
     81         Document htmlDocument = wordToHtmlConverter.getDocument();
     82         
     83         File htmlFile = new File(filepath +strRanString+htmlName);
     84         OutputStream outStream = new FileOutputStream(htmlFile);
     85         
     86 
     87         DOMSource domSource = new DOMSource(htmlDocument);
     88         StreamResult streamResult = new StreamResult(outStream);
     89 
     90         TransformerFactory factory = TransformerFactory.newInstance();
     91         Transformer serializer = factory.newTransformer();
     92         serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
     93         serializer.setOutputProperty(OutputKeys.INDENT, "yes");
     94         serializer.setOutputProperty(OutputKeys.METHOD, "html");
     95         
     96         serializer.transform(domSource, streamResult);
     97         outStream.close();
     98         
     99         System.out.println("生成html文件路径:"+ "http://"+IP+":"+PORT+"//uploadFile/"+strRanString+htmlName);
    100     }
    101 
    102     /**
    103      * 2007版本word转换成html
    104      * @throws IOException
    105      */
    106     public void Word2007ToHtml(String fileName) throws IOException {
    107         
    108        final String strRanString=getRandomNum();
    109         
    110         String filepath = STORAGEPATH+strRanString;
    111         String htmlName =fileName.substring(0, fileName.indexOf("."))+ "2007.html";
    112         File f = new File(STORAGEPATH+fileName);  
    113         if (!f.exists()) {  
    114             System.out.println("Sorry File does not Exists!");  
    115         } else {  
    116             if (f.getName().endsWith(".docx") || f.getName().endsWith(".DOCX")) {  
    117                 try {
    118                     // 1) 加载word文档生成 XWPFDocument对象  
    119                     InputStream in = new FileInputStream(f);  
    120                     XWPFDocument document = new XWPFDocument(in);  
    121       
    122                     // 2) 解析 XHTML配置 (这里设置IURIResolver来设置图片存放的目录)  
    123                     File imageFolderFile = new File(filepath);  
    124                     XHTMLOptions options = XHTMLOptions.create().URIResolver(new FileURIResolver(imageFolderFile));  
    125                     options.setExtractor(new FileImageExtractor(imageFolderFile));  
    126                     options.URIResolver(new IURIResolver() {
    127                         public String resolve(String uri) {
    128                             //http://192.168.30.222:8010//uploadFile/....
    129                             return "http://"+IP+":"+PORT+"//uploadFile/"+strRanString +"/"+ uri;
    130                         }
    131                     });
    132                     
    133                     options.setIgnoreStylesIfUnused(false);  
    134                     options.setFragment(true);  
    135                       
    136                     // 3) 将 XWPFDocument转换成XHTML  
    137                     OutputStream out = new FileOutputStream(new File(filepath + htmlName));  
    138                     IXWPFConverter converter = XHTMLConverter.getInstance();
    139                     converter.convert(document,out, options);
    140                     //XHTMLConverter.getInstance().convert(document, out, options);  
    141                     System.out.println("html路径:"+"http://"+IP+":"+PORT+"//uploadFile/"+strRanString+htmlName);
    142                 } catch (Exception e) {
    143                     e.printStackTrace();
    144                 }
    145             
    146             } else {  
    147                 System.out.println("Enter only MS Office 2007+ files");  
    148             }  
    149         }  
    150     }  
    151 
    152      /**
    153      *功能说明:生成时间戳
    154      *创建人:zsq
    155      *创建时间:2019年12月7日 下午2:37:09
    156      *
    157      */
    158      public static String getRandomNum(){
    159          Date dt = new Date();
    160          SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss");  
    161          String str=sdf.format(dt);
    162          return str;
    163      }
    164      
    165    }

    二:Java实现将Pdf转换为html

      1: 引入依赖

     1 
     2             net.sf.cssbox
     3             pdf2dom
     4             1.7
     5          
     6         
     7             org.apache.pdfbox
     8             pdfbox
     9             2.0.12
    10         
    11         
    12             org.apache.pdfbox
    13             pdfbox-tools
    14             2.0.12
    15  
    16

    2:代码Demo

     1 public class PdfToHtml {
     2 
     3   /*
     4     pdf转换html
     5      */
     6     public void pdfToHtmlTest(String inPdfPath,String outputHtmlPath)  {
     7        // String outputPath = "C:\\works\\files\\ZSQ保密知识测试题库.html";
     8     9        //try() 写在()里面会自动关闭流
    10         try{
    11             BufferedWriter out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(outputHtmlPath)),"utf-8"));
    12             //加载PDF文档
    13             //PDDocument document = PDDocument.load(bytes);
    14             PDDocument document = PDDocument.load(new File(inPdfPath));
    15             PDFDomTree pdfDomTree = new PDFDomTree();
    16             pdfDomTree.writeText(document,out);
    17         } catch (Exception e) {
    18             e.printStackTrace();
    19         }
    20     }
    21 
    22     public static void main(String[] args) throws IOException {
    23         PdfToHtml ph=new PdfToHtml();
    24         String pdfPath="C:\\works\\files\\武研中心行政考勤制度.pdf";
    25         String outputPath="C:\\works\\files\\武研中心行政考勤制度.html";
    26         ph.pdfToHtmlTest(pdfPath,outputPath);
    27   }
    28 
    29 }

    三:Java实现将TXT转换为html

     1  /*
     2      * txt文档转html
     3        filePath:txt原文件路径
     4        htmlPosition:转化后生成的html路径
     5     */
     6     public static void txtToHtml(String filePath, String htmlPosition) {
     7         try {
     8             //String encoding = "GBK";
     9             File file = new File(filePath);
    10             if (file.isFile() && file.exists()) { // 判断文件是否存在
    11                 InputStreamReader read = new InputStreamReader(new FileInputStream(file), "GBK");
    12                 // 考虑到编码格式
    13                 BufferedReader bufferedReader = new BufferedReader(read);
    14                 // 写文件
    15                 FileOutputStream fos = new FileOutputStream(new File(htmlPosition));
    16                 OutputStreamWriter osw = new OutputStreamWriter(fos, "GBK");
    17                 BufferedWriter bw = new BufferedWriter(osw);
    18                 String lineTxt = null;
    19                 while ((lineTxt = bufferedReader.readLine()) != null) {
    20                     bw.write("   "+lineTxt + "
    "); 21                 } 22                 bw.close(); 23                 osw.close(); 24                 fos.close(); 25                 read.close(); 26             } else { 27                 System.out.println("找不到指定的文件"); 28             } 29         } catch (Exception e) { 30             System.out.println("读取文件内容出错"); 31             e.printStackTrace(); 32         } 33     }
    本站声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系bd@zhengruan.com
    作者最新文章
    编程开发 Java html
    相关文章 更多
    精品专题 更多
    装机必备

    正软商城装机必备专区,精选办公、浏览器、安全防护、影音播放、压缩解压、设计创作和系统工具等电脑常用正版软件,帮助用户快速完成新电脑软件配置。

    Windows

    正软商城Windows软件专区,汇集适用于Windows电脑的办公、设计、安全防护、影音播放、开发工具和系统优化软件,提供软件介绍、系统要求、正版授权及购买下载服务。

    PDF教程

    正软商城PDF教程频道提供PDF编辑、转换、合并、拆分、压缩及格式处理方法,同时介绍常用PDF软件和工具的使用技巧。

    macOS软件

    正软商城macOS软件专区,精选适用于Mac电脑的办公、设计、影音、效率、开发和系统工具,提供软件功能介绍、macOS兼容版本、正版授权及购买下载服务。

    IOS软件

    正软商城iOS软件专区,精选适用于iPhone和iPad的办公、学习、影音、设计、效率及AI应用,提供功能介绍、适用设备、系统要求和正版获取方式等信息。

    AI

    正软商城AI软件专区,汇集AI写作、AI绘画、AI视频、AI办公、AI编程、AI翻译、智能客服和数据分析等人工智能工具,提供功能介绍、适用平台、收费方式及正版购买信息。

    Mac软件 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    Aperty macOS版
    Aperty macOS版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw macOS版
    AionClaw macOS版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy macOS版
    Loomy macOS版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。

    AirBuddy 3 macOS版
    AirBuddy 3 macOS版

    AirBuddy 3 是面向 macOS 的蓝牙外设增强工具,可集中查看 AirPods、Beats 与苹果设备电量,提供快速连接、播放控制、电量提醒、桌面小组件和多台 Mac 外设接力等功能。

    AirServer macOS版
    AirServer macOS版

    AirServer macOS版可把 Mac 转换为无线投屏接收端,通过 AirPlay 或 Google Cast 接收手机、平板和电脑画面,并支持多设备同时连接、高清镜像及会话录制,适合家庭娱乐、课堂教学、会议演示和应用展示。

    AnyDesk macOS版
    AnyDesk macOS版

    AnyDesk macOS版是一款适用于远程办公、设备维护和客户支持的远程桌面工具,可连接并操作异地计算机,支持文件传输、无人值守访问、会话权限控制及跨平台协作。

    WINDOWS 更多
    讯飞智作 网页版
    讯飞智作 网页版

    讯飞智作是一款基于语音合成技术、虚拟人驱动技术与数字人形象声音构建能力的 AI 数字人音视频创作平台。

    火山引擎 网页版
    火山引擎 网页版

    火山引擎是字节跳动旗下企业级云与AI服务平台。聚焦大模型核心能力,依托字节自研豆包多模态大模型,凭借火山方舟一站式平台,提供模型精调、推理部署、智能应用搭建等全链路服务,结合高性能AI算力,助力各行业快速落地大模型数字化与智能化应用。

    PixTV 网页版
    PixTV 网页版

    PixTV 是一款在浏览器中使用的 AI 视觉内容创作平台,提供图片、视频、音频、文字生成、AI 分镜、局部重绘、提示词反推和无限画布等工具,适合短剧、漫剧、广告及社交媒体内容制作。

    讯飞绘文 网页版
    讯飞绘文 网页版

    讯飞绘文网页版是科大讯飞推出的AI图文创作与内容运营工具,覆盖热点选题、文章生成、稿件校对、智能配图、排版发布和数据复盘等环节,适合自媒体创作者及内容团队在线使用。

    Maya(Autodesk Maya) Windows版
    Maya(Autodesk Maya) Windows版

    Autodesk Maya 是面向影视、电视、动画和游戏行业的专业三维制作软件,集多边形与 NURBS 建模、角色绑定、关键帧和动作捕捉动画、Bifrost 特效模拟、材质开发及 Arnold 渲染于一体,

    Aperty Windows版
    Aperty Windows版

    Aperty 是 Skylum 推出的 AI 人像修图软件,支持自然肤质修饰、瑕疵处理、面部与身体调整、预设及批量同步。

    立刻MV 网页版
    立刻MV 网页版

    立刻MV 面向音乐人、内容创作者和品牌团队,帮助用户低成本完成歌曲 MV、歌词视频、AI 分镜、图生视频与最终合成。

    蛙蛙写作 网页版
    蛙蛙写作 网页版

    蛙蛙写作 AI 创作工具,覆盖小说、剧本、文案,一键生成文稿,打通文字转视频全流程,高效解决创作难题。

    超级简历WonderCV 网页版
    超级简历WonderCV 网页版

    超级简历WonderCV是面向应届生和AI小白的智能求职平台,覆盖简历、面试与职业规划。

    音述AI 网页版
    音述AI 网页版

    音述AI,是一个以“用声音述说故事”为核心的 AI 音乐创作与声音分享社区。

    AionClaw Windows版
    AionClaw Windows版

    AionClaw 是可在桌面端运行的任务型 AI 助手,通过数字专家与技能市场组合办公、创作、数据和开发能力。

    Loomy Windows版
    Loomy Windows版

    Loomy 是科大讯飞推出的桌面 AI 助手,可通过对话、任务与工作目录协助处理办公、内容创作和资料整理。