PDFs with PHP part 1 - Closing the Document (Page 7 of 10 )
The closing function is a bit more involved: we need to clean up a bit, set some PDF tags, and create a few references. This is the code that does most of the work in setting up the buffered content to finally look like a PDF file.
Begin by checking that there is at least one page, and setting the state to “page closed”.
function close
()
{
if ($this->_page == 0) { // If not yet initialised, add
$this->addPage(); // one page to make this a valid
} // PDF.
$this->_state = 1; // Set the state page closed.
Now output the couple of objects that we have been buffering separately: pages and other resources. We shall go through each method later.
/* Pages and resources. */
$this->_putPages();
$this->_putResources();
Include some document information. PDF treats this information as a separate object, and here we introduce the _newobj() function. You could add other information to this section, such as author, subject, title, keywords, etc. For now we'll just put in the producer.
/* Print some document info. */
$this->_newobj();
$this->_out('<<');
$this->_out('/Producer (My First PDF Class)');
$this->_out(sprintf('/CreationDate (D:%s)',
date('YmdHis')));
$this->_out('>>');
$this->_out('endobj');
The next section is the PDF catalog, which defines how the document will initially look in the reader. You can take this as it is for now. There’s nothing exciting going on here, but it is needed.
/* Print catalog. */
$this->_newobj();
$this->_out('<<');
$this->_out('/Type /Catalog');
$this->_out('/Pages 1 0 R');
$this->_out('/OpenAction [3 0 R /FitH null]');
$this->_out('/PageLayout /OneColumn');
$this->_out('>>');
$this->_out('endobj');
The cross reference section is very important. It brings into use the $_offset array that has appeared before. PDF stores a byte offset reference to all objects in the document. This allows the PDF reader to read objects in a random access way, without having to load the entire document.
/* Print cross reference. */
$start_xref = strlen($this->_buffer); // Get the xref offset.
$this->_out('xref'); // Announce the xref.
$this->_out('0 ' . ($this->_n + 1)); // Number of objects.
$this->_out('0000000000 65535 f ');
/* Loop through all objects and output their offset. */
for ($i = 1; $i <= $this->_n; $i++) {
$this->_out(sprintf('%010d 00000 n ', $this->_offsets[$i]));
}
Each object is printed on a separate line. The offset for each object is printed as a 10 digit integer, followed by a generation number, and an in-use/free indicator. You need not worry about either the generation number or the in-use/free indicator, since those will only be used if editing PDF files and deleting objects. Since we shall be generating from scratch, the generation number will always be 00000 and the in use indicator will be set to 'n'.
Next: The Trailer >>
More Zend Articles
More By Zend