How can I create a pdf file with Product details and download it by clicking on download image in product list page in magento 2.Can anybody Help me on this.

  • Do you want to download as per category?
    – Keith
    Jun 26, 2017 at 9:19

1 Answer 1


Action will be pass in html form as below :

<form id="download_product" method="POST" action="<?php echo $this->getUrl('module/foldername/action')?>">

Then below code you can add into your controller:

namespace vendor\modulename\Controller\foldername;

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

class actionname extends Action

protected $mycustomblock;

    public function __construct(
        \Magento\Framework\App\Action\Context $context,
        \vendor\modulename\Block\Mycustomblock $mycustomblock,
        array $data = [])
        $this->mycustomblock = $mycustomblock;

    public function execute()
        $params = $this->getRequest()->getParams();
        $categoryId = $params['category'];//Here i am passing category id from my form or you can get current category id if you are in a listing page

        $heading = array('Name','Id','Sku','Qty','Availability'); //here you can add details as per your requirement

        $outputFile = "products_". date('Ymd_His').".csv";
        $handle = fopen($outputFile, 'w');
        fputcsv($handle, $heading);

        //fputcsv($fp, $header);
         foreach($categoryId as $key => $id ) 
        $categoryProducts = $this->mycustomblock->getProductCollection($id); you can get product collection

                foreach ($categoryProducts as $product) {
                    $productStock = $this->mycustomblock->getStockItem($product->getId());

                    $output[]= $product->getName();
                    $output[]= $product->getId();
                    $output[]= $product->getSku();
                    $output[]= $productStock->getQty();
                    $output[]= $productStock->getIsInStock();
                    fputcsv($handle, $output); 



        if (!unlink($file))
          echo ("Error deleting $file");
          echo ("Deleted $file");

        //return $this;


    public function downloadCsv($file){
        if (file_exists($file)) {
            //set appropriate headers
            header('Content-Description: File Transfer');
            header('Content-Type: application/csv');
            header('Content-Disposition: attachment; filename='.basename($file));
            header('Expires: 0');
            header('Cache-Control: must-revalidate');
            header('Pragma: public');
            header('Content-Length: ' . filesize($file));


Let me know if you will need more help!

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.