Как я могу создать конечную точку API DjRF, которая возвращает сгенерированный RML PDF? - PullRequest
0 голосов
/ 03 июля 2019

Документация 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, которая может преобразовать документ RML в PDF с использованием разметки, аналогичной шаблонизированию Django.Как я могу предоставить Django шаблон RML и сделать так, чтобы Django возвращал PDF в ответе API, аналогично примеру в документации?

1 Ответ

0 голосов
/ 03 июля 2019

Разобрался.

Шаблон RML

Поместите это в папку с шаблонами 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>

Представление Django

Это представление загружает шаблон в виде строки, а 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
...