Python中哪个框架可以实现在线编辑器并生成类似PDF的样式?

null
Python中哪个框架可以实现在线编辑器并生成类似PDF的样式?

3 回复

要实现在线编辑器并生成类似PDF的样式,推荐用 Django + Quill.js + WeasyPrint 这套组合。

核心思路:

  1. 前端用 Quill.js 富文本编辑器,用户在线编辑内容。
  2. 后端 Django 接收编辑器的 HTML 内容。
  3. 用 WeasyPrint 把 HTML 转成带样式的 PDF。

具体代码示例:

1. 安装依赖:

pip install django weasyprint

2. Django 视图处理:

# views.py
from django.http import HttpResponse
from django.template.loader import render_to_string
from weasyprint import HTML
import json

def generate_pdf(request):
    if request.method == 'POST':
        # 获取 Quill 编辑器提交的 HTML 内容
        data = json.loads(request.body)
        html_content = data.get('content', '')
        
        # 创建带样式的 HTML 模板
        html_string = render_to_string('pdf_template.html', {
            'content': html_content
        })
        
        # 生成 PDF
        pdf_file = HTML(string=html_string).write_pdf()
        
        # 返回 PDF 文件
        response = HttpResponse(pdf_file, content_type='application/pdf')
        response['Content-Disposition'] = 'attachment; filename="document.pdf"'
        return response

3. HTML 模板(pdf_template.html):

<!DOCTYPE html>
<html>
<head>
    <style>
        /* PDF 样式定义 */
        body { font-family: Arial, sans-serif; line-height: 1.6; }
        .ql-editor { padding: 20px; }
        h1 { color: #333; }
        .ql-align-center { text-align: center; }
        /* 添加更多 Quill 样式匹配 */
    </style>
</head>
<body>
    <div class="ql-editor">
        {{ content|safe }}
    </div>
</body>
</html>

4. 前端 Quill 编辑器:

<div id="editor"></div>
<button onclick="generatePDF()">生成PDF</button>

<script src="https://cdn.quilljs.com/1.3.6/quill.js"></script>
<script>
    var quill = new Quill('#editor', { theme: 'snow' });
    
    function generatePDF() {
        const content = quill.root.innerHTML;
        fetch('/generate-pdf/', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ content: content })
        })
        .then(response => response.blob())
        .then(blob => {
            const url = window.URL.createObjectURL(blob);
            const a = document.createElement('a');
            a.href = url;
            a.download = 'document.pdf';
            a.click();
        });
    }
</script>

关键点说明:

  • Quill 编辑器生成的 HTML 带有特定 class(如 ql-editorql-align-center
  • 需要在 CSS 中正确定义这些 class 的打印样式
  • WeasyPrint 支持 CSS3,可以很好地控制分页、页眉页脚等

替代方案:

  • 如果只需要简单编辑,可以用 django-ckeditor 替代 Quill
  • 生成 PDF 也可以用 xhtml2pdf,但 WeasyPrint 对 CSS 支持更好

总结建议: 用 Django 做后端框架,配合 Quill 编辑器和 WeasyPrint 生成 PDF 最直接。


在线编辑器不是该区 JS 版块问吗?

python 哪个框架都不行, python 哪个框架都行

回到顶部