ExportService.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  1. # import io
  2. # import re
  3. # import subprocess
  4. # import sys
  5. #
  6. # import mammoth
  7. # import pdfkit
  8. # from bs4 import BeautifulSoup
  9. # from django.http import JsonResponse
  10. # from pdf2docx import Converter
  11. # from DCbackend.utils import common
  12. # from DCbackend.utils.common import success, fail
  13. # import os
  14. # from datetime import datetime
  15. # class ExportService:
  16. #
  17. # @staticmethod
  18. # def Export(request):
  19. # html_content = request.POST.get("content", "<h1>Test Content</h1>")
  20. #
  21. # # 预处理 HTML 内容,将特定格式转换为标题
  22. # def process_content(content):
  23. # # 使用正则表达式匹配 A{{Directory1}}, A.1{{Directory2}} 等格式
  24. # pattern = r'([A-Z](?:\.\d+)*){{Directory(\d+)}}'
  25. #
  26. # def replace_with_header(match):
  27. # prefix = match.group(1)
  28. # level = int(match.group(2))
  29. # # 确保标题级别在1到6之间
  30. # level = max(1, min(level, 6))
  31. # return f'<h{level}>{prefix}'
  32. #
  33. # # 替换匹配的内容为HTML标题
  34. # processed_content = re.sub(pattern, replace_with_header, content)
  35. # return processed_content
  36. #
  37. # processed_html_content = process_content(html_content)
  38. #
  39. # output_dir = 'uploads'
  40. # input_file = 'input.html'
  41. #
  42. # # 使用当前时间生成唯一的文件名
  43. # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
  44. # output_file = f'exported_document_{current_time}.docx'
  45. #
  46. # input_path = os.path.join(output_dir, input_file)
  47. # output_path = os.path.join(output_dir, output_file)
  48. #
  49. # print(f"准备创建输入文件: {input_path}")
  50. #
  51. # try:
  52. # # 确保输出目录存在
  53. # os.makedirs(output_dir, exist_ok=True)
  54. #
  55. # # 写入处理后的 HTML 内容到输入文件
  56. # with open(input_path, 'w', encoding='utf-8') as f:
  57. # f.write(processed_html_content)
  58. #
  59. # print(f"输入文件成功创建: {input_path}")
  60. #
  61. # if sys.platform.startswith('win'):
  62. # pandoc_path = r'D:\Download\pandoc-3.1.12.2\pandoc.exe'
  63. # else:
  64. # pandoc_path = '/usr/local/bin/pandoc'
  65. # command = [
  66. # pandoc_path,
  67. # "-f", "html",
  68. # "-t", "docx",
  69. # "--toc", # 生成目录
  70. # "--toc-depth=6", # 目录深度,设置为6以包含所有可能的级别
  71. # "--number-sections", # 为标题添加编号
  72. # "-o", output_path,
  73. # input_path
  74. # ]
  75. #
  76. # print("开始执行 Pandoc 转换")
  77. # result = subprocess.run(command, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
  78. #
  79. # if result.returncode == 0:
  80. # print(f"Pandoc 转换成功,输出文件: {output_path}")
  81. # if os.path.exists(output_path):
  82. # oss_url = common.oss_upload_file(output_path)
  83. # file_size = os.path.getsize(output_path)
  84. # return success({
  85. # "file_name": output_file,
  86. # "file_path": oss_url,
  87. # "file_size": file_size
  88. # })
  89. # else:
  90. # return JsonResponse({"error": "DOCX 文件创建失败,无法找到文件"}, status=500)
  91. # else:
  92. # print(f"Pandoc 转换失败。错误信息: {result.stderr.decode()}")
  93. # return JsonResponse({"error": f"Pandoc 转换失败: {result.stderr.decode()}"}, status=500)
  94. #
  95. # except Exception as e:
  96. # print(f"处理过程中发生错误: {str(e)}")
  97. # return JsonResponse({"error": f"处理过程中发生错误: {str(e)}"}, status=500)
  98. # finally:
  99. # # 清理输入文件
  100. # if os.path.exists(input_path):
  101. # os.remove(input_path)
  102. # print(f"已删除输入文件: {input_path}")
  103. #
  104. # @staticmethod
  105. # def htmlPDFWord(request):
  106. # html_content = request.POST.get("content", "<h1>Test Content</h1>")
  107. #
  108. # # 创建一个临时目录来存储生成的文件
  109. # output_dir = 'temp_files'
  110. # os.makedirs(output_dir, exist_ok=True)
  111. #
  112. # # 生成唯一的文件名
  113. # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
  114. # pdf_file = f'exported_document_{current_time}.pdf'
  115. # docx_file = f'exported_document_{current_time}.docx'
  116. # pdf_path = os.path.join(output_dir, pdf_file)
  117. # docx_path = os.path.join(output_dir, docx_file)
  118. #
  119. # try:
  120. # # 配置pdfkit选项
  121. # options = {
  122. # 'page-size': 'A4',
  123. # 'margin-top': '0.75in',
  124. # 'margin-right': '0.75in',
  125. # 'margin-bottom': '0.75in',
  126. # 'margin-left': '0.75in',
  127. # 'encoding': "UTF-8",
  128. # }
  129. #
  130. # # 指定wkhtmltopdf的路径
  131. # if sys.platform.startswith('win'):
  132. # config = pdfkit.configuration(wkhtmltopdf=r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
  133. # else:
  134. # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
  135. #
  136. # # 将HTML转换为PDF
  137. # pdfkit.from_string(html_content, pdf_path, options=options, configuration=config)
  138. #
  139. # # 将PDF转换为DOCX
  140. # cv = Converter(pdf_path)
  141. # cv.convert(docx_path)
  142. # cv.close()
  143. #
  144. # # 上传到阿里云OSS
  145. # oss_url = common.oss_upload_file(docx_path)
  146. #
  147. # # 获取文件大小
  148. # file_size = os.path.getsize(docx_path)
  149. #
  150. # # 返回成功响应,包含文件信息
  151. # return success({
  152. # "file_name": docx_file,
  153. # "file_path": oss_url,
  154. # "file_size": file_size
  155. # })
  156. #
  157. # except Exception as e:
  158. # return fail(f"文档生成或上传失败: {str(e)}")
  159. #
  160. # finally:
  161. # # 清理临时文件
  162. # if os.path.exists(pdf_path):
  163. # os.remove(pdf_path)
  164. # if os.path.exists(docx_path):
  165. # os.remove(docx_path)
  166. # # 尝试删除临时目录
  167. # try:
  168. # os.rmdir(output_dir)
  169. # except OSError:
  170. # # 如果目录不为空,就忽略错误
  171. # pass
  172. #
  173. # @staticmethod
  174. # def htmlPDF(request):
  175. # html_content = request.POST.get("content", "<h1>Test Content</h1>")
  176. #
  177. # # 创建一个临时目录来存储生成的PDF
  178. # output_dir = 'temp_pdf'
  179. # os.makedirs(output_dir, exist_ok=True)
  180. #
  181. # # 生成唯一的文件名
  182. # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
  183. # output_file = f'exported_document_{current_time}.pdf'
  184. # output_path = os.path.join(output_dir, output_file)
  185. #
  186. # try:
  187. # # 配置pdfkit选项
  188. # # 调整选项以放大内容
  189. # options = {
  190. # 'page-size': 'A4',
  191. # 'margin-top': '0.75in',
  192. # 'margin-right': '0.75in',
  193. # 'margin-bottom': '0.75in',
  194. # 'margin-left': '0.75in',
  195. # 'encoding': "UTF-8",
  196. # 'dpi': 300, # 增加 DPI 以提高清晰度
  197. # }
  198. #
  199. # # 指定wkhtmltopdf的路径
  200. # if sys.platform.startswith('win'):
  201. # config = pdfkit.configuration(wkhtmltopdf=r'D:\Program Files\wkhtmltopdf\bin\wkhtmltopdf.exe')
  202. # else:
  203. # config = pdfkit.configuration(wkhtmltopdf='/usr/local/bin/wkhtmltopdf')
  204. #
  205. # # 将HTML转换为PDF
  206. # pdfkit.from_string(html_content, output_path, options=options, configuration=config)
  207. #
  208. # # 上传到阿里云OSS
  209. # oss_url = common.oss_upload_file(output_path)
  210. #
  211. # # 获取文件大小
  212. # file_size = os.path.getsize(output_path)
  213. #
  214. # # 删除临时文件
  215. # os.remove(output_path)
  216. #
  217. # # 返回成功响应,包含文件信息
  218. # return success({
  219. # "file_name": output_file,
  220. # "file_path": oss_url,
  221. # "file_size": file_size
  222. # })
  223. #
  224. # except Exception as e:
  225. # # 如果出现错误,确保删除任何可能创建的临时文件
  226. # if os.path.exists(output_path):
  227. # os.remove(output_path)
  228. # return fail(f"PDF生成或上传失败: {str(e)}")
  229. #
  230. # finally:
  231. # # 尝试删除临时目录
  232. # try:
  233. # os.rmdir(output_dir)
  234. # except OSError:
  235. # # 如果目录不为空,就忽略错误
  236. # pass
  237. #
  238. # @staticmethod
  239. # def htmlWord(request):
  240. # html_content = request.POST.get("content", "<h1>Test Content</h1>")
  241. #
  242. # # 创建一个内存中的字节流来存储Word文档
  243. # output = io.BytesIO()
  244. #
  245. # # 使用mammoth将HTML转换为Word文档
  246. # style_map = """
  247. # p => p:fresh
  248. # h1 => h1:fresh
  249. # h2 => h2:fresh
  250. # h3 => h3:fresh
  251. # h4 => h4:fresh
  252. # h5 => h5:fresh
  253. # h6 => h6:fresh
  254. # strong => b
  255. # em => i
  256. # ul => ul
  257. # ol => ol
  258. # li => li
  259. # """
  260. # mammoth.convert_html_to_docx(html_content, output, style_map=style_map)
  261. #
  262. # # 生成唯一的文件名
  263. # current_time = datetime.now().strftime("%Y%m%d_%H%M%S")
  264. # output_file = f'exported_document_{current_time}.docx'
  265. # output_dir = 'temp_word'
  266. # os.makedirs(output_dir, exist_ok=True)
  267. # output_path = os.path.join(output_dir, output_file)
  268. #
  269. # try:
  270. # # 将内存中的文档保存到文件
  271. # with open(output_path, "wb") as f:
  272. # f.write(output.getvalue())
  273. #
  274. # # 上传到阿里云OSS
  275. # oss_url = common.oss_upload_file(output_path)
  276. #
  277. # # 获取文件大小
  278. # file_size = os.path.getsize(output_path)
  279. #
  280. # return success({
  281. # "file_name": output_file,
  282. # "file_path": oss_url,
  283. # "file_size": file_size
  284. # })
  285. #
  286. # except Exception as e:
  287. # return fail(f"Word文档生成或上传失败: {str(e)}")
  288. #
  289. # finally:
  290. # # 清理临时文件
  291. # if os.path.exists(output_path):
  292. # os.remove(output_path)
  293. # # 尝试删除临时目录
  294. # try:
  295. # os.rmdir(output_dir)
  296. # except OSError:
  297. # # 如果目录不为空,就忽略错误
  298. # pass
  299. #
  300. #
  301. #
  302. #
  303. #
  304. #
  305. #
  306. #
  307. #
  308. #
  309. #