加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

为什么此代码使用PHP Zend_Pdf库无法正常处理PDF上的文本?

发布时间:2020-12-13 16:02:48 所属栏目:PHP教程 来源:网络整理
导读:我正在尝试在服务器上动态创建PDF文档,并使用Zend_Pdf库将它们发送到客户端. PDF上的所有文本都需要与页面居中对齐,页面将是字母大小的横向.使用我在不同网站上多次发现的功能,我遇到了问题 – 中心理由是关闭的.所有文字都显得太偏左了.这是我的代码: ?req
我正在尝试在服务器上动态创建PDF文档,并使用Zend_Pdf库将它们发送到客户端. PDF上的所有文本都需要与页面居中对齐,页面将是字母大小的横向.使用我在不同网站上多次发现的功能,我遇到了问题 – 中心理由是关闭的.所有文字都显得太偏左了.这是我的代码:
<?
require('Zend/Pdf.php');

$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$pdf = new Zend_Pdf();

// Create a new page,add to page listing
$pdfPage = $pdf->newPage(Zend_Pdf_Page::SIZE_LETTER_LANDSCAPE);
$pdf->pages[] = $pdfPage;

// Add certify that
$pdfPage->setFont($font,15.75);
drawCenteredText($pdfPage,"THIS IS TO CERTIFY THAT",378);

// Add name
$pdfPage->setFont($font,39.75);
drawCenteredText($pdfPage,"Example Name",314.25);

// Headers
header("Content-type: application/pdf");
header("Content-Disposition: inline; filename="cert.pdf"");
header('Content-Transfer-Encoding: binary');
header('Accept-Ranges: bytes');

// Output PDF
echo $pdf->render();


function drawCenteredText($page,$text,$bottom) {  
    $text_width = getTextWidth($text,$page->getFont(),$page->getFontSize());
    $box_width = $page->getWidth();
    $left = ($box_width - $text_width) / 2;

    $page->drawText($text,$left,$bottom,'UTF-8');
}

function getTextWidth($text,$font,$font_size) {
    $drawing_text = iconv('','UTF-8',$text);
    $characters    = array();
    for ($i = 0; $i < strlen($drawing_text); $i++) {
        $characters[] = (ord($drawing_text[$i++]) << 8) | ord ($drawing_text[$i]);
    }
    $glyphs        = $font->glyphNumbersForCharacters($characters);
    $widths        = $font->widthsForGlyphs($glyphs);
    $text_width   = (array_sum($widths) / $font->getUnitsPerEm()) * $font_size;
    return $text_width;
}

?>

……这就是结果.

如果其他人遇到类似的问题,问题在这里:
function getTextWidth($text,$text);
    $characters    = array();
    for ($i = 0; $i < strlen($drawing_text); $i++) {
        $characters[] = (ord($drawing_text[$i++]) << 8) | ord ($drawing_text[$i]);
    }
    $glyphs        = $font->glyphNumbersForCharacters($characters);
    $widths        = $font->widthsForGlyphs($glyphs);
    $text_width   = (array_sum($widths) / $font->getUnitsPerEm()) * $font_size;
    return $text_width;
}

构建字符数组时,字符加载错误 – 8位,而不是16位.

$characters[] = ord ($drawing_text[$i]);

这解决了问题,并正确计算文本宽度.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读