Error programmatically rendering an invoice PDF

by Manuel Di Iorio   Last Updated September 14, 2018 16:09 PM

The error:

Invalid template file: 'Magento_Payment::info/pdf/default.phtml' in module: 'Magento_Payment' block's name: 'info\instructions_0'

The class:

<?php
namespace Vendor\PDF\Response\Renderer;

use Magento\Framework\Webapi\Exception;
use Magento\Framework\Webapi\Rest\Request;
use Magento\Sales\Api\InvoiceRepositoryInterface;
use Magento\Framework\Webapi\Rest\Response\RendererInterface;
use Magento\Sales\Model\Order\Pdf\Invoice as InvoicePdf;

class PdfRenderer implements RendererInterface
{
    private $request;
    private $invoiceRepository;
    private $invoicePdf;

    /**
     * Pdf constructor.
     * @param \Magento\Framework\Webapi\Rest\Request $request
     * @param \Magento\Sales\Api\InvoiceRepositoryInterface $invoiceRepository
     * @param \Magento\Sales\Model\Order\Pdf\Invoice $invoicePdf
     */
    public function __construct(
        Request $request,
        InvoiceRepositoryInterface $invoiceRepository,
        InvoicePdf $invoicePdf
    ) {
        $this->request = $request;
        $this->invoiceRepository = $invoiceRepository;
        $this->invoicePdf = $invoicePdf;
    }

    /**
     * Render content in a certain format.
     *
     * @param object|array|int|string|bool|float|null $data
     * @return string
     * @throws \Magento\Framework\Webapi\Exception
     */
    public function render($data)
    {
        if (!strstr($this->request->getPathInfo(), '/V1/invoices')) {
            throw new Exception(__('PDF rendering is not supported for this URI'));
        }

        if (isset($data['entity_id'])) {
            $invoice = $this->invoiceRepository->get($data['entity_id']);

            try {
                $pdf = $this->invoicePdf->getPdf([$invoice]);

            } catch (\Exception $e) {
                header("Content-type: application/json");
                exit(json_encode([
                    "operationPerformed" => false,
                    "message" => $e->getMessage()
                ]));
            }

            return $pdf->render();
        } 

        throw new Exception(__('Invoice not found'));
    }

    /**
     * Get MIME type generated by renderer.
     *
     * @return string
     */
    public function getMimeType()
    {
        return 'application/pdf';
    }
}

The error happens when doing $this->invoicePdf->getPdf([$invoice]).

What am I missing ?

Tags : magento2 invoice


Related Questions


Does magento 2 support invoicing based on amount?

Updated September 21, 2018 01:09 AM