Magento2 – Create Download Link in Custom Module

downloadmagento2module

I have created the simple custom module in Magento2. Which show pages correctly now I need to create the link on that page which download the PDF file which is in module web folder.

 For Ex app\code\Magento\Hello\view\frontend\web\pdf\test.pdf

What should I do? DO I need to add the routing for new function if yes how I can do that currently my routing file is

\app\code\Magento\Hello\etc\frontend\routes.xml

<?xml version="1.0"?> 
<config xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:noNamespaceSchemaLocation="urn:magento:framework:App/etc/routes.xsd">
    <router id="standard">
        <route id="hello" frontName="hello">
            <module name="Magento_Hello"/>
        </route>
    </router> 
</config>

rest of the files are simple module files with no modification.

Please let me know where I need to write the download code for the link

Thank you.

Best Answer

This is the sample code for download pdf in magento2

namespace Namespace\ModuleName\Controller\ControllerName;

use Magento\Framework\App\Filesystem\DirectoryList;
class Download extends \Magento\Framework\App\Action\Action
{
protected $directory_list;
protected $fileFactory;
public function __construct(
        \Magento\Framework\App\Action\Context $context, 
        DirectoryList $directory_list,
        \Magento\Framework\App\Response\Http\FileFactory $fileFactory) {
    $this->directory_list = $directory_list;
    $this->fileFactory = $fileFactory;
    parent::__construct($context);
}

public function execute()
{
    $file = $this->getRequest()->getParam('file');

    if(isset($file) && !empty($file)) {

        $pdf = \Zend_Pdf::load($this->directory_list->getPath(DirectoryList::MEDIA) . DIRECTORY_SEPARATOR . $file);
        $fileName = test.pdf;
        $this->fileFactory->create(
        $fileName,
        str_replace('/Annot /Subtype /Link', '/Annot /Subtype /Link /Border[0 0 0]', $pdf->render()),
        \Magento\Framework\App\Filesystem\DirectoryList::VAR_DIR,
        'application/pdf'
        );
    }
}
}
Related Topic