123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309 |
- # import io
- # import re
- # import subprocess
- # import sys
- #
- # import mammoth
- # import pdfkit
- # from bs4 import BeautifulSoup
- # from django.http import JsonResponse
- # from pdf2docx import Converter
- # from DCbackend.utils import common
- # from DCbackend.utils.common import success, fail
- # import os
- # from datetime import datetime
- # class ExportService:
- #
- # @staticmethod
- # def Export(request):
- # html_content = request.POST.get("content", "<h1>Test Content</h1>")
- #
- # # 预处理 HTML 内容,将特定格式转换为标题
- # def process_content(content):
- # # 使用正则表达式匹配 A{{Directory1}}, A.1{{Directory2}} 等格式
- # pattern = r'([A-Z](?:\.\d+)*){{Directory(\d+)}}'
- #
- # def replace_with_header(match):
- # prefix = match.group(1)
- # level = int(match.group(2))
- # # 确保标题级别在1到6之间
- # level = max(1, min(level, 6))
- # return f'<h{level}>{prefix}'
- #
- # # 替换匹配的内容为HTML标题
- # processed_content = re.sub(pattern, replace_with_header, content)
- # return processed_content
- #
- # processed_html_content = process_content(html_content)
- #
- # output_dir = 'uploads'
- # input_file = 'input.html'
- #
- # # 使用当前时间生成唯一的文件名
- # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
- # output_file = f'exported_document_{current_time}.docx'
- #
- # input_path = os.path.join(output_dir, input_file)
- # output_path = os.path.join(output_dir, output_file)
- #
- # print(f"准备创建输入文件: {input_path}")
- #
- # try:
- # # 确保输出目录存在
- # os.makedirs(output_dir, exist_ok=True)
- #
- # # 写入处理后的 HTML 内容到输入文件
- # with open(input_path, 'w', encoding='utf-8') as f:
- # f.write(processed_html_content)
- #
- # print(f"输入文件成功创建: {input_path}")
- #
- # if sys.platform.startswith('win'):
- # pandoc_path = r'D:\Download\pandoc-3.1.12.2\pandoc.exe'
- # else:
- # pandoc_path = '/usr/local/bin/pandoc'
- # command = [
- # pandoc_path,
- # "-f", "html",
- # "-t", "docx",
- # "--toc", # 生成目录
- # "--toc-depth=6", # 目录深度,设置为6以包含所有可能的级别
- # "--number-sections", # 为标题添加编号
- # "-o", output_path,
- # input_path
- # ]
- #
- # print("开始执行 Pandoc 转换")
- # result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
- #
- # if result.returncode == 0:
- # print(f"Pandoc 转换成功,输出文件: {output_path}")
- # if os.path.exists(output_path):
- # oss_url = common.oss_upload_file(output_path)
- # file_size = os.path.getsize(output_path)
- # return success({
- # "file_name": output_file,
- # "file_path": oss_url,
- # "file_size": file_size
- # })
- # else:
- # return JsonResponse({"error": "DOCX 文件创建失败,无法找到文件"}, status=500)
- # else:
- # print(f"Pandoc 转换失败。错误信息: {result.stderr.decode()}")
- # return JsonResponse({"error": f"Pandoc 转换失败: {result.stderr.decode()}"}, status=500)
- #
- # except Exception as e:
- # print(f"处理过程中发生错误: {str(e)}")
- # return JsonResponse({"error": f"处理过程中发生错误: {str(e)}"}, status=500)
- # finally:
- # # 清理输入文件
- # if os.path.exists(input_path):
- # os.remove(input_path)
- # print(f"已删除输入文件: {input_path}")
- #
- # @staticmethod
- # def htmlPDFWord(request):
- # html_content = request.POST.get("content", "<h1>Test Content</h1>")
- #
- # # 创建一个临时目录来存储生成的文件
- # output_dir = 'temp_files'
- # os.makedirs(output_dir, exist_ok=True)
- #
- # # 生成唯一的文件名
- # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
- # pdf_file = f'exported_document_{current_time}.pdf'
- # docx_file = f'exported_document_{current_time}.docx'
- # pdf_path = os.path.join(output_dir, pdf_file)
- # docx_path = os.path.join(output_dir, docx_file)
- #
- # try:
- # # 配置pdfkit选项
- # options = {
- # 'page-size': 'A4',
- # 'margin-top': '0.75in',
- # 'margin-right': '0.75in',
- # 'margin-bottom': '0.75in',
- # 'margin-left': '0.75in',
- # 'encoding': "UTF-8",
- # }
- #
- # # 指定wkhtmltopdf的路径
- # if sys.platform.startswith('win'):
- # config = pdfkit.configuration(wkhtmltopdf=r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
- # else:
- # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
- #
- # # 将HTML转换为PDF
- # pdfkit.from_string(html_content, pdf_path, options=options, configuration=config)
- #
- # # 将PDF转换为DOCX
- # cv = Converter(pdf_path)
- # cv.convert(docx_path)
- # cv.close()
- #
- # # 上传到阿里云OSS
- # oss_url = common.oss_upload_file(docx_path)
- #
- # # 获取文件大小
- # file_size = os.path.getsize(docx_path)
- #
- # # 返回成功响应,包含文件信息
- # return success({
- # "file_name": docx_file,
- # "file_path": oss_url,
- # "file_size": file_size
- # })
- #
- # except Exception as e:
- # return fail(f"文档生成或上传失败: {str(e)}")
- #
- # finally:
- # # 清理临时文件
- # if os.path.exists(pdf_path):
- # os.remove(pdf_path)
- # if os.path.exists(docx_path):
- # os.remove(docx_path)
- # # 尝试删除临时目录
- # try:
- # os.rmdir(output_dir)
- # except OSError:
- # # 如果目录不为空,就忽略错误
- # pass
- #
- # @staticmethod
- # def htmlPDF(request):
- # html_content = request.POST.get("content", "<h1>Test Content</h1>")
- #
- # # 创建一个临时目录来存储生成的PDF
- # output_dir = 'temp_pdf'
- # os.makedirs(output_dir, exist_ok=True)
- #
- # # 生成唯一的文件名
- # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
- # output_file = f'exported_document_{current_time}.pdf'
- # output_path = os.path.join(output_dir, output_file)
- #
- # try:
- # # 配置pdfkit选项
- # # 调整选项以放大内容
- # options = {
- # 'page-size': 'A4',
- # 'margin-top': '0.75in',
- # 'margin-right': '0.75in',
- # 'margin-bottom': '0.75in',
- # 'margin-left': '0.75in',
- # 'encoding': "UTF-8",
- # 'dpi': 300, # 增加 DPI 以提高清晰度
- # }
- #
- # # 指定wkhtmltopdf的路径
- # if sys.platform.startswith('win'):
- # config = pdfkit.configuration(wkhtmltopdf=r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
- # else:
- # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
- #
- # # 将HTML转换为PDF
- # pdfkit.from_string(html_content, output_path, options=options, configuration=config)
- #
- # # 上传到阿里云OSS
- # oss_url = common.oss_upload_file(output_path)
- #
- # # 获取文件大小
- # file_size = os.path.getsize(output_path)
- #
- # # 删除临时文件
- # os.remove(output_path)
- #
- # # 返回成功响应,包含文件信息
- # return success({
- # "file_name": output_file,
- # "file_path": oss_url,
- # "file_size": file_size
- # })
- #
- # except Exception as e:
- # # 如果出现错误,确保删除任何可能创建的临时文件
- # if os.path.exists(output_path):
- # os.remove(output_path)
- # return fail(f"PDF生成或上传失败: {str(e)}")
- #
- # finally:
- # # 尝试删除临时目录
- # try:
- # os.rmdir(output_dir)
- # except OSError:
- # # 如果目录不为空,就忽略错误
- # pass
- #
- # @staticmethod
- # def htmlWord(request):
- # html_content = request.POST.get("content", "<h1>Test Content</h1>")
- #
- # # 创建一个内存中的字节流来存储Word文档
- # output = io.BytesIO()
- #
- # # 使用mammoth将HTML转换为Word文档
- # style_map = """
- # p => p:fresh
- # h1 => h1:fresh
- # h2 => h2:fresh
- # h3 => h3:fresh
- # h4 => h4:fresh
- # h5 => h5:fresh
- # h6 => h6:fresh
- # strong => b
- # em => i
- # ul => ul
- # ol => ol
- # li => li
- # """
- # mammoth.convert_html_to_docx(html_content, output, style_map=style_map)
- #
- # # 生成唯一的文件名
- # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
- # output_file = f'exported_document_{current_time}.docx'
- # output_dir = 'temp_word'
- # os.makedirs(output_dir, exist_ok=True)
- # output_path = os.path.join(output_dir, output_file)
- #
- # try:
- # # 将内存中的文档保存到文件
- # with open(output_path, "wb") as f:
- # f.write(output.getvalue())
- #
- # # 上传到阿里云OSS
- # oss_url = common.oss_upload_file(output_path)
- #
- # # 获取文件大小
- # file_size = os.path.getsize(output_path)
- #
- # return success({
- # "file_name": output_file,
- # "file_path": oss_url,
- # "file_size": file_size
- # })
- #
- # except Exception as e:
- # return fail(f"Word文档生成或上传失败: {str(e)}")
- #
- # finally:
- # # 清理临时文件
- # if os.path.exists(output_path):
- # os.remove(output_path)
- # # 尝试删除临时目录
- # try:
- # os.rmdir(output_dir)
- # except OSError:
- # # 如果目录不为空,就忽略错误
- # pass
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
|