FPDF и ТВ / Фильм Форматирование сценария - PullRequest
3 голосов
/ 12 декабря 2011

Я хотел бы создать сценарий PHP, который форматирует XML в сценарий ТВ / кино, это оказалось несколько сложнее, чем предполагалось. Я создал некоторый код, однако есть определенные места, где я застреваю.

Небольшой фон

В сценарии присутствуют несколько тегов, таких как символ, диалог, заголовок сцены, переход и т. Д. Они имеют разную ширину и левые и правые поля, определяющие положение на странице.

Есть две основные области, которые вызывают озабоченность, то есть я не могу понять:

  • Родительские / дочерние XML-теги, которые нельзя разделить.
  • Если дочерний тег длинный и должен переходить на другую страницу, необходимо создать последующий тег, чтобы показать, что он все еще является родительским. Например, если отображается символьный тег и рассчитывается диалоговое окно для этого тега, дочернего элемента (по ширине, длине символа и высоте строки), чтобы перейти на следующую страницу, тогда родительский символ «символ» должен быть снова показан в начало следующей страницы.
    • К таким родительским / сиротским тегам относятся:
    • "sceneheadng" -> Любой тег.
    • "символ" -> диалоговое окно или скобка
    • "в скобках" -> диалоговое окно

В идеале, однако, родительские / дочерние теги должны храниться в таком месте, чтобы можно было добавить больше без большого количества кода.

Вот что у меня получилось после многих настроек и попыток FPDF:

// Parse the XML string which has been requested from the database.
$xml                        = new SimpleXmlIterator($file, null);
$namespaces                 = $xml->getNamespaces(true);
/*
 * An external function which converts the XML into an ORDERED array.
 * This returns all the attributes of the xml and the following:
 *  "@type"     Refers to the type, i.e. character/dialog etc,
 *  "@content"  What was actually within the tags of the XML.
 */
$source                     = $parseXML($xml, $namespaces);
$saved                      = array ();
// For every line of the XML.
foreach ($source as $index => $line) {
    /*
     * We are going to save the current line of the XML so that we
     * can check the size of the saved cells against the size of the 
     * page. If there is not enough space for specific tags which are
     * required such as character and dialog, then we create a new page.
     * 
     */
    $saved[]                = $line;
    $forward                = false;
    /*
     * Here is where I get somewhat confused - I have attempted to create
     * a mechanism that determines the "@types" which are needed as parents
     * and children of one another. 
     *
     * The $forward variable refers to the possibilty of writing the tag to
     * the PDF. If the parent/orphan is possible or there are non, then it
     * should be able to write.
     */
    if ($forward) {
        $width              = 0;
        foreach ($saved as $index => $value) {
            /*
             * Everything is measured in inches, therefore, I have created a 
             * point() function which turns inches into mm so that FPDF understands
             * everything.
             * 
             * The $format variable is an array which has margins, either top,
             * left or right. We use this to position the Cell of a specific @type
             * so that it appears in the correct format for a TV/Film script.
             *
             * The width variable is deduced via finding the full width of the page,
             * then subtracting the subsequent left and right margin of the said
             * @type.
             */     
            $width          = (point ($setting["width"])
                            - (point ($format[$value["@type"]]["margin-left"])
                            +  point ($format[$value["@type"]]["margin-right"])));
            /*
             * The $pdf variable is that of the FPDF Class.
             */
            $pdf->SetLeftMargin (point($format[$value["@type"]]["margin-left"]));
            $pdf->SetRightMargin (point($format[$value["@type"]]["margin-right"]));
            // Formatting purposes.
            $pdf->Ln (0);   
            $pdf->MultiCell (
                $width,
                point ($setting["line-height"]), //Line height? Still needs fixing.
                $value["@content"], // Physical text
                1); // A temporary border to see what's going on.
        }
        // Reset the $saved, after no more parent/children?
        $saved              = array ();
    }
}

Кроме того, я написал функцию, которая вычисляет высоту комбинированных «$ сохраненных» строк:

function calculate_page_breaks ($saved_lines, $act_upon = true) {
    $num_lines          = 0;
    foreach ($saved_lines as $value) {
        $column_width   = (point ($setting["width"])
                        - (point ($format[$type][$value["@type"]]["margin-left"])
                        +  point ($format[$type][$value["@type"]]["margin-right"])));
        $num_lines      += ceil($pdf->GetStringWidth($value["@content"]) / ($column_width - 1));
    }
    $cell_height        = 5 + 1; // have cells at a height of five so set to six for a padding
    $height_of_cell     = ceil($num_lines * $cell_height); 
    $space_left         = point($setting["height"]) - $pdf->GetY();
    $space_left         -= point($format[$type]["margin-bottom"]);
    // test if height of cell is greater than space left
    if ($height_of_cell >= $space_left) {
        // If this is not just a check, then we can physically "break" the page.
        if ($act_upon) {
            $pdf->Ln ();                        
            $pdf->AddPage (); // page break
            $pdf->SetTopMargin ($point($format[$type]["margin-top"]));
            $pdf->SetLeftMargin ($point($format[$type]["margin-left"]));
            $pdf->SetRightMargin ($point($format[$type]["margin-right"]));
            $pdf->MultiCell (100,5,'','B',2); // this creates a blank row for formatting reasons
        }
        return false;
    } else {
        return true;
    }
}

Редактировать

Я обнаружил, что LaTeX предлагает класс Screenplay (http://www.tug.org/texlive/Contents/live/texmf-dist/doc/latex/screenplay/screenplay.pdf),, однако я искал повсюду, чтобы найти инструмент на основе PHP для конвертации LaTeX в PDF, но безуспешно. Я понимаю, что LaTeX работает на на стороне сервера, однако мне все еще требуется командный процесс на основе PHP для генерации указанных файлов PDF с использованием LaTeX.

Кроме того, установка двоичных файлов, библиотек или инструментов на сервер запрещена. В моем распоряжении инструмент PHP и встроенные в него функциональные возможности. Любой инструмент класса или PHP, который может конвертировать LaTex в PDF, невероятно полезен.

1 Ответ

0 голосов
/ 03 января 2012

Учитывая ваши требования, я бы порекомендовал использовать онлайн веб-сервисы , чтобы отправить ваш файл LateX и получить взамен скомпилированный PDF.

Это означает, что вы получите полный PDF-файл без какой-либо компиляции, без установки, просто на основе PHP веб-сервисов и API.

Существует несколько онлайн-решений, некоторые из которых бесплатны, поэтому, пожалуйста, выберите подходящее: Компиляция документов онлайн

Удачи!

...