首页 > 解决方案 > PDFLib (PHP) 无法放置表格:计算的表格高度太大

问题描述

我得到这个例外:

无法放置表格:计算的表格高度 657.375 太大(> 492,缩小 74.8432%)

内容是动态的,有时它似乎超出了表格的容量,但我不确定,有什么想法吗?

PDFLibary 9.2.0 版本/PHP 7.2.13 MSVC15 版本

引发异常的代码部分:

$result = $p->fit_table($tbl, $llx, $lly, $urx, $y, $fit_opts);

                    
                    if ($result == "_error")
                        throw new Exception("Couldn't place table : " .
                            $p->get_errmsg());

完整代码如下:

<?php
$outfile = "";
$title = "Table Invoice";


$infile = "stationery.pdf";

$tf = 0;
$tbl = 0;

$sum = 0;
$total = 0;
$subtotal = 0;
$tabheight = 0;

$pagewidth = 792;
$pageheight = 612;
$fontsize = 12;
$capheight = 7;
$rowheight = 16;
$margin = 4;
$leading = "120%";
$ystart = $pageheight - 40;
$yoffset = 15;
$ycontinued = 40;
$nfooters = 1;
$nheaders = 1;

/* The table coordinates are fixed; only the height of the table may differ*/
$llx = 25;
$urx = 770;
$lly = 80;

/* The widths of the individual columns is fixed */
$maxcol = 5;

$c1 = 20;
$c2 = 300;
$c3 = 30;
$c4 = 30;
$c5 = 30;
$c6 = 30;
$c7 = 30;
$c8 = 30;
$c9 = 30;
$c10 = 30;
$c11 = 30;


/* Get the current date */
setlocale(LC_TIME, "C");
date_default_timezone_set("Europe/Berlin");
$fulldate = date("F j, Y");

/* Text to output after the table */
$closingtext =
    "Terms of payment: 30 days net. " .
    "90 days warranty starting at the day of sale. " .
    "This warranty covers defects in workmanship only. " .
    "Kraxi Systems, Inc. will, at its option, repair or replace the " .
    "product under the warranty. This warranty is not transferable. " .
    "No returns or exchanges will be accepted for wet products.";

