""" 生成文档,包括word和pdf两种类型 """ import pypandoc import pdfkit from init import gcfg from utils import regular_filename #pdf文档的配置选项 options = { 'enable-local-file-access': None, # 允许访问本地文件 'page-size': 'A4', 'margin-top': '0.5in', 'margin-right': '0.5in', 'margin-bottom': '0.5in', 'margin-left': '0.5in', 'encoding': "UTF-8", 'custom-header': [ ('Accept-Encoding', 'gzip') ], 'no-outline': None, 'footer-center': '[page]', 'footer-font-size': '8', 'dpi': '300', 'disable-smart-shrinking': '' } header_html="""
""" html_template=""" {body} """ def gen_word(name,content): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.docx' fname=f'pub/{name}.docx' content = content.replace('src="/api/',f'src="{gcfg["fs"]["path"]}/') html_content = header_html+html_template.format(body=content) output = pypandoc.convert_text(html_content, 'docx', format='html', outputfile=path) return fname def gen_pdf(name,content): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.pdf' fname=f'pub/{name}.pdf' content = content.replace('src="/api/',f'src="files://{gcfg["fs"]["path"]}/') html_content = header_html+html_template.format(body=content) pdfkit.from_string(html_content, path,options=options) return fname def gen_ppt(name,content): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.pptx' fname=f'pub/{name}.pptx' from make_ppt2 import create_unified_ppt from gen_img_servie import create_ppt_images color = create_ppt_images() style={"title_style":2,"main_color":color,"style":0} create_unified_ppt(content,path,style) return fname #颜色转换 def hex_to_rgb(hex_color): # 去掉可能的 '#' 字符 hex_color = hex_color.lstrip('#') # 使用 int 和 base=16 将十六进制字符串转换为整数,然后用 ',' 分隔这些值,并创建一个元组 rgb = tuple(int(hex_color[i:i+2], 16) for i in (0, 2, 4)) return rgb def gen_ppt_by_ai(name,content,style): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.pptx' fname=f'pub/{name}.pptx' from make_ppt2 import create_unified_ppt from gen_img_servie import create_ppt_images style["main_color"] = hex_to_rgb(style["main_color"]) create_ppt_images(style["main_color"]) #宝石蓝 create_unified_ppt(content,path,style) return fname #生成海报 def gen_poster(name,content): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.png' fname=f'pub/{name}.png' from make_poster import create_poster create_poster(content,path) return fname #生成海报,根据样式生成 def gen_poster_style(name,content,style): name = regular_filename(name) path =f'{gcfg["fs"]["path"]}/pub/{name}.png' fname=f'pub/{name}.png' from make_poster import create_poster_style create_poster_style(content,path,style) return fname def test_pdf(): html_content = "这是生成文档的内容,如果出现乱码,请检查字体是否安装!
" pdfkit.from_string(html_content, 'output.pdf',options=options) print("文件已成功转换并保存至 output.pdf") if __name__=="__main__": test_pdf()