Печать номеров страниц с использованием Pisa

#python #html #django #pdf #pisa

#python #HTML #django #PDF #pisa

Вопрос:

Я использую pisa в своем проекте django, чтобы мой HTML-код генерировался в формате PDF для функциональности отчета. Некоторые из моих отчетов становятся довольно большими, и я заметил, что в них нет нумерации страниц. Кто-нибудь знает, как я могу заставить номера страниц отображаться в распечатанном отчете PDF?

Редактировать

вот как я создаю PDF

 if request.POST.has_key('print_report_submit'):
            context['show_report'] = True
            context['mb_logo'] = os.path.join(os.path.dirname(__file__), "../../../media/images/mb_logo.jpg")
            html = render_to_string('reports/fam_maturity_print.html', RequestContext(request,context))
            result = StringIO.StringIO()
            pdf = pisa.pisaDocument(StringIO.StringIO(html.encode("ISO-8859-1")), result)
            response = HttpResponse(result.getvalue(), mimetype='application/pdf')
            response['Content-Disposition'] = 'attachment; filename=family_maturity-statement.pdf'
            return response
  

HTML

 {% if show_report %}

<table width="100%">

    <tr>
        <td colspan="2" align="center" width="400px">
            <h1 class="title">Family Maturities by Year</h1>
            <br/><br/>
        </td>
    </tr>
    <tr>
        <td width="500px">
            <img src="{{ mb_logo }}"/>
        <td>                            <p>
              <img style="max-height: 60px; max-width:60px;" src="{{ check_image }}"/>
          </p>
    </tr>
</table>
    <br/>
    <br/>



   <hr class="report_hr1"/>
   <h2 class="state_head" style="font-size: 16px;">Statement Information As of {{ statement_date|date:"F d, Y" }}</h2>
<hr class="report_hr1"/>

    <table>

    {% for plan_dict in plan_list %}
        <hr class="report_hr2"/>
        <table>
        <tr>
            <td><strong>Plan Holder: </strong></td><td>{{ plan_dict.plan.get_primary_owner.member.client}}</td>
            <td><strong>Joint Owner(s): </strong></td>
            <td>
                {% for member in plan_dict.plan.planmember_set.all %}
                    {% ifnotequal member.ownership_type.code "primary" %}
                        {{ member }}
                    {% endifnotequal %}
                {% endfor %}
            </td>
        </tr>
        <tr>
            <td><strong>Plan ID: </strong></td><td>{{ plan_dict.plan.id }}</td>
        </tr>
        <tr>
            <td><strong>Plan type: </strong></td><td>{{ plan_dict.plan.plan_type }}</td>
        </tr>
        </table>
        <hr class="report_hr2"/>
        {#      This is the table for the current year's maturities      #}
        {% if plan_dict.investment %}
        <table>
            <td colspan="2"><h3>{{ cur_year }}</h3></td>
            <tr>
                <th>Financial Institution</th>
                <th>Type</th>
                <th>Principal</th>
                <th>Maturity</th>
            </tr>
            {% for i in plan_dict.investment %}
            <tr>
                <td>{{ i.financial_institution.abbr }}</td>
                <td>{{ i.product.code }}</td>
                <td>${{ i.amount|intcomma }}</td>
                <td>${{ i.maturity_amount|intcomma }}</td>
            </tr>
            {% endfor %}
            <tr>
                    <td><strong>Total for {{ cur_year }}</strong></td>
                    <td></td>
                    <td><strong>${{ plan_dict.total|intcomma }}</strong></td>
                    <td><strong>${{ plan_dict.total_m|intcomma }}</strong></td>
                </tr>
        </table>
        {% endif %}
        <div id="holding_table" align="center">
               <h3>Holding Totals with Each Company</h3>
               <table>
                    <tr>
                        <td style="font-weight: bold;">Financial Institution</td>
                        <td style="font-weight: bold;">Total</td>
                    </tr>
               {% for l in plan_dict.total_list %}
                   {% if l.maturity_amount__sum != None %}
                       <tr>
                        <td>{{ l.financial_institution__abbr }}</td>
                        <td>${{ l.maturity_amount__sum|intcomma }}</td>
                    </tr>
                   {% endif %}
               {% endfor %}
                    <tr>
                        <td style="font-weight: bold;">Total Non-Fund Holdings for this plan</td>
                        <td style="font-weight: bold;">${{ plan_dict.grand|intcomma }}</td>
                    </tr>
               </table>
                <span class="disclaimer_span">This report has been prepared from data believed to be reliable but no
                        representation is made as to accuracy or completeness.</span>
        </div>
        <br/>
        <br/>

    {% endfor %}
    </table>
{% endif %}
  

Любая помощь будет высоко оценена.

Ответ №1:

Как говорится в этой ссылке:

http://www.arnebrodowski.de/blog/501-Pisa-and-Reportlab-pitfalls.html

Одной из проблем, с которой я столкнулся, было добавление статического нижнего колонтитула на мои страницы, который содержит <pdf:pagenumber /> тег и должен показывать текущий номер страницы внизу каждой страницы результирующего PDF. Проблема заключалась в том, что на каждой странице просто отображалось число 0. Решение было очень простым, но я смог понять это только после изучения исходного кода pisa: вы можете использовать тег только внутри абзаца, а не (как я), например, внутри таблицы. Даже параграфы внутри таблиц не работают. Это должен быть абзац верхнего уровня.

Редактировать

Попробуйте это:

 <div>
   <pdf:pagenumber />
</div>
  

Комментарии:

1. Хорошо, итак, я попробовал это на своем html, который печатается <p><pdf:pagenumber /></p> , и ничего не отображается?

2. Как вы создаете свой PDF-файл?

3. Я не вижу, что вы используете <p><pdf:pagenumber /></p> и помните ссылку: «Вы можете использовать тег только внутри абзаца, а не (как я), например, внутри таблицы. Даже параграфы внутри таблиц не работают. Это должен быть абзац верхнего уровня «.

4. да, извините, я забыл включить это … это все еще не работает

5. Вы уверены, что ваш тег <pdf:pagenumber> не находится внутри таблицы?

Ответ №2:

Это работает для меня, вам нужно использовать это для формата A3

 @page{
        size: A3;
        margin: 1cm;

      @frame footer_frame {           /* Another static Frame */
        -pdf-frame-content: footer_content;
        left: 400pt; top: 1170pt; height: 20pt;
        
    }
    }
  

вы должны поместить в таблицу выше

 <div id="footer_content"> Page <pdf:pagenumber>
of <pdf:pagecount> </div>