[英]Exporting TextField in Django - Python model to PDF using ReportLab - line break becomes unprintable characters
我有一個模型屬性,可以保存用戶的HTML Textarea輸入。 因為當用戶在Textarea(提交的表單)中按Enter鍵時,我編寫了一個小的Javascript代碼來自動輸入“ \\ n”,從而換行了。
當我嘗試使用ReportLab將此屬性導出為PDF時,我收到了看起來像2個黑色矩形的不可打印字符。 當我嘗試將它們復制到文本板時,它變為“ n”。
這是模型中的代碼
class Package(models.Model):
content = models.TextField()
這是特定字段的JavaScript和HTML:
<form action="" role="form" method="post">{% csrf_token %}
<textarea class="form-control" autofocus name="content">{{content}}</textarea>
<br/>
</form>
<script type="text/javascript">
$('textarea').keypress(function(event) {
if (event.which == 13) {
event.preventDefault();
var s = $(this).val();
$(this).val(s+"\n");
}
});
</script>
這是來自views.py的Reportlab代碼:
from reportlab.pdfgen import canvas
from reportlab.platypus import Spacer
from reportlab.lib.pagesizes import letter
def create(pdf):
packet = StringIO.StringIO()
can = canvas.Canvas(packet, pagesize=letter)
p_content = str(package.content)
textobject = can.beginText(0.5*inch, 4.75*inch)
for line in p_content:
textobject.textOut(line)
if line=="\n":
textobject.textLines(p_content)
can.save()
請幫忙。 我似乎無法弄清楚。
非常感謝。
我已經得到了外界的幫助,所以我將其發布在這里給有興趣的人。
問題是這行代碼:
for line in p_content:
textobject.textOut(line)
if line=="\n":
textobject.textLines(p_content)
can.save()
我先檢查一下轉義字符,然后再打印。 正確的代碼應該是
for c in p_content:
if c == '\n':
textobject.textLine()
elif c == '\r':
pass # do nothing
else:
textobject.textOut(c)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.