CakePHP 4: how to redirect to view after PDF is downloaded using CakePDF

After a PDF is generated and downloaded I want to reload the view to get the flash success message.
But when I use a redirect no pdf is generated but the view is reloaded.

public function smakeOrders(?string $id = null): void
{
    $smakeShop = $this->SmakeShops->get($id, [
        'contain' => [],
    ]);

    $this->loadComponent('SmakeAPI', [
        'endpoint' => $smakeShop->endpoint,
        'token' => $smakeShop->token,
    ]);

    $orders = $this->SmakeAPI->getOrders($this->request->getAttribute('params'));
    $ordersCount = count($orders);
    $subtotal = $this->SmakeAPI->getTotal();
    $subtotalVat = $this->SmakeAPI->getTotal(true);
    $subtotalShipping = $this->SmakeAPI->getTotalShipping();
    $subtotalShippingVat = $this->SmakeAPI->getTotalShipping(true);

    if ($ordersCount > 0) {
        $this->viewBuilder()->setClassName('CakePdf.Pdf');
        $this->viewBuilder()->setOption(
            'pdfConfig',
            [
                'download' => true,
                'filename' => 'bestelllisten-nr-' .
                    FrozenTime::now()->format('Y') .
                    $smakeShop->document_number . '-' .
                    $smakeShop->company . '.pdf',
            ]
        );
    }

    $smakeShop = $this->SmakeShops->patchEntity($smakeShop, [
        'document_number' => $smakeShop->document_number + 1,
    ]);
    $this->SmakeShops->save($smakeShop);

    if ($ordersCount > 0) {
        $this->Flash->success(__("Orders found: {$ordersCount} | PDF generated"));
    } else {
        $this->Flash->error(__('No Orders found'));
    }

    $this->set(['orders' => $orders,
        'smakeShop' => $smakeShop,
        'subtotal' => $subtotal,
        'subtotalVat' => $subtotalVat,
        'subtotalShipping' => $subtotalShipping,
        'subtotalShippingVat' => $subtotalShippingVat,
        'now' => FrozenTime::now()]);

    // if this is set view gets reloaded but no pdf is generated
    $this->redirect(['action' => 'view', $id]);
}

Does anyone have an idea or a hint how to implement this?

It looks like you’re using the view builder to create the PDF. But if you redirect, then no view is rendered. It’s an “either / or” thing, a request can have only one response, which is either content or a redirect. Is the intent that the PDF will be sent immediately to the user to either view in the browser or download and save? If so, what purpose does the flash message serve? They should be pretty clearly aware that a PDF was generated, because it was already presented to them.

Good Point!

Yes

The only alternative I can think of would be to create and save a PDF document first and then initiate a download.

Regardless of how you create the PDF, if you initiate a download of it to the user right away, you cannot also do a redirect.