⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 pdf.php

📁 Bug tracker, and reporter.
💻 PHP
📖 第 1 页 / 共 2 页
字号:
                }                $this->pages[] = new Zend_Pdf_Page($child, $this->_objFactory);            }        }    }    /**     * Orginize pages to tha pages tree structure.     *     * @todo atomatically attach page to the document, if it's not done yet.     * @todo check, that page is attached to the current document     *     * @todo Dump pages as a balanced tree instead of a plain set.     */    private function _dumpPages()    {        $pagesContainer = $this->_trailer->Root->Pages;        $pagesContainer->touch();        $pagesContainer->Kids->items->clear();        foreach ($this->pages as $page ) {            $page->render($this->_objFactory);            $pageDictionary = $page->getPageDictionary();            $pageDictionary->touch();            $pageDictionary->Parent = $pagesContainer;            $pagesContainer->Kids->items[] = $pageDictionary;        }        $pagesContainer->Count->touch();        $pagesContainer->Count->value = count($this->pages);    }    /**     * Create page object, attached to the PDF document.     * Method signatures:     *     * 1. Create new page with a specified pagesize.     *    If $factory is null then it will be created and page must be attached to the document to be     *    included into output.     * ---------------------------------------------------------     * new Zend_Pdf_Page(string $pagesize);     * ---------------------------------------------------------     *     * 2. Create new page with a specified pagesize (in default user space units).     *    If $factory is null then it will be created and page must be attached to the document to be     *    included into output.     * ---------------------------------------------------------     * new Zend_Pdf_Page(numeric $width, numeric $height);     * ---------------------------------------------------------     *     * @param mixed $param1     * @param mixed $param2     * @return Zend_Pdf_Page     */    public function newPage($param1, $param2 = null)    {        if ($param2 === null) {            return new Zend_Pdf_Page($param1, $this->_objFactory);        } else {            return new Zend_Pdf_Page($param1, $param2, $this->_objFactory);        }    }    /**     * Return the document-level Metadata     * or null Metadata stream is not presented     *     * @return string     */    public function getMetadata()    {        if ($this->_trailer->Root->Metadata !== null) {            return $this->_trailer->Root->Metadata->value;        } else {            return null;        }    }    /**     * Sets the document-level Metadata (mast be valid XMP document)     *     * @param string $metadata     */    public function setMetadata($metadata)    {        $metadataObject = $this->_objFactory->newStreamObject($metadata);        $metadataObject->dictionary->Type    = new Zend_Pdf_Element_Name('Metadata');        $metadataObject->dictionary->Subtype = new Zend_Pdf_Element_Name('XML');        $this->_trailer->Root->Metadata = $metadataObject;        $this->_trailer->Root->touch();    }    /**     * Return the document-level JavaScript     * or null if there is no JavaScript for this document     *     * @return string     */    public function getJavaScript()    {        return $this->_javaScript;    }    /**     * Return an associative array containing all the named actions in the PDF.     * Named actions (it's always "GoTo" actions) can be used to reference from outside     * the PDF, ex: 'http://www.something.com/mydocument.pdf#MyAction'     *     * @return array     */    public function getNamedActions()    {        return $this->_namedActions;    }    /**
     * Extract fonts attached to the document
     *
     * returns array of Zend_Pdf_Resource_Font_Extracted objects
     * 
     * @return array
     */
    public function extractFonts()
    {
        $fontResourcesUnique = array();
        foreach ($this->pages as $page) {
            $pageResources = $page->extractResources();

            if ($pageResources->Font === null) {
                // Page doesn't contain have any font reference
                continue;
            }
            
            $fontResources = $pageResources->Font;

            foreach ($fontResources->getKeys() as $fontResourceName) {
                $fontDictionary = $fontResources->$fontResourceName;
    
                if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference  ||
                       $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
                    // Font dictionary has to be an indirect object or object reference
                    continue;
                }
    
                $fontResourcesUnique[$fontDictionary->toString($this->_objFactory)] = $fontDictionary;
            }
        }
        
        $fonts = array();
        foreach ($fontResourcesUnique as $resourceReference => $fontDictionary) {
            try {
                // Try to extract font
                $extractedFont = new Zend_Pdf_Resource_Font_Extracted($fontDictionary);

                $fonts[$resourceReference] = $extractedFont; 
            } catch (Zend_Pdf_Exception $e) {
                if ($e->getMessage() != 'Unsupported font type.') {
                    throw $e;
                }
            }
        }
        
        return $fonts;
    } 

    /**
     * Extract font attached to the page by specific font name
     * 
     * $fontName should be specified in UTF-8 encoding
     *
     * @return Zend_Pdf_Resource_Font_Extracted|null
     */
    public function extractFont($fontName)
    {
        $fontResourcesUnique = array();
        foreach ($this->pages as $page) {
            $pageResources = $page->extractResources();
            
            if ($pageResources->Font === null) {
                // Page doesn't contain have any font reference
                continue;
            }
            
            $fontResources = $pageResources->Font;

            foreach ($fontResources->getKeys() as $fontResourceName) {
                $fontDictionary = $fontResources->$fontResourceName;
    
                if (! ($fontDictionary instanceof Zend_Pdf_Element_Reference  ||
                       $fontDictionary instanceof Zend_Pdf_Element_Object) ) {
                    // Font dictionary has to be an indirect object or object reference
                    continue;
                }
                
                $resourceReference = $fontDictionary->toString($this->_objFactory);
                if (isset($fontResourcesUnique[$resourceReference])) {
                    continue;
                } else {
                    // Mark resource as processed
                    $fontResourcesUnique[$resourceReference] = 1;
                }
   
                if ($fontDictionary->BaseFont->value != $fontName) {
                    continue;
                }
                
                try {
                    // Try to extract font
                    return new Zend_Pdf_Resource_Font_Extracted($fontDictionary); 
                } catch (Zend_Pdf_Exception $e) {
                    if ($e->getMessage() != 'Unsupported font type.') {
                        throw $e;
                    }
                    // Continue searhing
                }
            }
        }

        return null;
    } 
        /**     * Render the completed PDF to a string.     * If $newSegmentOnly is true, then only appended part of PDF is returned.     *     * @param boolean $newSegmentOnly     * @param resource $outputStream     * @return string     * @throws Zend_Pdf_Exception     */    public function render($newSegmentOnly = false, $outputStream = null)    {        // Save document properties if necessary        if ($this->properties != $this->_originalProperties) {            $docInfo = $this->_objFactory->newObject(new Zend_Pdf_Element_Dictionary());            foreach ($this->properties as $key => $value) {                switch ($key) {                    case 'Trapped':                        switch ($value) {                            case true:                                $docInfo->$key = new Zend_Pdf_Element_Name('True');                                break;                            case false:                                $docInfo->$key = new Zend_Pdf_Element_Name('False');                                break;                            case null:                                $docInfo->$key = new Zend_Pdf_Element_Name('Unknown');                                break;                            default:                                throw new Zend_Pdf_Exception('Wrong Trapped document property vale: \'' . $value . '\'. Only true, false and null values are allowed.');                                break;                        }                    case 'CreationDate':                        // break intentionally omitted                    case 'ModDate':                        $docInfo->$key = new Zend_Pdf_Element_String((string)$value);                        break;                    case 'Title':                        // break intentionally omitted                    case 'Author':                        // break intentionally omitted                    case 'Subject':                        // break intentionally omitted                    case 'Keywords':                        // break intentionally omitted                    case 'Creator':                        // break intentionally omitted                    case 'Producer':                        // break intentionally omitted                    default:                        $docInfo->$key = new Zend_Pdf_Element_String((string)$value);                        break;                }            }            $this->_trailer->Info = $docInfo;        }        $this->_dumpPages();        // Check, that PDF file was modified        // File is always modified by _dumpPages() now, but future implementations may eliminate this.        if (!$this->_objFactory->isModified()) {            if ($newSegmentOnly) {                // Do nothing, return                return '';            }            if ($outputStream === null) {                return $this->_trailer->getPDFString();            } else {                $pdfData = $this->_trailer->getPDFString();                while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {                    $pdfData = substr($pdfData, $byteCount);                }                return '';            }        }        // offset (from a start of PDF file) of new PDF file segment        $offset = $this->_trailer->getPDFLength();        // Last Object number in a list of free objects        $lastFreeObject = $this->_trailer->getLastFreeObject();        // Array of cross-reference table subsections        $xrefTable = array();        // Object numbers of first objects in each subsection        $xrefSectionStartNums = array();        // Last cross-reference table subsection        $xrefSection = array();        // Dummy initialization of the first element (specail case - header of linked list of free objects).        $xrefSection[] = 0;        $xrefSectionStartNums[] = 0;        // Object number of last processed PDF object.        // Used to manage cross-reference subsections.        // Initialized by zero (specail case - header of linked list of free objects).        $lastObjNum = 0;        if ($outputStream !== null) {            if (!$newSegmentOnly) {                $pdfData = $this->_trailer->getPDFString();                while ( strlen($pdfData) > 0 && ($byteCount = fwrite($outputStream, $pdfData)) != false ) {                    $pdfData = substr($pdfData, $byteCount);                }            }        } else {            $pdfSegmentBlocks = ($newSegmentOnly) ? array() : array($this->_trailer->getPDFString());        }        // Iterate objects to create new reference table        foreach ($this->_objFactory->listModifiedObjects() as $updateInfo) {            $objNum = $updateInfo->getObjNum();            if ($objNum - $lastObjNum != 1) {                // Save cross-reference table subsection and start new one                $xrefTable[] = $xrefSection;                $xrefSection = array();                $xrefSectionStartNums[] = $objNum;            }            if ($updateInfo->isFree()) {                // Free object cross-reference table entry                $xrefSection[]  = sprintf("%010d %05d f \n", $lastFreeObject, $updateInfo->getGenNum());                $lastFreeObject = $objNum;            } else {                // In-use object cross-reference table entry                $xrefSection[]  = sprintf("%010d %05d n \n", $offset, $updateInfo->getGenNum());                $pdfBlock = $updateInfo->getObjectDump();                $offset += strlen($pdfBlock);                if ($outputStream === null) {                    $pdfSegmentBlocks[] = $pdfBlock;                } else {                    while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {                        $pdfBlock = substr($pdfBlock, $byteCount);                    }                }            }            $lastObjNum = $objNum;        }        // Save last cross-reference table subsection        $xrefTable[] = $xrefSection;        // Modify first entry (specail case - header of linked list of free objects).        $xrefTable[0][0] = sprintf("%010d 65535 f \n", $lastFreeObject);        $xrefTableStr = "xref\n";        foreach ($xrefTable as $sectId => $xrefSection) {            $xrefTableStr .= sprintf("%d %d \n", $xrefSectionStartNums[$sectId], count($xrefSection));            foreach ($xrefSection as $xrefTableEntry) {                $xrefTableStr .= $xrefTableEntry;            }        }        $this->_trailer->Size->value = $this->_objFactory->getObjectCount();        $pdfBlock = $xrefTableStr                 .  $this->_trailer->toString()                 . "startxref\n" . $offset . "\n"                 . "%%EOF\n";        if ($outputStream === null) {            $pdfSegmentBlocks[] = $pdfBlock;            return implode('', $pdfSegmentBlocks);        } else {            while ( strlen($pdfBlock) > 0 && ($byteCount = fwrite($outputStream, $pdfBlock)) != false ) {                $pdfBlock = substr($pdfBlock, $byteCount);            }            return '';        }    }    /**     * Set the document-level JavaScript     *     * @param string $javascript     */    public function setJavaScript($javascript)    {        $this->_javaScript = $javascript;    }    /**     * Convert date to PDF format (it's close to ASN.1 (Abstract Syntax Notation     * One) defined in ISO/IEC 8824).     *     * @todo This really isn't the best location for this method. It should     *   probably actually exist as Zend_Pdf_Element_Date or something like that.     *     * @todo Address the following E_STRICT issue:     *   PHP Strict Standards:  date(): It is not safe to rely on the system's     *   timezone settings. Please use the date.timezone setting, the TZ     *   environment variable or the date_default_timezone_set() function. In     *   case you used any of those methods and you are still getting this     *   warning, you most likely misspelled the timezone identifier.     *     * @param integer $timestamp (optional) If omitted, uses the current time.     * @return string     */    public static function pdfDate($timestamp = null)    {        if (is_null($timestamp)) {            $date = date('\D\:YmdHisO');        } else {            $date = date('\D\:YmdHisO', $timestamp);        }        return substr_replace($date, '\'', -2, 0) . '\'';    }}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -