<?php
	//https://wkhtmltopdf.org/usage/wkhtmltopdf.txt

	class PdfPrinter {

		private $binPath;
		private $config;

		function __construct() {
			global $config;

			$this->config = $config;

			$this->binPath = $this->config['settings']['wkhtmltopdf-bin-path'];
		}

		//https://gist.github.com/davejamesmiller/1965886
		function convertHtmlToPdf($html='', $headerURL=null, $footerURL=null) {

			$descriptorspec = array(
		        0 => array('pipe', 'r'), // stdin
		        1 => array('pipe', 'w'), // stdout
		        2 => array('pipe', 'w'), // stderr
		    );

		    $httpUser = $this->config['settings']['http-username'];
		    $httpPass = $this->config['settings']['http-password'];

		    $process = proc_open($this->binPath.' -q -B 2cm -T 2cm --username '.$httpUser.' --password '.$httpPass.' --header-html "'.$headerURL.'" --footer-html "'.$footerURL.'" - -', $descriptorspec, $pipes);
		    // Send the HTML on stdin
		    fwrite($pipes[0], $html);
		    fclose($pipes[0]);
		    // Read the outputs
		    $pdf = stream_get_contents($pipes[1]);
		    $errors = stream_get_contents($pipes[2]);

		    // Close the process
		    fclose($pipes[1]);

		    $return_value = proc_close($process);

		    // Output the results
		    if ($errors) {
		        file_put_contents(PUBLIC_HTML.'pdf_errors.log', $errors);
		        //return false;
		    }

		    return $pdf;
		}
	}
