0

Is there a way to programatically save pdf invoices to a directory on the magento server without the system attempting to download it?

I currently use the below code to generate and save the file to a directory on the server but it also attempts to download it. I just need the link which I already get as output but want to prevent the auto downloading it.

Thanks in advance.

$filename = 'pdf/Invoice-' . $invoiceCollection->getFirstItem()->getIncrementId() . '.pdf';
try{
    $pdf = $this->pdfInvoice->getPdf($invoiceCollection);
    $file = $this->fileFactory->create(
    $filename,
    $pdf->render(),
    DirectoryList::MEDIA,
    'application/pdf'
);
$mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA ) . $filename;
} catch (\Exception $e) {
    $this->logger->info('Error printing invoice: ' . $e->getMessage() . ' error.');
}

1 Answer 1

0

Instead of using the fileFactory, I was able to use php's file_put_contents function to create the file in the desired directory. These function requires two input, the first being the file path and the second being the content. Replacing the fileFactory, final script looked like below;

$filename = 'pdf/Invoice-' . $invoiceCollection->getFirstItem()->getIncrementId() . '.pdf';
try{
    $pdf = $this->pdfInvoice->getPdf($invoiceCollection);
    $file = $this->directoryList->getPath('media') . $filename;
    file_put_contents( $file, $pdf->render());
    $mediaUrl = $this->_storeManager->getStore()->getBaseUrl(\Magento\Framework\UrlInterface::URL_TYPE_MEDIA ) . $filename;
} catch (\Exception $e) {
    $this->logger->info('Error printing invoice: ' . $e->getMessage() . ' error.');
}

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.