How to crop PDF in PHP (AWS Linux)

Viewed 21

I want to crop PDF to 4*6 size, I am generating a FedEx Shipping label which provides me the label of 4X6 size but when we add that data into PDF it generates a label with A4 size with white space (Blue Highlighted area in the image).

I want the PDF to be generated 4X6 Or Data should be filled on Full A4 Size as there should be no white space.

FedEx API Call -

function prepareShipRequest(\Magento\Sales\Model\Order $order,$type,$labeltype)
        {
            $config = $this->_config;

            if($type == 'ground'){
                $type = 'FEDEX_GROUND';
            }

            if($type == 'express_saver'){
                $type = 'FEDEX_EXPRESS_SAVER';
            }


/*          if($labeltype == 'carton')
                $label_size = 'PAPER_7X4.75';
            else
                $label_size = 'PAPER_4X6';*/
            $label_size = 'PAPER_4X6';


            $request = [
                'WebAuthenticationDetail' => [
                    'UserCredential' => ['Key' => $config->getProperty('key'), 'Password' => $config->getProperty('password')]
                ],
                'ClientDetail' => ['AccountNumber' => $config->getProperty('shipaccount'), 'MeterNumber' => $config->getProperty('meter')],
                'TransactionDetail' => ['CustomerTransactionId' => $order->getIncrementId()],
                'Version' => $this->getVersionInfo(),
                'RequestedShipment' => [
                'DropoffType' => 'REGULAR_PICKUP', // valid values REGULAR_PICKUP, REQUEST_COURIER, DROP_BOX, BUSINESS_SERVICE_CENTER and STATION
                'ShipTimestamp' => date('c'),
                'PackagingType' => 'YOUR_PACKAGING', // valid values FEDEX_BOX, FEDEX_PAK, FEDEX_TUBE, YOUR_PACKAGING, ...
                'ServiceType' => $type,
                //'TotalInsuredValue' => ['Amount' => $r->getValue(), 'Currency' => $this->getCurrencyCode()],
                'Shipper' => $this->getShipper($order),
                'Recipient' => $this->getRecipient($order),
                'ShippingChargesPayment' => [
                    'PaymentType' => 'SENDER',
                    'Payor' => [
                        'ResponsibleParty' => [
                            'AccountNumber' => $config->getProperty('billaccount'),
                            'Contact' => null,
                            'Address' => [ 'CountryCode' => 'US' ]
                        ]
                    ]
                ],
                'LabelSpecification' => [
                    'LabelFormatType' => 'COMMON2D',
                    'ImageType' => 'PDF',
                        // 'LabelStockType' => 'PAPER_4X6' //PAPER_7X4.75 
                        'LabelStockType' => PAPER_4X6
                    ],                
                    'PackageCount' => '1',
                    'PackageDetail' => 'INDIVIDUAL_PACKAGES',
                    'RequestedPackageLineItems' => [
                        '0' => [
                            'Weight' => [
                                'Value' => 2.0,
                                'Units' => 'LB',
                            ],
                            'GroupPackageCount' => 1,
                            'CustomerReferences' => [
                                '0' => [ 'CustomerReferenceType' => 'P_O_NUMBER', 'Value' => $order->getIncrementId() ]
                            ]
                        ],
                    ],
                ],
            ];

            return $request;
        }

API Response to PDF creation -

try {

                $client = new \SoapClient($this->_wsdlDir.self::SHIP_SERVICE_WSDL, 
                    array(
                        'trace' => 1,
                        'stream_context' => stream_context_create(
                            array(
                                'http' => array(
                                    'protocol_version' => 1.0,
                                ),
                            )
                        ),
                    )
                );

                $FedexSanbox = "https://wsbeta.fedex.com:443/web-services/";

                if ($order->getStoreId() == 5 && $order->getIsRfr() == 1) {

                    $request = $this->prepareShipRequest($order, $type, 'carton');

                    $attempt = 1;
                    $error_str= '';
                    while ($attempt <= 2) {
                        $response = $client->processShipment($request);
                        if ($response->HighestSeverity != 'FAILURE' && $response->HighestSeverity != 'ERROR') {
                            $trackingNumber = $response->CompletedShipmentDetail->CompletedPackageDetails->TrackingIds->TrackingNumber;
                            $pdf = $response->CompletedShipmentDetail->CompletedPackageDetails->Label->Parts->Image;
                            $labelName = $order->getIncrementId() . ".pdf";
                            $fullPath = $this->_pubPath . "/" . self::LABEL_FOLDER . $labelName;
                            if (file_put_contents($fullPath, $pdf)) {
                                // shell_exec("pdfcrop " . $fullPath . " " . $fullPath);
                                //Save in DB
                                $this->_labels->setMageOrderId($order->getId());
                                $this->_labels->setLabelName($labelName);
                                $this->_labels->setLabelFullPath($fullPath);
                                $this->_labels->setTrackNumber($trackingNumber);
                                $objectManager = \Magento\Framework\App\ObjectManager::getInstance();
                                $magentoDateObject = $objectManager->create('Magento\Framework\Stdlib\DateTime\DateTime');
                                $this->_labels->setCreatedAt($magentoDateObject->gmtDate());
                                //$this->_labels->setLabelData(trim($pdf));
                                $this->_labels->save();
                                $attempt = 2;
                                return array(1, file_get_contents($fullPath));
                            } else {
                                // FILE NOT SAVED
                                return array(0, 'Label File I/O Failure ');
                            }
                        } else {
                            $errorCode = 0;
                            if (is_array($response->Notifications)) $errorCode = $response->Notifications[0]->Code;
                            else $errorCode = $response->Notifications->Code;
                            $attempt++;
                            if ($attempt == 2) {
                                $failureCodes = array(2012, 3024, 3037, 3039, 6581, 3040);
                                $newAddress = $this->validateAddress($order, $errorCode);
                                if (is_array($newAddress)) $request['RequestedShipment']['Shipper'] = $newAddress;
                            } else {
                                $error_str.= $this->printNotifications($response->Notifications);
                                mail("test@test.com", "FEDEX Shipping Labels EXCEPTION " . $order->getIncrementId(), $error_str);
                                return array(0, $error_str);
                            }
                        }
                    }
                } 

            }catch(SoapFault $e) {
                mail("test@test.com", "FEDEX Shipping Labels EXCEPTION " . $order->getIncrementId(), $e->getMessage());
                return array(0, '');
            } 

As I have passed Label Size (LabelStockType) as PAPER_4X6 still it is generating a PDF of A4 with white space.

Any help would be appreciated ..

Update

shell_exec("pdfcrop " . $fullPath . " " . $fullPath);

is not working on CentOS as pdfcrop package not available for CentOS.

enter image description here

0 Answers
Related