簡體   English   中英

Python將json / html轉換為pdf

[英]Python convert json/html to pdf

我正在編寫一個腳本,用於將帶有html的json文件轉換為呈現的pdf。 我這樣寫:

from weasyprint import HTML  
from django.template import Template, Context
from django.template.loader import render_to_string, get_template
import json


context = json.load(open("source path"))

rendered_string = render_to_string("template.html", context)

HTML(string=rendered_string).write_pdf("sample.pdf")

問題是輸出,json中的所有html都被格式化為簡單文本和綁定類型... json部分還可以。 有人知道我該如何解決?

這是模板:

{%for elemento in elementi%}
 {%if not elemento.tipo%}
   <h1>{{elemento.html}}</h1>
 {%else%}
   <ul>
   {%for f in elemento.form %}
     <li>{{f}}</li>
   {%endfor%}
   </ul>
 {%endif%}
{%endfor%} 

這是json:

{"elementi":[{"id":107729,"titolo":null,"tipo":false,"form":null,"html":"<span lessico='Questa' idx=\"0\" testo=\"testo\" show-modal=\"setModal()\" tables=\"updateTables(input)\">Questa</span> <span lessico='&egrave;' idx=\"1\" testo=\"testo\" show-modal=\"setModal()\" tables=\"updateTables(input)\">&egrave;</span> <span lessico='una' idx=\"2\" testo=\"testo\" show-modal=\"setModal()\" tables=\"updateTables(input)\">una</span> <span lessico='domanda' idx=\"3\" testo=\"testo\" show-modal=\"setModal()\" tables=\"updateTables(input)\">domanda</span>...","traduci":[],"inputLessicale":[],"esercizioId":101624,"italiano":null,"testo_principale":"Questa &egrave; una domanda...","testo_principale_pre":"","testo_principale_post":"","risposta_1":"","risposta_2":"","risposta_3":"","risposta_4":"","distrattore_1":"","distrattore_2":"","distrattore_3":"","distrattore_4":"","parole_gia_ricostruite":"","continua":false,"focus":true,"ignora_lessico":false,"etichetta_1":null,"etichetta_2":null,"etichetta_3":null,"etichetta_4":null,"etichetta_5":null},
{"id":107730,"titolo":"Scegli la risposta corretta","tipo":"M","form":["a scelta multipla","con risposta aperta","di tipo trova","di associazione"],"html":null,"traduci":[],"inputLessicale":[],"esercizioId":101624,"italiano":null,"testo_principale":"a scelta multipla","testo_principale_pre":"","testo_principale_post":"","risposta_1":"","risposta_2":"","risposta_3":"","risposta_4":"","distrattore_1":"con risposta aperta","distrattore_2":"di associazione","distrattore_3":"di tipo trova","distrattore_4":"","parole_gia_ricostruite":"","continua":false,"focus":false,"ignora_lessico":false,"etichetta_1":null,"etichetta_2":null,"etichetta_3":null,"etichetta_4":null,"etichetta_5":null}],"ordine_in_verifica":null}

避免HTML注入是Django的一項安全功能,請通過類似的線程查看此答案:

https://stackoverflow.com/a/4848661/1047040

代替:

{{ elemento.html }}

用這個:

{{ elemento.html | safe }}

從Django文檔中:

將字符串標記為不需要在輸出之前進一步轉義HTML。 關閉自動轉義功能時,此過濾器無效。

鏈接: https//docs.djangoproject.com/en/dev/ref/templates/builtins/#safe

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM