Magento 2 – How to Change Save Path of PDF Files

magento2pdf

Currently PDF files are saving in var directory.

Here is controller's execute function

 public function execute()
    {  
        $orderId = $this->getRequest()->getParam('id');
        if ($orderId) {
            $order = $this->orderRepository->get($orderId);
            if ($order) {
                $pdf = $this->orderPdfFactory->create()->getPdf([$order]);
                $date = $this->date->date('Y-m-d_H-i-s');
                return $this->fileFactory->create(
                    'order' . $date . '.pdf',
                    $pdf->render(),
                    DirectoryList::VAR_DIR,
                    'application/pdf'
                );
            }
        }
        return $this->resultRedirectFactory->create()->setPath('sales/*/view');
    }

DirectoryList::VAR_DIR,

Above code responsible for that. Now my question is that I want to save pdf files under var/pdf directory. How can I do this ?

Best Answer

You can do this in 2 ways:

1.The easiest way is to add in the file name the path, for example:

return $this->fileFactory->create(
    'custom/path/ . 'order' . $date . '.pdf',
    $pdf->render(),
    DirectoryList::VAR_DIR,
    'application/pdf'
);

2. Find a way to override the DirectoryList Class "Magento\Framework\App\Filesystem\DirectoryList" and add a constant with your custom path.

...
/**
* Code base root
*/
const ROOT = 'base';

const CUSTOM_PATH = 'var/pdf';
...
public static function getDefaultConfig()
{
    $result = [
        self::ROOT => [parent::PATH => ''],
        ...
        self::CUSTOM_PATH => [parent::PATH => 'var/pdf/'],
    ];
    return parent::getDefaultConfig() + $result;
}
...