table_process.py 11.1 KB
Newer Older
U
user1018 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14
# Copyright (c) 2022 PaddlePaddle Authors. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
U
user1018 已提交
15
This code is refer from: https://github.com/weizwx/html2docx/blob/master/htmldocx/h2d.py
U
user1018 已提交
16 17
"""

U
user1018 已提交
18 19
import re
import docx
U
user1018 已提交
20 21
from docx import Document
from bs4 import BeautifulSoup
U
user1018 已提交
22
from html.parser import HTMLParser
U
user1018 已提交
23 24


U
user1018 已提交
25 26 27 28 29 30 31
def get_table_rows(table_soup):
    table_row_selectors = [
        'table > tr', 'table > thead > tr', 'table > tbody > tr',
        'table > tfoot > tr'
    ]
    # If there's a header, body, footer or direct child tr tags, add row dimensions from there
    return table_soup.select(', '.join(table_row_selectors), recursive=False)
U
user1018 已提交
32 33


U
user1018 已提交
34 35 36
def get_table_columns(row):
    # Get all columns for the specified row tag.
    return row.find_all(['th', 'td'], recursive=False) if row else []
U
user1018 已提交
37 38


U
user1018 已提交
39 40 41 42 43
def get_table_dimensions(table_soup):
    # Get rows for the table
    rows = get_table_rows(table_soup)
    # Table is either empty or has non-direct children between table and tr tags
    # Thus the row dimensions and column dimensions are assumed to be 0
U
user1018 已提交
44

U
user1018 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66
    cols = get_table_columns(rows[0]) if rows else []
    # Add colspan calculation column number
    col_count = 0
    for col in cols:
        colspan = col.attrs.get('colspan', 1)
        col_count += int(colspan)

    return rows, col_count


def get_cell_html(soup):
    # Returns string of td element with opening and closing <td> tags removed
    # Cannot use find_all as it only finds element tags and does not find text which
    # is not inside an element
    return ' '.join([str(i) for i in soup.contents])


def delete_paragraph(paragraph):
    # https://github.com/python-openxml/python-docx/issues/33#issuecomment-77661907
    p = paragraph._element
    p.getparent().remove(p)
    p._p = p._element = None
U
user1018 已提交
67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149


def remove_whitespace(string, leading=False, trailing=False):
    """Remove white space from a string.
    Args:
        string(str): The string to remove white space from.
        leading(bool, optional): Remove leading new lines when True.
        trailing(bool, optional): Remove trailing new lines when False.
    Returns:
        str: The input string with new line characters removed and white space squashed.
    Examples:
        Single or multiple new line characters are replaced with space.
            >>> remove_whitespace("abc\\ndef")
            'abc def'
            >>> remove_whitespace("abc\\n\\n\\ndef")
            'abc def'
        New line characters surrounded by white space are replaced with a single space.
            >>> remove_whitespace("abc \\n \\n \\n def")
            'abc def'
            >>> remove_whitespace("abc  \\n  \\n  \\n  def")
            'abc def'
        Leading and trailing new lines are replaced with a single space.
            >>> remove_whitespace("\\nabc")
            ' abc'
            >>> remove_whitespace("  \\n  abc")
            ' abc'
            >>> remove_whitespace("abc\\n")
            'abc '
            >>> remove_whitespace("abc  \\n  ")
            'abc '
        Use ``leading=True`` to remove leading new line characters, including any surrounding
        white space:
            >>> remove_whitespace("\\nabc", leading=True)
            'abc'
            >>> remove_whitespace("  \\n  abc", leading=True)
            'abc'
        Use ``trailing=True`` to remove trailing new line characters, including any surrounding
        white space:
            >>> remove_whitespace("abc  \\n  ", trailing=True)
            'abc'
    """
    # Remove any leading new line characters along with any surrounding white space
    if leading:
        string = re.sub(r'^\s*\n+\s*', '', string)

    # Remove any trailing new line characters along with any surrounding white space
    if trailing:
        string = re.sub(r'\s*\n+\s*$', '', string)

    # Replace new line characters and absorb any surrounding space.
    string = re.sub(r'\s*\n\s*', ' ', string)
    # TODO need some way to get rid of extra spaces in e.g. text <span>   </span>  text
    return re.sub(r'\s+', ' ', string)


font_styles = {
    'b': 'bold',
    'strong': 'bold',
    'em': 'italic',
    'i': 'italic',
    'u': 'underline',
    's': 'strike',
    'sup': 'superscript',
    'sub': 'subscript',
    'th': 'bold',
}

font_names = {
    'code': 'Courier',
    'pre': 'Courier',
}


class HtmlToDocx(HTMLParser):
    def __init__(self):
        super().__init__()
        self.options = {
            'fix-html': True,
            'images': True,
            'tables': True,
            'styles': True,
        }
        self.table_row_selectors = [
U
user1018 已提交
150
            'table > tr', 'table > thead > tr', 'table > tbody > tr',
U
user1018 已提交
151 152
            'table > tfoot > tr'
        ]
U
user1018 已提交
153 154
        self.table_style = None
        self.paragraph_style = None
U
user1018 已提交
155 156 157 158 159 160 161 162 163 164

    def set_initial_attrs(self, document=None):
        self.tags = {
            'span': [],
            'list': [],
        }
        if document:
            self.doc = document
        else:
            self.doc = Document()
U
user1018 已提交
165 166
        self.bs = self.options[
            'fix-html']  # whether or not to clean with BeautifulSoup
U
user1018 已提交
167
        self.document = self.doc
U
user1018 已提交
168
        self.include_tables = True  #TODO add this option back in?
U
user1018 已提交
169 170 171 172 173 174 175 176 177 178 179 180
        self.include_images = self.options['images']
        self.include_styles = self.options['styles']
        self.paragraph = None
        self.skip = False
        self.skip_tag = None
        self.instances_to_skip = 0

    def copy_settings_from(self, other):
        """Copy settings from another instance of HtmlToDocx"""
        self.table_style = other.table_style
        self.paragraph_style = other.paragraph_style

U
user1018 已提交
181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226
    def ignore_nested_tables(self, tables_soup):
        """
        Returns array containing only the highest level tables
        Operates on the assumption that bs4 returns child elements immediately after
        the parent element in `find_all`. If this changes in the future, this method will need to be updated
        :return:
        """
        new_tables = []
        nest = 0
        for table in tables_soup:
            if nest:
                nest -= 1
                continue
            new_tables.append(table)
            nest = len(table.find_all('table'))
        return new_tables

    def get_tables(self):
        if not hasattr(self, 'soup'):
            self.include_tables = False
            return
            # find other way to do it, or require this dependency?
        self.tables = self.ignore_nested_tables(self.soup.find_all('table'))
        self.table_no = 0

    def run_process(self, html):
        if self.bs and BeautifulSoup:
            self.soup = BeautifulSoup(html, 'html.parser')
            html = str(self.soup)
        if self.include_tables:
            self.get_tables()
        self.feed(html)

    def add_html_to_cell(self, html, cell):
        if not isinstance(cell, docx.table._Cell):
            raise ValueError('Second argument needs to be a %s' %
                             docx.table._Cell)
        unwanted_paragraph = cell.paragraphs[0]
        if unwanted_paragraph.text == "":
            delete_paragraph(unwanted_paragraph)
        self.set_initial_attrs(cell)
        self.run_process(html)
        # cells must end with a paragraph or will get message about corrupt file
        # https://stackoverflow.com/a/29287121
        if not self.doc.paragraphs:
            self.doc.add_paragraph('')
U
user1018 已提交
227 228 229 230 231 232 233 234

    def apply_paragraph_style(self, style=None):
        try:
            if style:
                self.paragraph.style = style
            elif self.paragraph_style:
                self.paragraph.style = self.paragraph_style
        except KeyError as e:
U
user1018 已提交
235 236
            raise ValueError(
                f"Unable to apply style {self.paragraph_style}.") from e
U
user1018 已提交
237

U
user1018 已提交
238
    def handle_table(self, html, doc):
U
user1018 已提交
239 240 241 242 243 244 245 246
        """
        To handle nested tables, we will parse tables manually as follows:
        Get table soup
        Create docx table
        Iterate over soup and fill docx table with new instances of this parser
        Tell HTMLParser to ignore any tags until the corresponding closing table tag
        """
        table_soup = BeautifulSoup(html, 'html.parser')
U
user1018 已提交
247
        rows, cols_len = get_table_dimensions(table_soup)
U
user1018 已提交
248 249
        table = doc.add_table(len(rows), cols_len)
        table.style = doc.styles['Table Grid']
U
user1018 已提交
250

U
user1018 已提交
251 252
        cell_row = 0
        for index, row in enumerate(rows):
U
user1018 已提交
253
            cols = get_table_columns(row)
U
user1018 已提交
254 255 256 257 258
            cell_col = 0
            for col in cols:
                colspan = int(col.attrs.get('colspan', 1))
                rowspan = int(col.attrs.get('rowspan', 1))

U
user1018 已提交
259
                cell_html = get_cell_html(col)
U
user1018 已提交
260 261
                if col.name == 'th':
                    cell_html = "<b>%s</b>" % cell_html
U
user1018 已提交
262

U
user1018 已提交
263
                docx_cell = table.cell(cell_row, cell_col)
U
user1018 已提交
264

U
user1018 已提交
265 266 267 268
                while docx_cell.text != '':  # Skip the merged cell
                    cell_col += 1
                    docx_cell = table.cell(cell_row, cell_col)

U
user1018 已提交
269 270
                cell_to_merge = table.cell(cell_row + rowspan - 1,
                                           cell_col + colspan - 1)
U
user1018 已提交
271 272 273 274 275
                if docx_cell != cell_to_merge:
                    docx_cell.merge(cell_to_merge)

                child_parser = HtmlToDocx()
                child_parser.copy_settings_from(self)
U
user1018 已提交
276
                child_parser.add_html_to_cell(cell_html or ' ', docx_cell)
U
user1018 已提交
277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317

                cell_col += colspan
            cell_row += 1

    def handle_data(self, data):
        if self.skip:
            return

        # Only remove white space if we're not in a pre block.
        if 'pre' not in self.tags:
            # remove leading and trailing whitespace in all instances
            data = remove_whitespace(data, True, True)

        if not self.paragraph:
            self.paragraph = self.doc.add_paragraph()
            self.apply_paragraph_style()

        # There can only be one nested link in a valid html document
        # You cannot have interactive content in an A tag, this includes links
        # https://html.spec.whatwg.org/#interactive-content
        link = self.tags.get('a')
        if link:
            self.handle_link(link['href'], data)
        else:
            # If there's a link, dont put the data directly in the run
            self.run = self.paragraph.add_run(data)
            spans = self.tags['span']
            for span in spans:
                if 'style' in span:
                    style = self.parse_dict_string(span['style'])
                    self.add_styles_to_run(style)

            # add font style and name
            for tag in self.tags:
                if tag in font_styles:
                    font_style = font_styles[tag]
                    setattr(self.run.font, font_style, True)

                if tag in font_names:
                    font_name = font_names[tag]
                    self.run.font.name = font_name