【问题标题】:Convert html file containing mathjax to pdf using reportlab django使用reportlab django将包含mathjax的html文件转换为pdf
【发布时间】:2017-02-13 05:21:00
【问题描述】:

我想知道如何将包含一些 Mathjax 的 HTML 文件转换为 pdf(以便打印)。我试图让它像这样工作:

VIEWS.PY 从 easy_pdf.views 导入 PDFTemplateView

类 HelloPDFView(PDFTemplateView): template_name = "mytemplate.html"

def get_context_data(self, **kwargs):    
    context = super(HelloPDFView, self).get_context_data(
            pagesize="A4",
            title="Hi Pierre!",
            **kwargs
        )
    context.update({'variable':12})
    return context

我的模板.HTML

{% extends "easy_pdf/base.html" %}

{% block extra_style %}
<script type="text/x-mathjax-config">
  MathJax.Hub.Config({
    tex2jax: {inlineMath: [["$","$"],["\\(","\\)"]]}
  });
</script>

<script type="text/javascript" src="https://cdn.mathjax.org/mathjax/latest/MathJax.js?config=TeX-MML-AM_HTMLorMML"></script>

{% endblock %}

{% block content %}
    <div id="content">
        <h1>Hi there!{{variable}}</h1>

        {% autoescape on %} 
            $$ \frac{a}{b} x=2 $$
        {% endautoescape %}
    </div>
{% endblock %}

URLS.PY

urlpatterns = patterns('',
                       ('^monpremierpdf.pdf$', HelloPDFView.as_view()),
                      )

但这并没有给我预期的结果。而且我仍然可以在我的 pdf 中看到“$$”,但里面没有任何乳胶。

如果有人可以向我解释最简单的方法,那对我正在从事的项目非常有帮助......

谢谢!

【问题讨论】:

  • 上次我检查,reportlab 没有执行 JavaScript,所以 MathJax 永远不会运行。如果您可以在将数学片段或完整的 html 传递给 reportlabs 之前截获它,您也许可以使用 mathjax-node 做一些事情。
  • 未来注意事项:cdn.mathjax.org 即将结束生命周期,请查看mathjax.org/cdn-shutting-down 了解迁移提示。

标签: django pdf pdf-generation mathjax reportlab


【解决方案1】:

我终于找到了解决办法:使用 pdfcrowd

1°。在这里订阅:pdfcrowd.com 2°。他们为您提供用户名和 API 密钥(前 100 个令牌是免费的) 3°。运行:pip install pdfcrowd 4°。

import pdfcrowd
def generate_pdf_view(request):
    path_to_html_file = os.path.join(settings.PROJECT_ROOT,"templates/mytemplate.html")
    try:
        # create an API client instance
        client = pdfcrowd.Client("<username>", "<API_key>")

        # convert a web page and store the generated PDF to a variable
        pdf = client.convertFile(path_to_html_file)

         # set HTTP response headers
        response = HttpResponse(content_type="application/pdf")
        response["Cache-Control"] = "max-age=0"
        response["Accept-Ranges"] = "none"
        response["Content-Disposition"] = "attachment; filename=myamazingPDF.pdf"

        # send the generated PDF
        response.write(pdf)
    except pdfcrowd.Error, why:
        response = HttpResponse(content_type="text/plain")
        response.write(why)
    return response

结果正是我想要的......

【讨论】:

    猜你喜欢
    • 2023-03-06
    • 2011-12-23
    • 1970-01-01
    • 1970-01-01
    • 2013-04-07
    • 2023-03-15
    • 2011-06-17
    • 2012-05-05
    • 2011-05-22
    相关资源
    最近更新 更多