2016-10-04 144 views
0

我想知道如何將包含一些Mathjax的HTML文件轉換爲pdf(爲了打印它)。我試圖使它的工作是這樣的:從easy_pdf.views進口PDFTemplateView使用reportlab將包含mathjax的html文件轉換爲pdf django

類HelloPDFView(PDFTemplateView)

VIEWS.PY : 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 

MyTemplate的。 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()), 
        ) 

但它沒有給我我期待的結果。我仍然可以在沒有任何Latex的情況下看到我的pdf中的「$$」。

如果有人可以解釋我這樣做最簡單的方法,那將是對我工作的項目真的很有幫助...

謝謝!

+0

上次我檢查,ReportLab的未執行JavaScript,因此MathJax將永遠不會運行。如果您可以在傳遞給reportlabs之前截取數學片段或完整html,您可能可以使用mathjax-node做些什麼。 –

+0

未來的注意事項:cdn.mathjax.org即將報廢,請查看https://www.mathjax.org/cdn-shutting-down/獲取遷移提示。 –

回答

0

我終於找到了解決方案:使用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 

而結果是完全一樣的我想...