<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Simple_pdf
{
	private $lines = array();

	public function add_line($text = '')
	{
		$this->lines[] = (string) $text;
	}

	public function output($filename = 'document.pdf')
	{
		$max_lines = 46;
		$lines = array_slice($this->lines, 0, $max_lines);

		$content = "BT\n/F1 11 Tf\n14 TL\n50 790 Td\n";
		$first = TRUE;
		foreach ($lines as $line)
		{
			$safe = $this->pdf_escape($line);
			if ($first)
			{
				$content .= "(" . $safe . ") Tj\n";
				$first = FALSE;
			}
			else
			{
				$content .= "T*\n(" . $safe . ") Tj\n";
			}
		}
		$content .= "ET";

		$objects = array();
		$objects[] = "1 0 obj\n<< /Type /Catalog /Pages 2 0 R >>\nendobj\n";
		$objects[] = "2 0 obj\n<< /Type /Pages /Kids [3 0 R] /Count 1 >>\nendobj\n";
		$objects[] = "3 0 obj\n<< /Type /Page /Parent 2 0 R /MediaBox [0 0 595 842] /Contents 4 0 R /Resources << /Font << /F1 5 0 R >> >> >>\nendobj\n";
		$objects[] = "4 0 obj\n<< /Length " . strlen($content) . " >>\nstream\n" . $content . "\nendstream\nendobj\n";
		$objects[] = "5 0 obj\n<< /Type /Font /Subtype /Type1 /BaseFont /Helvetica >>\nendobj\n";

		$pdf = "%PDF-1.4\n";
		$offsets = array(0);

		foreach ($objects as $obj)
		{
			$offsets[] = strlen($pdf);
			$pdf .= $obj;
		}

		$xref_pos = strlen($pdf);
		$pdf .= "xref\n0 " . (count($objects) + 1) . "\n";
		$pdf .= "0000000000 65535 f \n";
		for ($i = 1; $i <= count($objects); $i++)
		{
			$pdf .= sprintf('%010d 00000 n ', $offsets[$i]) . "\n";
		}
		$pdf .= "trailer\n<< /Size " . (count($objects) + 1) . " /Root 1 0 R >>\n";
		$pdf .= "startxref\n" . $xref_pos . "\n%%EOF";

		header('Content-Type: application/pdf');
		header('Content-Disposition: attachment; filename="' . $filename . '"');
		header('Content-Length: ' . strlen($pdf));
		echo $pdf;
		exit;
	}

	private function pdf_escape($text)
	{
		$text = str_replace("\\", "\\\\", $text);
		$text = str_replace("(", "\\(", $text);
		$text = str_replace(")", "\\)", $text);
		$text = preg_replace('/[^\x20-\x7E]/', '?', $text);
		return $text;
	}
}
