Django文档为ReportLab提供了以下示例。
from reportlab.pdfgen import canvas
from django.http import HttpResponse
def some_view(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
# Create the PDF object, using the response object as its "file."
p = canvas.Canvas(response)
# Draw things on the PDF. Here's where the PDF generation happens.
# See the ReportLab documentation for the full list of functionality.
p.drawString(100, 100, "Hello world.")
# Close the PDF object cleanly, and we're done.
p.showPage()
p.save()
return response
但是。我想使用RML生成我的PDF。 ReportLab Plus提供了rml2pdf
函数,可以使用与Django模板相似的标记将RML文档转换为PDF。如何为Django提供RML模板,并让Django在API响应中返回PDF,类似于文档中的示例?
答案 0 :(得分:0)
弄清楚了。
将其放在Django模板文件夹中,以便Django可以找到它。
命名为templates/rml_template.rml
<!DOCTYPE document SYSTEM "rml.dtd">
<document filename="example_01.pdf">
<template>
<!--this section contains elements of the document -->
<!--which are FIXED into position. -->
<pageTemplate id="main">
<frame id="first" x1="100" y1="400" width="150" height="200"/>
</pageTemplate>
</template>
<stylesheet>
<!--this section contains the STYLE information for -->
<!--the document, but there isn't any yet. The tags still -->
<!--have to be present, however, or the document won't compile.-->
</stylesheet>
<story>
<!--this section contains the FLOWABLE elements of the -->
<!--document. These elements will fill up the frames -->
<!--defined in the <template> section above. -->
<para>
Welcome to RML!
</para>
<para>
This is the "story". This is the part of the RML document where
your text is placed.
</para>
<para>
It should be enclosed in "para" and "/para" tags to turn it into
paragraphs.
</para>
</story>
</document>
此视图以字符串形式加载模板,rml2pdf使用响应对象作为要写入的“文件”,类似于Django文档示例。
from django.template import loader
from rlextra.rml2pdf import rml2pdf
from django.http import HttpResponse
def some_view(request):
# Create the HttpResponse object with the appropriate PDF headers.
response = HttpResponse(content_type='application/pdf')
response['Content-Disposition'] = 'attachment; filename="somefilename.pdf"'
context = {} # You can add values to be inserted into the template here
rml = str(loader.render_to_string('rml_template.rml', context))
rml2pdf.go(rml, outputFileName=response)
return response