openlabs / docker-wkhtmltopdf-aas

wkhtmltopdf in a docker container as a web service.
BSD 3-Clause "New" or "Revised" License
99 stars 94 forks source link

PHP example #18

Open michcald opened 8 years ago

michcald commented 8 years ago

Thought it might be useful for someone to see a PHP example.

class PdfGenerator {

private $serviceUrl;

private $servicePort;

// ...

private function getHtml()
{
  // ... generates the HTML to convert to PDF
}

private function generatePdf()
{
        $data = array(
            'contents' => base64_encode($this->getHtml($loan)),
            'options' => array(
               // ...
            ),
        );
        $dataString = json_encode($data);
        $headers = array(
            'Content-Type: application/json',
            'Content-Length: ' . strlen($dataString),
        );

        $ch = curl_init();

        curl_setopt($ch, CURLOPT_URL, $this->serviceUrl);
        curl_setopt($ch, CURLOPT_PORT, $this->servicePort);
        curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
        curl_setopt($ch, CURLOPT_POSTFIELDS, $dataString);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);

        $result = curl_exec($ch);
        curl_close($ch);

        return $result;
}
}
nazar-pc commented 7 years ago

There is much easier way to do it without curl:

$context = stream_context_create(
    [
        'http' => [
            'method'  => 'POST',
            'header'  => 'Content-Type: application/json',
            'content' => json_encode(
                [
                    'contents' => base64_encode('<h1>html content here</h1>')
                ]
            )
        ]
    ]
);
$pdf     = file_get_contents("http://127.0.0.1:1234", null, $context);
cve commented 6 years ago

pdf is created, but images does not display

vicluber commented 4 years ago

I adition to nazar-pc comment, you can send wkhtmltopdf options like this.

$context = stream_context_create( [ 'http' => [ 'method' => 'POST', 'header' => 'Content-Type: application/json', 'content' => json_encode( [ 'contents' => base64_encode($htmlStringView), 'options' => [ 'page-size' => 'A4', 'footer-right' => '[page]', 'margin-bottom' => '20', 'margin-top' => '20', 'footer-font-size' => '8' ] ] ) ] ] ); $pdf = file_get_contents("http://laradock_wkhtmltopdf_1/", null, $context);