Magento 2 Documentation  2.3
Documentation for Magento 2 CMS v2.3 (December 2018)
PrintLabel.php
Go to the documentation of this file.
1 <?php
8 
12 
14 {
20  const ADMIN_RESOURCE = 'Magento_Sales::shipment';
21 
25  protected $shipmentLoader;
26 
30  protected $labelGenerator;
31 
35  protected $_fileFactory;
36 
43  public function __construct(
44  Action\Context $context,
45  \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader $shipmentLoader,
46  \Magento\Shipping\Model\Shipping\LabelGenerator $labelGenerator,
47  \Magento\Framework\App\Response\Http\FileFactory $fileFactory
48  ) {
49  $this->shipmentLoader = $shipmentLoader;
50  $this->labelGenerator = $labelGenerator;
51  $this->_fileFactory = $fileFactory;
52  parent::__construct($context);
53  }
54 
60  public function execute()
61  {
62  try {
63  $this->shipmentLoader->setOrderId($this->getRequest()->getParam('order_id'));
64  $this->shipmentLoader->setShipmentId($this->getRequest()->getParam('shipment_id'));
65  $this->shipmentLoader->setShipment($this->getRequest()->getParam('shipment'));
66  $this->shipmentLoader->setTracking($this->getRequest()->getParam('tracking'));
67  $shipment = $this->shipmentLoader->load();
68  $labelContent = $shipment->getShippingLabel();
69  if ($labelContent) {
70  $pdfContent = null;
71  if (stripos($labelContent, '%PDF-') !== false) {
72  $pdfContent = $labelContent;
73  } else {
74  $pdf = new \Zend_Pdf();
75  $page = $this->labelGenerator->createPdfPageFromImageString($labelContent);
76  if (!$page) {
77  $this->messageManager->addError(
78  __(
79  'We don\'t recognize or support the file extension in this shipment: %1.',
80  $shipment->getIncrementId()
81  )
82  );
83  }
84  $pdf->pages[] = $page;
85  $pdfContent = $pdf->render();
86  }
87 
88  return $this->_fileFactory->create(
89  'ShippingLabel(' . $shipment->getIncrementId() . ').pdf',
90  $pdfContent,
92  'application/pdf'
93  );
94  }
95  } catch (\Magento\Framework\Exception\LocalizedException $e) {
96  $this->messageManager->addError($e->getMessage());
97  } catch (\Exception $e) {
98  $this->_objectManager->get(\Psr\Log\LoggerInterface::class)->critical($e);
99  $this->messageManager->addError(__('An error occurred while creating shipping label.'));
100  }
101  $this->_redirect(
102  'adminhtml/order_shipment/view',
103  ['shipment_id' => $this->getRequest()->getParam('shipment_id')]
104  );
105  }
106 }
__()
Definition: __.php:13
$page
Definition: pages.php:8
__construct(Action\Context $context, \Magento\Shipping\Controller\Adminhtml\Order\ShipmentLoader $shipmentLoader, \Magento\Shipping\Model\Shipping\LabelGenerator $labelGenerator, \Magento\Framework\App\Response\Http\FileFactory $fileFactory)
Definition: PrintLabel.php:43
foreach($order->getItems() as $orderItem) $shipment