PrintAction.php 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475
  1. <?php
  2. /**
  3. *
  4. * Copyright © Magento, Inc. All rights reserved.
  5. * See COPYING.txt for license details.
  6. */
  7. namespace Magento\Sales\Controller\Adminhtml\Invoice\AbstractInvoice;
  8. use Magento\Framework\App\ResponseInterface;
  9. use Magento\Framework\App\Filesystem\DirectoryList;
  10. abstract class PrintAction extends \Magento\Backend\App\Action
  11. {
  12. /**
  13. * Authorization level of a basic admin session
  14. *
  15. * @see _isAllowed()
  16. */
  17. const ADMIN_RESOURCE = 'Magento_Sales::sales_invoice';
  18. /**
  19. * @var \Magento\Framework\App\Response\Http\FileFactory
  20. */
  21. protected $_fileFactory;
  22. /**
  23. * @var \Magento\Backend\Model\View\Result\ForwardFactory
  24. */
  25. protected $resultForwardFactory;
  26. /**
  27. * @param \Magento\Backend\App\Action\Context $context
  28. * @param \Magento\Framework\App\Response\Http\FileFactory $fileFactory
  29. * @param \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
  30. */
  31. public function __construct(
  32. \Magento\Backend\App\Action\Context $context,
  33. \Magento\Framework\App\Response\Http\FileFactory $fileFactory,
  34. \Magento\Backend\Model\View\Result\ForwardFactory $resultForwardFactory
  35. ) {
  36. $this->_fileFactory = $fileFactory;
  37. parent::__construct($context);
  38. $this->resultForwardFactory = $resultForwardFactory;
  39. }
  40. /**
  41. * @return ResponseInterface|void
  42. * @throws \Exception
  43. */
  44. public function execute()
  45. {
  46. $invoiceId = $this->getRequest()->getParam('invoice_id');
  47. if ($invoiceId) {
  48. $invoice = $this->_objectManager->create(
  49. \Magento\Sales\Api\InvoiceRepositoryInterface::class
  50. )->get($invoiceId);
  51. if ($invoice) {
  52. $pdf = $this->_objectManager->create(\Magento\Sales\Model\Order\Pdf\Invoice::class)->getPdf([$invoice]);
  53. $date = $this->_objectManager->get(
  54. \Magento\Framework\Stdlib\DateTime\DateTime::class
  55. )->date('Y-m-d_H-i-s');
  56. $fileContent = ['type' => 'string', 'value' => $pdf->render(), 'rm' => true];
  57. return $this->_fileFactory->create(
  58. 'invoice' . $date . '.pdf',
  59. $fileContent,
  60. DirectoryList::VAR_DIR,
  61. 'application/pdf'
  62. );
  63. }
  64. } else {
  65. return $this->resultForwardFactory->create()->forward('noroute');
  66. }
  67. }
  68. }