I am trying to dynamically create PDF documents on the server and send them to the client using the Zend_Pdf library. All text in PDF format should be centered on the page, which will have the size of the letters, landscape. Using the functions that I found several times on different sites, I had a problem - the excuse of the center is disabled. All text appears too far to the left. Here is my code:
<? 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; } ?>
... and this is the result.
source share