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


<?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"/>

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.

1 Answer 1


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;

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;
        str_replace('/Annot /Subtype /Link', '/Annot /Subtype /Link /Border[0 0 0]', $pdf->render()),
  • It can download only pdf files but how can we download any type of file with same code?
    – Laty
    May 23, 2017 at 11:31
  • @Yogesh Karodiya I am getting issue - a:4:{i:0;s:76:"Error occured while '/var/www/html/test/pub/media/brochures' file reading."Object(Zend_Pdf_ElementFactory_Proxy), true)
    – jassi
    Jul 30, 2017 at 11:05

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.