1

Below is my Laravel function for generating a waybill from the courier provider. Currently, the code is working fine but the waybill pdf is directly open in the browser. How do I force it to download the pdf?

public function awb(Request $request)
{
    function e($str) {print'<pre>';print_r($str);print'</pre>';}

    $url = 'http://web.com/print/print.action';

    $key = $request->key;
    $billCode = $key;

    $data = array(
    'billcode' => $billCode,
    'account' => 'xxx',
    'password' => 'xxx',
    'customercode' => 'xxx',
    );

    $t = array('logistics_interface' => json_encode($data), 'msg_type' =>
    '1', 'data_digest' => md5($billCode));

    $s = curl_init();

    curl_setopt($s,CURLOPT_URL,$url);
    curl_setopt($s,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($s,CURLOPT_POSTFIELDS,http_build_query($t));
    header('Content-type: application/pdf');

    $r = curl_exec($s);
    curl_close($s);

    e($r);
}
Izzat Z.
  • 437
  • 1
  • 7
  • 15
  • Does this answer your question? [How to force file download with PHP](https://stackoverflow.com/questions/7263923/how-to-force-file-download-with-php) – ArSeN Aug 19 '21 at 18:46

1 Answers1

1

Your need save request to file and return download

public function awb(Request $request)
{
    function e($str) {print'<pre>';print_r($str);print'</pre>';}

    $url = 'http://web.com/print/print.action';

    $key = $request->key;
    $billCode = $key;

    $data = array(
    'billcode' => $billCode,
    'account' => 'xxx',
    'password' => 'xxx',
    'customercode' => 'xxx',
    );

    $t = array('logistics_interface' => json_encode($data), 'msg_type' =>
    '1', 'data_digest' => md5($billCode));

    $s = curl_init();

    curl_setopt($s,CURLOPT_URL,$url);
    curl_setopt($s,CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($s,CURLOPT_RETURNTRANSFER,true);
    curl_setopt($s,CURLOPT_POSTFIELDS,http_build_query($t));
    //header('Content-type: application/pdf');

    $r = curl_exec($s);
    curl_close($s);
    
    $f = 'pdf/download.pdf';
    Storage::disk('local')->put($f, $r);
    return Response::download(Storage::disk('local')->getDriver()->getAdapter()->applyPathPrefix($f));
}
jrz.soft.mx
  • 151
  • 1
  • 1
  • 11