Data is returned in response, but isn't being saved / displayed as PDF
br0wnie opened this issue · comments
Hello, I can't seem to get this to work.
-
With the code below running from a REST request, I get ~6.7MB of what looks like binary data (not sure how else to describe it, you can see some of it in this screenshot)
-
I looked at some of the data and can see some links that are on the page being created (example: social media links) so I think the PDF data is being created correctly it just isn't taking that next step and downloading.
-
If I assign the result of $snappy->getOutput($url); to a variable, and then use file_put_contents it saves a PDF that has no styles but does have the content.
OS: Manjaro Linux
Kernel Version: 5.10.36-2-MANJARO
wkhtmltopdf: 0.12.5-1, installed using pacman
JS:
const jsButtonsCreatePDF = document.getElementsByClassName('js-download-report-pdf');
for(const button of jsButtonsCreatePDF) {
button.addEventListener('click', event => {
axios.post('/wp-json/h5bs/v1/generate-pdf-server-side', {
url: window.location.href
}).then(response => {
console.log(response);
})
});
}
PHP:
<?php
use Knp\Snappy\Pdf;
// REST API setup
add_action( 'rest_api_init', 'h5bs_register_routes' );
function h5bs_register_routes() {
register_rest_route( 'h5bs/v1', '/generate-pdf-server-side', [
'methods' => 'POST',
'callback' => 'h5bs_generate_pdf_server_side',
] );
}
function h5bs_generate_pdf_server_side( WP_REST_Request $request ) {
$params = $request->get_json_params();
$url = $params['url'];
$directory = '/usr/bin/wkhtmltopdf';
try {
$snappy = new Pdf($directory);
header('Content-Type: application/pdf');
header('Content-Disposition: attachment; filename="file.pdf"');
echo $snappy->getOutput($url);
} catch( Exception $e) {
return $e->getMessage();
}
}
The content-disposition and content-type headers seem to match what the documentation shows to use. But nothing is being downloaded.
Is there something I'm doing wrong / anything I can try debugging? I've been trying to figure this out for hours but no luck.
I'd appreciate any help I can get!
Hello,
I think the issue is more related to your Javascript code than to your php one.
What happens if you directly navigate to /wp-json/h5bs/v1/generate-pdf-server-side
from your browser? Does the pdf gets downloaded?
BTW this is not a Snappy issue but it's more related to your implementation IMHO.
This issue has been automatically marked as stale because it has not had recent activity. It will be closed if no further activity occurs. Thank you for your contributions.