//Executing query for table rows
    
    if (!$rst) {
        print "Error " . $conn->ErrorMsg();
        exit;
    } else {

        if ($rst->RecordCount() > 0) {

            $address = array(
                "John Q. Doe", "255 Customer Lane", "Suite B",
                "12345 User Town", "Everland"
            );

            try {
                $searchpath = $PDFSOURCEPATH;
                $p = new PDFlib();

                $p->set_option("errorpolicy=return");
                $p->set_option("textformat=bytes");
                $p->set_option("SearchPath={{" . $searchpath . "}}");

                if ($p->begin_document("", "") == -1) {
                    die("Error: " . $p->get_errmsg());
                }

                $boldfont = $p->load_font("Helvetica-Bold", "unicode", "");
                if ($boldfont == 0)
                    throw new Exception("Error: " . $p->get_errmsg());

                $regularfont = $p->load_font("Helvetica", "unicode", "");
                if ($regularfont == 0)
                    throw new Exception("Error: " . $p->get_errmsg());

                /* Start the output page */
                $p->begin_page_ext($pagewidth, $pageheight, "");

                /* Output the customer's address */
                $y = $ystart;

                $p->setfont($regularfont, $fontsize);

                for ($i = 0; $i < count($address); $i++) {
                    $p->fit_textline($address[$i], $llx, $y, "");
                    $y -= $yoffset;
                }

                /* Print the header and the date */
                $y -= 3 * $yoffset;

                $p->setfont($boldfont, $fontsize);

                $p->fit_textline("INVOICE", $llx, $y, "position {left top}");
                $p->fit_textline($fulldate, $urx, $y, "position {right top}");

                $y -= 3 * $yoffset;

                $head_opts_right = "fittextline={position={right top} " .
                    " font=" . $boldfont . " fontsize={capheight=" . $capheight . "}} " .
                    " rowheight=" . $rowheight . " margin=" . $margin;

                $head_opts_left = "fittextline={position={left top} " .
                    " font=" . $boldfont . " fontsize={capheight=" . $capheight . "}} " .
                    " rowheight=" . $rowheight . " margin=" . $margin;

                $col = 1;
                $row = 1;

                /* Add each heading cell with the option list defined above; 
                * in addition, supply a fixed column width
                */
                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 1",
                    $head_opts_right . " colwidth=" . $c1
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 2",
                    $head_opts_left . " colwidth=" . $c2
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 3",
                    $head_opts_left . " colwidth=" . $c3
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 4",
                    $head_opts_right . " colwidth=" . $c4
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 5",
                    $head_opts_right . " colwidth=" . $c5
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 6",
                    $head_opts_right . " colwidth=" . $c6
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 7",
                    $head_opts_right . " colwidth=" . $c7
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 8",
                    $head_opts_right . " colwidth=" . $c8
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 9",
                    $head_opts_right . " colwidth=" . $c9
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 10",
                    $head_opts_right . " colwidth=" . $c10
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $tbl = $p->add_table_cell(
                    $tbl,
                    $col++,
                    $row,
                    "Col 11",
                    $head_opts_right . " colwidth=" . $c11
                );
                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $row++;

                $body_opts = "fittextline={position={right top} " .
                    " font=" . $regularfont .
                    " fontsize={capheight=" . $capheight . "}} " .
                    " rowheight=" . $rowheight . " margin=" . $margin;

                $itemno = 1;
                $masterRows = array();

                while (!$rst->EOF) {

                    $col = 1;
                    $masterRows[] = $row;

                    /* ---------------------------------------------------------------
                    * Add the text line cell containing the Item in the first column,
                    * with the options defined for table body cells above
                    * ---------------------------------------------------------------
                    */
                    $tbl = $p->add_table_cell($tbl, $col++, $row, $rst->fields["col1"], $body_opts);
                    if ($tbl == 0)
                        throw new Exception("Error adding cell: " . $p->get_errmsg());

                    $tf_opts = "font=" . $regularfont .
                        " fontsize={capheight=" . $capheight . "} leading=" . $leading;

                    $bodytf_opts = "fittextflow={firstlinedist=capheight}" .
                        " colwidth=" . $c2 . " margin=" . $margin;

                    /* Add the Textflow with the options defined above */
                    $tf = $p->add_textflow(0, $rst->fields["customername"], $tf_opts);

                    if ($tf == 0)
                        throw new Exception("Error: " . $p->get_errmsg());

                    /* Add the Textflow table cell with the options defined above */
                    $tbl = $p->add_table_cell(
                        $tbl,
                        $col++,
                        $row,
                        "",
                        $bodytf_opts . " textflow=" . $tf
                    );

                    if ($tbl == 0)
                        throw new Exception("Error adding cell: " . $p->get_errmsg());

                    $tf = 0;

                    $tbl = $p->add_table_cell(
                        $tbl,
                        $col++,
                        $row,
                        date("m/d/Y", strtotime($rst->fields["col2"])),
                        $body_opts
                    );
                    if ($tbl == 0)
                        throw new Exception("Error adding cell: " . $p->get_errmsg());

                    $tbl = $p->add_table_cell(
                        $tbl,
                        $col++,
                        $row,
                        date("m/d/Y", strtotime($rst->fields["col3"])),
                        $body_opts
                    );
                    if ($tbl == 0)
                        throw new Exception("Error adding cell: " . $p->get_errmsg());

                    if ($result == "_error")
                        throw new Exception("Couldn't place table : " .
                            $p->get_errmsg());

                    /* Calculate the overall sum */
                    $total += $sum;
                    $itemno++;
                    $row++;

                    //Executing query for table rows comments

                    while (!$rstComments->EOF) {
                        $tf_opts = "font=" . $regularfont .
                            " fontsize={capheight=" . $capheight . "} alignment=left leading=" . $leading;

                        $tf = $p->add_textflow(0, $rstComments->fields["comment"], $tf_opts);

                        if ($tf == 0)
                            throw new Exception("Error: " . $p->get_errmsg());

                        $bodytf_opts = "fittextflow={firstlinedist=capheight} colspan=10" .
                            " colwidth= 700 margin=" . $margin;

                        $tbl = $p->add_table_cell(
                            $tbl,
                            2,
                            $row,
                            "",
                            $bodytf_opts . " textflow=" . $tf
                        );

                        if ($tbl == 0)
                            throw new Exception("Error adding cell: " . $p->get_errmsg());

                        $tf = 0;
                        ///////////////End comments///////////////

                        $row++;
                        $rstComments->MoveNext();
                    } /* for */

                    $rst->MoveNext();
                }

                $footer_opts =
                    "rowheight=" . $rowheight . " colspan=2 margin =" . $margin .
                    " matchbox={name=subtotal}";

                $tbl = $p->add_table_cell($tbl, $maxcol - 1, $row, "", $footer_opts . "");

                if ($tbl == 0)
                    throw new Exception("Error adding cell: " . $p->get_errmsg());

                $fill_opts =
                    " fill={";

                foreach ($masterRows as $rowNumber) {
                    $fill_opts .=
                        "{area=row" . $rowNumber . " fillcolor={gray 0.9}} ";
                }

                do {

                    $fit_opts =
                        "header=" . $nheaders . " footer=" . $nfooters .
                        $fill_opts .
                        "{area=header fillcolor={rgb 0.90 0.90 0.98}} " .
                        "{area=footer fillcolor={rgb 0.98 0.92 0.84}}}";

                    /* Place the table instance */
                    $result = $p->fit_table($tbl, $llx, $lly, $urx, $y, $fit_opts);

                    /* An error occurred or the table's fitbox is too small to keep any
                    * contents 
                    */
                    if ($result == "_error")
                        throw new Exception("Couldn't place table : " .
                            $p->get_errmsg());

                    if ($result != "_boxfull") {
                        /* Format the total to a maximum of two fraction digits */
                        $roundedValue = sprintf("%.2f", $total);
                        $contents = "total:   " . $roundedValue;

                        /* Retrieve the coordinates of the third (upper right) corner of
                        * the "subtotal" matchbox. The parameter "1" indicates the 
                        * first instance of the matchbox.
                        */
                        $x3 = 0;
                        $y3 = 0;

                        if ($p->info_matchbox("subtotal", 1, "exists") == 1) {
                            $x3 = $p->info_matchbox("subtotal", 1, "x3");
                            $y3 = $p->info_matchbox("subtotal", 1, "y3");
                        } else {
                            throw new Exception("Error: " . $p->get_errmsg());
                        }

                        /* Start the text line at the corner coordinates retrieved
                        * (x2, y2) with a small margin. Right-align the text.
                        */
                        $p->setfont($boldfont, $fontsize);
                        $p->fit_textline(
                            $contents,
                            $x3 - $margin,
                            $y3 - $margin,
                            "position={right top}"
                        );
                    } else if ($result == "_boxfull") {
                        /* Get the last body row output in the table instance */
                        $lastrow = $p->info_table($tbl, "lastbodyrow");

                        /* Calculate the subtotal */
                        $subtotal = 0;
                        for ($i = 0; $i < $lastrow - $nfooters; $i++) {
                            $subtotal += $items[$i][1] * $items[$i][2];
                        }

                        /* Format the subtotal to a maximum of two fraction digits*/
                        $roundedValue = sprintf("%.2f", $subtotal);

                        $contents = "subtotal:   " . $roundedValue;

                        /* Retrieve the coordinates of the third (upper right) corner of
                        * the "subtotal" matchbox. The parameter "1" indicates the 
                        * first instance of the matchbox.
                        */
                        $x3 = 0;
                        $y3 = 0;

                        if ($p->info_matchbox("subtotal", 1, "exists") == 1) {
                            $x3 = $p->info_matchbox("subtotal", 1, "x3");
                            $y3 = $p->info_matchbox("subtotal", 1, "y3");
                        } else {
                            throw new Exception("Error: " . $p->get_errmsg());
                        }

                        /* Start the text line at the corner coordinates retrieved in
                        * (x3, y3) with a small margin. Right-align the text.
                        */
                        $p->setfont($boldfont, $fontsize);
                        $p->fit_textline(
                            $contents,
                            $x3 - $margin,
                            $y3 - $margin,
                            "position={right top}"
                        );

                        /* Output the "Continued" remark */
                        $p->setfont($regularfont, $fontsize);
                        $p->fit_textline(
                            "-- Continued --",
                            $urx,
                            $ycontinued,
                            "position {right top}"
                        );

                        $p->end_page_ext("");
                        $p->begin_page_ext($pagewidth, $pageheight, "");
                        $y = $ystart;
                    }
                } while ($result == "_boxfull");

                /* Get the table height of the current table instance */
                $tabheight = $p->info_table($tbl, "height");

                $y = $y - (int) $tabheight - $yoffset;

                /* Add the closing Textflow to be placed after the table */
                $tf_opts = "font=" . $regularfont . " fontsize=" . $fontsize .
                    " leading=" . $leading . " alignment=justify";

                $tf = $p->add_textflow(0, $closingtext, $tf_opts);
                if ($tf == 0)
                    throw new Exception("Error: " . $p->get_errmsg());

                /* Loop until all text has been fit which is indicated by the "_stop"
                * return value of fit_textflow()
                */
                do {
                    /* Place the Textflow */
                    $result = $p->fit_textflow($tf, $llx, $lly, $urx, $y, "");

                    if ($result == "_error")
                        throw new Exception("Couldn't place table : " .
                            $p->get_errmsg());

                    if ($result == "_boxfull" || $result == "_boxempty") {
                        $p->setfont($regularfont, $fontsize);
                        $p->fit_textline(
                            "-- Continued --",
                            $urx,
                            $ycontinued,
                            "position {right top}"
                        );

                        $p->end_page_ext("");
                        $p->begin_page_ext($pagewidth, $pageheight, "");
                        $y = $ystart;
                    }
                } while (!$result == "_stop");


                $p->end_page_ext("");
                $p->end_document("");

                $buf = $p->get_buffer();
                $len = strlen($buf);

                if ($email == 1) {
                    $filename = $filename . ".pdf";
                    @unlink($filename);
                    $file = fopen($filename, "w");
                    fputs($file, $buf, $len);
                    fclose($file);
                    PDF_delete($p);
                } else {
                    header("Content-type: application/pdf");
                    header("Content-Length: $len");
                    header("Content-Disposition: inline; filename=$report_filename");
                    print $buf;
                }
            } catch (PDFlibException $e) {
                die("PDFlib exception occurred in hello sample:\n" .
                    "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
                    $e->get_errmsg() . "\n");
            } catch (Exception $e) {
                die($e);
            }
        } else {
            if ($email == 1) {

                try {
                    $p = new PDFlib();
                    if ($p->begin_document("", "") == -1) {
                        die("Error: " . $p->get_errmsg());
                    }
                    $p->begin_page_ext($pagewidth, $pageheight, "");
                    $p->set_text_pos(20, 600);
                    $p->end_page_ext("");
                    $p->end_document("");

                    $buf = $p->get_buffer();
                    $len = strlen($buf);

                    $filename = $filename . ".pdf";
                    @unlink($filename);
                    $file = fopen($filename, "w");
                    fputs($file, $buf, $len);
                    fclose($file);
                } catch (PDFlibException $e) {
                    die("PDFlib exception occurred in hello sample:\n" .
                        "[" . $e->get_errnum() . "] " . $e->get_apiname() . ": " .
                        $e->get_errmsg() . "\n");
                } catch (Exception $e) {
                    die($e);
                }
            } else {
                print "No records matched search criteria";
                exit;
            }
        }
    }
?>

标签: phppdflib

解决方案


推荐阅读