How to change save path of PDF files in magento 2
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;
}
...
Looking at other methods where a subfolder of var
or media
is used and given the fact, that DirectoryList::VAR_DIR
returns the string value 'var'
I think it's save to assume it's fine to concat it via Directory Separator (DS).
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 . DS . 'pdf',
'application/pdf'
);
}
}
return $this->resultRedirectFactory->create()->setPath('sales/*/view');
}