1

I have following code:

<?php
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

generateBestellschein();

and

execute();

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

How do I do that?

2 Answers 2

3

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:

<?php 
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;
        parent::__construct($context);
    }
    public function execute()
    {
        //do your custom stuff here
        $fileName = 'file name for download here';
        $this->fileFactory->create(
            $fileName,
            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;
    }
}
0
5

Should see good examples:

vendor/magento/module-sales/Controller/Adminhtml/Order/Pdfinvoices.php
vendor/magento/module-sales/Controller/Adminhtml/Order/Pdfshipments.php

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.

2
  • I will check out the examples. Thanks!:-) Commented Mar 22, 2018 at 12:13
  • Just see those examples, we will know how to create your own Commented Mar 22, 2018 at 16:14

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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