Python将HTML手动转换为doc

最近项目中遇到一个很棘手的问题,需要将前端生成doc转换为后端Python生成,起初使用了python-docx生成,但是生成的doc文件缺少了样式,最后在理解了前端转换doc的jquery.wordexport.js文件后,将jquery.wordexport.js移植到Python中。

简述一下jquery.wordexport.js这个文件的逻辑:在HTML文件内容开头和结尾处增加doc描述,将图片转化为本地图片,添加img描述脚本,最后输出为doc文件。Python将HTML生成doc也类似,只不过我还将所有图片转换为base64位,逻辑代码如下:

def make_word(file_name, htmlstr):
    # docx
    now = int(time.time())
    filehtmlname = 'HTMLfiles/template{}.html'.format(now)
    # 将HTML内容中的echart图和图片统一转化为base64位图片方便传输。
    imgsrc_base64_makechart('template{}'.format(now), file_name, htmlstr)
    # 把HTML文件转化为doc
    docurl = html2doc(file_name, filehtmlname)
    os.remove(filehtmlname)
    return docurl

def html2doc(file_name, html_url):
    rename = 'docxFiles/{}.doc'.format(file_name)
    shutil.copyfile(html_url, rename)
    with open(rename, 'r') as f:
        doc_content = f.read()
        soup = BeautifulSoup(doc_content, "html.parser")
        imgs = soup.find_all("img")
        header = 'Mime-Version: 1.0\nContent-Base: http://www.baidu.com\nContent-Type: Multipart/related; boundary="NEXT.ITEM-BOUNDARY";type="text/html"\n\n--NEXT.ITEM-BOUNDARY\nContent-Type: text/html; charset="utf-8"\nContent-Location: http://www.baidu.com\n'
        mhtmlBottom = '\n'
        for img in imgs:
            data = img['src'].split('base64,')[1]
            location = img['src']
            type = img['src'].split(':')[1].split(';')[0]
            encoding = img['src'].split(';')[1].split(',')[0]
            mhtmlBottom += '--NEXT.ITEM-BOUNDARY\n'
            mhtmlBottom += 'Content-Location: ' + location + '\n'
            mhtmlBottom += 'Content-Type: ' + type + '\n'
            mhtmlBottom += 'Content-Transfer-Encoding: ' + encoding + '\n\n'
            mhtmlBottom += data + '\n\n'
        mhtmlBottom += '--NEXT.ITEM-BOUNDARY--'
        fx = header + str(soup) + mhtmlBottom
    with open(rename,"w") as f:
        f.write(fx)
    return rename
    
# 替换html中统计图模板变量以及转img为base64位
def imgsrc_base64_makechart(tem_name, title_str, htmlstr):
    soup = BeautifulSoup(htmlstr, "html.parser")
    imgs = soup.find_all("img")
    if len(imgs) != 0:
        for img in imgs:
            src = img["src"]
            if src.find('data:image') == -1:
                img_url = src.split('/')[-1]
                with open('static/img/' + img_url,"rb") as f:#转为二进制格式
                    base64_data = base64.b64encode(f.read())#使用base64进行加密
                    img["src"] = 'data:image/png;base64,' + base64_data
                    img['crossOrigin'] = "Anonymous"
                if img_url.find('template') != -1:
                    try:
                        os.remove('static/img/' + img_url)
                        os.remove('HTMLfiles/{}.html'.format(img_url.split('.')[0]))
                    except:
                        pass
    fx = soup
    with open('HTMLfiles/{}.html'.format(tem_name),"w") as f:
        f.write(str(fx))

你可能感兴趣的:(Python将HTML手动转换为doc)