Вывод Zend PDF wysiwyg редактора

В настоящее время я создаю редактор PDF. У меня проблема с реализацией обработки тегов.

Я хочу разрешить следующие теги: [h1],[h2],[h3],[h4],[h4],[h5],[h6],[strong]

Я создал класс с помощью метода drawText (код ниже).

Тег [h1] изменит размер и вес шрифта. Как вы можете видеть в коде, я вывожу строки текста. Пример текстовой строки: Это ваш [strong]посадочный талон[/strong]. Пожалуйста, сохраните этот PDF-файл на своем смартфоне или планшете и [strong]покажите его у выхода на посадку[/strong].

Я хотел бы сделать текст между [сильным] полужирным шрифтом. Чтобы сделать это с помощью Zend_PDF, мне нужно выделить файл TTF жирным шрифтом, а затем найти текущую координату X и вызвать $this->pdf()->drawText(текст, координата X, координата Y, кодировка). Я часами думал и пытался написать код, который делает это возможным (пробовал использовать взорваться, preg_match_all и т. д.), но я не могу заставить его работать...

Я считаю, что я не единственный с этой проблемой, и я надеюсь, что кто-то думал об этом и может немного помочь, рассказав, как он или она это сделал...

Надеюсь услышать от кого-нибудь и заранее спасибо!

/**
 * drawSplittedText()
 * 
 * @param array $text
 * @return object Application_Plugin_PdfPlugin
 */
public function drawSplittedText(Array $text)
{
    // Count the number of rows.
    $textRowCount = count($text);

    $i = 0;        

    foreach ($text as $row)
    {           
        // Replace tabs, because they're not outputted properly.
        $row = str_replace("\t", '    ', $row);

        // If the character encoding of the currrent row not is UTF-8, convert the row characters to UTF-8.
        if (($rowEncoding = mb_detect_encoding($row)) != 'UTF-8') {
            $row = iconv($rowEncoding, 'UTF-8', $row);
        }

        // Output row on PDF
        $this->pdf()->drawText($row, $this->_defaultMarginleft, $this->currentY, 'UTF-8');

        $this->newLine();

        ++$i;               
    }

    return $this;
}

person ivodvb    schedule 16.12.2012    source источник


Ответы (1)


Приведенный выше код, вероятно, является тем, с чего большинство людей начинают рендеринг текста с помощью Zend_Pdf, но, к сожалению, вам придется разработать что-то более сложное для достижения ваших целей.

Во-первых, вам нужно будет отслеживать текущее местоположение x и y, а также текущий тип и размер шрифта.

Затем вам понадобится вспомогательная функция/метод, чтобы вычислить, сколько места потребуется фрагменту текста при отображении с текущим шрифтом и размером.

Затем я бы предложил разбить ваш код рендеринга следующим образом:

function writeParagraph( $text )
{
    // Looks for the next tag and sends all text before that tag to the
    // writeText() function. When it gets to a tag it changes the current
    // font/size accordingly, then continues sending text until it runs out
    // of text or reaches another tag. If you need to deal with nested tags
    // then this function may have to call itself recursively.
}

function writeText( $text )
{
    // The first thing this function needs to do is call getStringWidth() to
    // determine the width of the text that it is being asked to render and if
    // the line is too long, shorten it. In practice, a better approach is to
    // split the words into an array based on the space between each word and
    // then use a while() loop to start building the string to be rendered
    // (start with first word, then add second word, then add third word, etc),
    // in each iteration testing the length of the current string concatenated
    // with the next word to see if the resulting string will still fit. If you
    // end up with a situation where adding the next word to the current string
    // will result in a string that is too long, render the current string and
    // a line feed then start the process again, using the next word as the first
    // word in the new string. You will probably want to write a bonus line feed
    // at the end as well (unless, of course, you just wrote one!).
}

function getStringWidth( $str )
{
    // This needs to return the width of $str
}

У меня есть пример класса (https://github.com/jamesggordon/Wrap_Pdf), который реализует функции/методы writeText() и getStringWidth(), а также включает в себя все остальные вещи, такие как текущее местоположение, текущий стиль и т. д. Если вы не можете выясните код для функции writeParagraph(), дайте мне знать, и я включу его в Wrap_Pdf.

person JamesG    schedule 18.12.2012