I have following code:

namespace UV\Bestellung\Controller\Adminhtml\Index;

use Magento\Framework\App\Action\Action;
use Magento\Framework\Controller\ResultFactory;

class Index extends Action

    public function generateBestellschein() {
        $pdf = new Zend("Bestellschein.pdf");

        return $pdf;

    public function execute()
        return generateBestellschein();

I am creating a PDF via




is executed when custom button is clicked. I want it to start a download of the PDF.

How do I do that?


Sample code for download file.

you can create your controller action by extending \Magento\Backend\App\Action for backend or \Magento\Framework\App\Action\Action for frontend.
and make it look like this:

namespace Your\Namespace\Here;

class ClassName extends \Magento\Backend\App\Action 
    public function __construct(
        \Magento\Framework\Controller\Result\RawFactory $resultRawFactory,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
        \Magento\Backend\App\Action\Context $context
    ) {
        $this->resultRawFactory      = $resultRawFactory;
        $this->fileFactory           = $fileFactory;
    public function execute()
        //do your custom stuff here
        $fileName = 'file name for download here';
            null, //content here. it can be null and set later 
            base dir of the file to download here
            'application/octet-stream', //content type here
            content lenght here...can be null
        $resultRaw = $this->resultRawFactory->create();
        $resultRaw->setContents(contents of file here); //set content for download file here
        return $resultRaw;

Should see good examples:


We should use \Magento\Framework\App\Response\Http\FileFactory to declare headers and content file in response for file download.

But, the Pdf content renderer is not easy. You should take a look at some existing code lines. You can use some PDF libraries.

  • I will check out the examples. Thanks!:-) – k33n Mar 22 '18 at 12:13
  • Just see those examples, we will know how to create your own – Khoa TruongDinh Mar 22 '18 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.