kaliscope
kaliscope

Reputation: 41

Send pdf from wp_remote_get to browser

I'm integrating a wordpress site with an external API. I have a form that posts to my server and I call a function on my server that makes a wp_remote_get call to the external API.

The external API returns a PDF, with headers like:

        [date] => Fri, 18 Aug 2017 15:59:19 GMT
        [x-powered-by] => Servlet/3.0
        [cache-control] => no-cache
        [content-type] => application/pdf;charset=utf-8
        [content-language] => en-US

And the response body is the PDF in nasty string format, which seems like a good start.

How do I pass this PDF to the user's browser? ie,

$response = wp_remote_get( $url, array ( //stuff the request needs));
if (is_wp_error ($response)) {
    $error_message = $response->get_error_message();
    echo "Something went wrong: $error_message";
} else {
    //What here?
}

I have to hit my server first, cannot post the form directly to the external API.

Upvotes: 2

Views: 1122

Answers (1)

kaliscope
kaliscope

Reputation: 41

I managed this by using javascript to redirect my form submit to a new window on my site, passing along the form information as URL params. ie, in my HTML:

<form onsubmit="return qrsDownload()">

And then in javascript:

function qrsDownload() {
    // a bunch of jquery and processing to build the URL..
    window.open(url, 'My Title', 'width=800, height=600');
}

The page I opened was a single-use page template I created, that I omitted the standard WP templates in (so no header, no footer, no wordpress loop), and in that page's php file:

<?php 
if (isset($_GET['someParam'])) {
  // started off with logic to verify that I had the params needed
  // because anybody could just jump directly to this page now
}
$url = "whateverurl.com/myendpoint";
// additional logic to set up the API call
$server_response = wp_remote_get($url, $args);
if (is_wp_error( $server_response) ) {
    // do something to handle error
} else {
    // PASS OUR PDF to the user
    $response_body = wp_remote_retrieve_body( $server_response);
    header("Content-type: application/pdf");
    header("Content-disposition: attachment;filename=downloaded.pdf");
    echo $response_body;
}
} else {
     get_header();
    $html = "<div class='content-container'><p>A pretty error message here.</p></div>";
     echo $html;
     get_footer();
}

?>

The approach is essentially to pass the result from the API straight back out the user, but you need the headers to specific it's a PDF, and the headers have to be set before you write out any output. An easier way to ensure this was to do it in a new window, rather than strictly on the form postback.

Upvotes: 2

Related Questions