Word文档转html并提取标题

最近做了一个功能,需要将word文档转化成html的格式,并提取出标题生成导航。考虑到功能的复杂程度,将需要降低为对“标题1”这种格式进行提取。

docx为后缀的文档(word2007)支持XML的文件格式,本质上是一个zip压缩包,解压出来就可以看到所有信息,可能正因为如果,使用XHTMLConverter便可以得到对应的html文档,且标题元素的class属性被标注为"X"+n(n为标题层级)。

但doc文档但相对麻烦,doc文档一般使用poi读取,用的比较多的html转换方式是使用poi中的WordToHtmlConverter进行转换,这个转换器并不会对标题进行特殊处理,将其当做普通有样式的一个段落(Paragraph)进行处理,因此会和其他普通段落混合在一起。对此有两种处理方法:

方案一:重写processParagraph方法,在注释的判断处加上对标题的判断,对标题进行特殊处理,但由于WordToHtmlConverter的成员变量均声明为private,因此我采用了另一种方案。

 

protected void processParagraph(HWPFDocumentCore hwpfDocument, Element parentElement, int currentTableLevel, Paragraph paragraph, String bulletText) {
    Element pElement = this.htmlDocumentFacade.createParagraph();
    parentElement.appendChild(pElement);
    StringBuilder style = new StringBuilder();
    WordToHtmlUtils.addParagraphProperties(paragraph, style);
    int charRuns = paragraph.numCharacterRuns();
    if(charRuns != 0) {
        CharacterRun characterRun = paragraph.getCharacterRun(0);
        String pFontName;
        int pFontSize;
        if(characterRun != null) {
            Triplet triplet = this.getCharacterRunTriplet(characterRun);
            pFontSize = characterRun.getFontSize() / 2;
            pFontName = triplet.fontName;
            WordToHtmlUtils.addFontFamily(pFontName, style);
            WordToHtmlUtils.addFontSize(pFontSize, style);
        } else {
            pFontSize = -1;
            pFontName = "";
        }

        this.blocksProperies.push(new WordToHtmlConverter.BlockProperies(pFontName, pFontSize));

        try {
            if(WordToHtmlUtils.isNotEmpty(bulletText)) {
                if(bulletText.endsWith("\t")) {
                    float defaultTab = 720.0F;
                    float firstLinePosition = (float)(paragraph.getIndentFromLeft() + paragraph.getFirstLineIndent() + 20);
                    float nextStop = (float)(Math.ceil((double)(firstLinePosition / 720.0F)) * 720.0D);
                    float spanMinWidth = nextStop - firstLinePosition;
                    Element span = this.htmlDocumentFacade.getDocument().createElement("span");
                    this.htmlDocumentFacade.addStyleClass(span, "s", "display: inline-block; text-indent: 0; min-width: " + spanMinWidth / 1440.0F + "in;");
                    pElement.appendChild(span);
                    Text textNode = this.htmlDocumentFacade.createText(bulletText.substring(0, bulletText.length() - 1) + '\u200b' + ' ');
                    span.appendChild(textNode);
                } else {
                    Text textNode = this.htmlDocumentFacade.createText(bulletText.substring(0, bulletText.length() - 1));
                    pElement.appendChild(textNode);
                }
            }

            this.processCharacters(hwpfDocument, currentTableLevel, paragraph, pElement);
        } finally {
            this.blocksProperies.pop();
        }

     // 此处需要修改 if(style.length() > 0) { this.htmlDocumentFacade.addStyleClass(pElement, "p", style.toString()); } WordToHtmlUtils.compactSpans(pElement); } }

  方案二:在word文档中进行埋点,然后在处理过后的html文档中根据itTitleMap进行再处理

private Map<String,String> setTitleElements(HWPFDocument wordObject ){
    // 获取样式表
    StyleSheet styleSheet = wordObject.getStyleSheet();
    int styleTotal = wordObject.getStyleSheet().numStyles();
    // 使用map映射存储标题信息
    Map<String,String> idTitleMap = Maps.newHashMap();
    Range range = wordObject.getRange();
    for (int i = 0; i < range.numParagraphs(); i++) {
        // 获取样式信息
        Paragraph paragraph = range.getParagraph(i);
        int styleIndex = paragraph.getStyleIndex();
        if (styleTotal > styleIndex) {
            StyleDescription styleDescription = styleSheet.getStyleDescription(styleIndex);
            String descriptionName = styleDescription.getName();
            if ( descriptionName != null  &&  descriptionName.contains(FIRST_LEVEL_TITLE_DESCRIPTION)) {
                String uuid = UUIDHelper.getUuid();
                String text = paragraph.text().replaceAll( "[\r\n]", "" );
                paragraph.replaceText( uuid, false );
                idTitleMap.put( uuid, text );
            }
        }
    }

    return idTitleMap;
}

  

转载于:https://www.cnblogs.com/channingwong/p/9698924.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
### 回答1: 使用 Python 将 HTML 换为 Word 文档并将标题作为文件名,可以使用 python-docx 库。首先,安装 python-docx 库: ``` pip install python-docx ``` 然后,使用下面的代码把 HTML 换为 Word 文档: ```python import requests from bs4 import BeautifulSoup import docx def html_to_word(html_str, title): # 解析 HTML 字符串 soup = BeautifulSoup(html_str, 'html.parser') # 创建一个 Word 文档 doc = docx.Document() # 遍历 HTML 文档中的所有元素 for element in soup.body.descendants: # 如果是标题 if element.name in ['h1', 'h2', 'h3', 'h4', 'h5', 'h6']: # 添加标题 doc.add_heading(element.text, level=int(element.name[1])) # 如果是段落 elif element.name == 'p': # 添加段落 doc.add_paragraph(element.text) # 保存 Word 文档 doc.save(title + '.docx') ``` 以上代码会创建一个 Word 文档,并把 HTML 中的标题和段落添加到文档中,最后使用标题作为文件名保存 Word 文档。 ### 回答2: 使用Python将HTML换为Word可以使用python-docx库。首先,我们需要安装该库,在命令行中输入以下命令: ``` pip install python-docx ``` 安装完成后,我们可以编写Python代码来实现将HTML换为Word的功能: ```python from docx import Document from bs4 import BeautifulSoup def html_to_word(html_file): # 读取HTML文件 with open(html_file, 'r', encoding='utf-8') as f: html_content = f.read() # 使用BeautifulSoup解析HTML soup = BeautifulSoup(html_content, 'html.parser') # 提取标题作为文件名 title = soup.title.string # 创建Word文档 doc = Document() # 将HTML内容换为Word doc.add_paragraph(str(soup)) # 保存为Word文件 doc.save(title + '.docx') # 使用示例 html_to_word('sample.html') ``` 在上述代码中,我们首先使用BeautifulSoup库解析HTML文件,然后提取标题作为文件名。接下来,我们创建一个空的Word文档,并将HTML内容换后添加到文档中。最后,使用标题加上扩展名 `.docx` 作为文件名保存Word文档。 当然,这只是一个简单的示例,如果HTML文件中包含更复杂的内容,可能需要进一步处理,考虑样式、图像或其他元素的换。具体换方式可以根据HTML文件的结构和需求进行定制。 ### 回答3: 使用Python进行HTMLWord换可以使用python-docx库来实现。下面是一个简单的示例代码,将HTML文件换成Word,使用标题作为文件名: ```python from bs4 import BeautifulSoup from docx import Document def html_to_word(html_filename): # 打开HTML文件并读取内容 with open(html_filename, 'r', encoding='utf-8') as file: html_content = file.read() # 使用BeautifulSoup解析HTML内容 soup = BeautifulSoup(html_content, 'html.parser') # 获取标题作为文件名 title = soup.title.text.strip() # 创建一个新的Word文档对象 doc = Document() # 获取HTML内容中的所有段落 paragraphs = soup.find_all('p') # 将每个段落添加到Word文档中 for p in paragraphs: doc.add_paragraph(p.text) # 保存Word文档,文件名使用标题 doc.save(title + '.docx') # 调用函数,传入HTML文件名 html_to_word('example.html') ``` 以上代码使用了`bs4`库来解析HTML内容,将所有的`<p>`标签中的文本添加到Word文档中。最终,保存的Word文档的文件名将会是HTML文件中的标题。 请注意,要运行此代码,你需要安装所需的库。可以通过运行`pip install beautifulsoup4 python-docx`来安装`bs4`和`python-docx`库。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值