Inline PDF view shows ��� when using Slim as router

We generate PDFs using phpwkhtmltopdf, so PHP wrapper for wkhtmltopdf. The inline view of the generated PDFs works when not using Slim as a router. As soon as Slim hands over the request, I get black diamonds with the question mark.
Allow me to refer to this post that unfortunately seems to be dead but describes the issue well.

Any idea what we can try?

Sure, I had the same issue with TCPDF the other day. You’re probably sending the PDF data inline to the browser without the correct content-type header.

If you do it the Slim way, then you have to return an HTTP response object with the PDF data in its response body. So the following lines do:

  1. Change the default response header “Content-type” to “application/pdf”
  2. Write the PDF output as a string to the response body stream (TCPDF uses the “S” option for this, not sure which option phpwkhtmltopdf has to output as a string)
  3. Return the response as required by Slim
$response = $this->response->withHeader( 'Content-type', 'application/pdf' );
		$response->write( $pdf->Output('My cool PDF', 'S') );
		
		return $response;

Hope this helps.

1 Like

Fantastic, thx a lot, zmip.
For the records, in phpwkhtmltopdf the method is $pdf->toString().
In full:

$app->get('/contract/preview', function ($request, $response, $args) {
    $response = $this->response->withHeader( 'Content-type', 'application/pdf' );
    include ('../../php/contract/pdf.php');
    $content = $pdf->toString();
    $response->write($content);
    return $response;
});