Output a PDF in PHP from a byte array

前端 未结 5 1178
北恋
北恋 2021-01-01 06:00

I am getting a byte array from a WCF service that generated the PDF and converted it to a byte array. I need to able to get the byte array and using either PHP or Javascript

5条回答
  •  生来不讨喜
    2021-01-01 06:57

    As mention in my comment to your question, it looks like you're getting a string representation of an array of decimal representations of bytes. e.g. "[37,80,68,70]"

    You likely need to transform that.

    Can be done like this:

    // with:
    $data = "[50,20,36,34,65]";
    
    // remove brackets
    $data = trim($data,'[]');
    
    // split into array on ',' character
    $data = explode(',',$data);
    
    // transform each decimal value to a byte   representation. chr does just that
    $data = array_map('chr',$data);
    
    // turn the resulting array back into a string
    $data = implode('',$data);
    

    The comments about setting the headers to force download are also relevant so you should use that too.

    Here's the final code:

     $idPDF, "username" => $userPDF, "password" => $passPDF);                                                                    
    $result_string = json_encode($result);                                                
    $ch = curl_init('http://********.com/******/v1/DealPdf');                                                                      
    
    curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");                                                                     
    curl_setopt($ch, CURLOPT_POSTFIELDS, $result_string);                                                                 
    curl_setopt($ch, CURLOPT_VERBOSE, 1 );
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);                                                                
    curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
    
    $result = curl_exec($ch);
    
    // remove brackets
    $result = trim($result,'[]');
    
    // split into array on ',' character
    $result = explode(',',$result);
    
    // transform each decimal value to a byte   representation. chr does just that
    $result = array_map('chr',$result);
    
    // turn the resulting array back into a string
    $result = implode('',$result);
    
    echo $result;
    ?>
    

    Note that echo is used here, var_dump is not good as it adds extra formatting to the output.

    Also, note, you're not doing any testing on the result of the curl, if it fails you should probably handle the output differently.

提交回复
热议问题