# 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", "
Test Content
")
#
# # 预处理 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'{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", "Test Content
")
#
# # 创建一个临时目录来存储生成的文件
# 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", "Test Content
")
#
# # 创建一个临时目录来存储生成的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", "Test Content
")
#
# # 创建一个内存中的字节流来存储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
#
#
#
#
#
#
#
#
#
#
#