<?php
$pdf=pdf_new();
pdf_open_file($pdf, "test.pdf");
pdf_begin_page($pdf, 595, 842);
$arial = pdf_findfont($pdf, "Arial", "host", 1);
pdf_setfont($pdf, $arial, 10);
pdf_show_xy($pdf, "There are more things in heaven and earth, Horatio,",50, 750);
pdf_end_page($pdf);
pdf_show_xy($pdf, "than are dreamt of in your philosophy", 50,730);
pdf_close($pdf);
?>
错误是:
Fatal error: Uncaught exception 'PDFlibException' with message 'Function must not be called in 'object' scope' in /var/www/Sample/sam.php:4 Stack trace: #0 /var/www/Sample/sam.php(4): pdf_begin_page(Resource id #2, 595, 842) #1 {main} thrown in /var/www/Sample/sam.php on line 4
答案 0 :(得分:0)
问题是pdf_open_file()返回一个忽略/未选中的错误。
当您尝试执行pdf_begin_page()时,虽然没有有效的打开文件,但PDFlib会抛出异常。
这里是PDFlib手册中的解释:
PDFlib应用程序必须遵守易于理解的某些结构规则。例如,您显然在结束文档之前就开始了。 PDFlib使用严格的作用域系统强制正确排序函数调用。范围定义可以在PDFlib手册中找到(表1.3)。所有API函数描述都指定了每个函数的允许范围。调用允许范围之外的函数会导致异常。您可以使用PDF_get_option()的范围keward查询当前范围。
此外,建议使用PDFlib提供的当前示例作为起点,在那里您可以看到当前使用的API以及正确的错误处理。
完整的PHP示例如下所示:
<?php
/* $Id: hello.php,v 1.20 2013/01/24 16:58:59 rp Exp $
*
* PDFlib client: hello example in PHP
*/
try {
$p = new PDFlib();
# This means we must check return values of load_font() etc.
$p->set_option("errorpolicy=return");
/* all strings are expected as utf8 */
$p->set_option("stringformat=utf8");
/* open new PDF file; insert a file name to create the PDF on disk */
if ($p->begin_document("", "") == 0) {
die("Error: " . $p->get_errmsg());
}
$p->set_info("Creator", "hello.php");
$p->set_info("Author", "Rainer Schaaf");
$p->set_info("Title", "Hello world (PHP)!");
$p->begin_page_ext(595, 842, "");
$font = $p->load_font("Helvetica-Bold", "unicode", "");
if ($font == 0) {
die("Error: " . $p->get_errmsg());
}
$p->setfont($font, 24.0);
$p->set_text_pos(50, 700);
$p->show("Hello world!");
$p->continue_text("(says PHP)");
$p->end_page_ext("");
$p->end_document("");
$buf = $p->get_buffer();
$len = strlen($buf);
header("Content-type: application/pdf");
header("Content-Length: $len");
header("Content-Disposition: inline; filename=hello.pdf");
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);
}
$p = 0;
?>