Senarist01
Senarist01

Reputation: 133

How to add new page to report from other PDF

I have a report (qweb-pdf). How to add a new page to this report from another pdf?

<template id="report_commercial_offer">
    <t t-call="web.html_container">
      <t t-foreach="docs"
        t-as="doc">
        ... some code
         <p style="page-break-after:always;">   </p>
          <p> Test New Page  </p>
          <div class="t">
                 <span t-esc="doc.test_func()" />
          </div>
      </t>
    </t>
  </template>

In this function test_func() I want to add a page from another pdf (for example D:\file1.pdf) to this pdf. I tried to use libraries: PyPDF2, slate3k but failed...

Upvotes: 1

Views: 302

Answers (1)

Kenly
Kenly

Reputation: 26698

You can use a controller to add the page before you download the report.

from PyPDF2 import PdfFileReader, PdfFileWriter
import io
from odoo import http
from odoo.http import request


class MergePdf(http.Controller):

    @http.route('/report/custom_invoice/<int:invoice_id>', auth="user")
    def print_custom_invoice(self, invoice_id, **kw):

        report_date, report_name = request.env.ref('account.account_invoices').sudo().render_qweb_pdf([invoice_id])
        pdf_data = io.BytesIO(report_date)
        file1 = PdfFileReader(stream=pdf_data)

        # Store template PDF in ir.attachment table
        page = request.env['ir.attachment'].search([('name', '=', 'invoice_document')], limit=1)
        page_data = io.BytesIO(base64.b64decode(page.datas))
        file2 = PdfFileReader(stream=page_data)

        # Read a template PDF
        # file2 = PdfFileReader(open(file_path, "rb"))

        output = PdfFileWriter()

        # Add all report pages
        output.appendPagesFromReader(file1)

        # Add the requested page from template pdf
        output.addPage(file2.getPage(0))

        output_stream = io.BytesIO()
        output.write(output_stream)

        data = output_stream.getvalue()
        pdf_http_headers = [('Content-Type', 'application/pdf'), ('Content-Length', len(data))]
        return request.make_response(data, headers=pdf_http_headers)

Then print the report using a button:

@api.multi
def send_sms(self):
    self.ensure_one()
    return {
        "type": "ir.actions.act_url",
        "url": "/report/custom_invoice/%s" % self.id,
        "target": "self",
    }

Upvotes: 1

Related Questions