Created
July 22, 2019 05:38
-
-
Save peaceman/70118cc0db52cf2f124d037d69c04da2 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function determineFittingFontScale( | |
$pdfLib, | |
int $textFlow, | |
array $fitTextFlowOptions, | |
array $maxDims | |
): float { | |
$fontScale = 1.0; | |
while ($fontScale >= 0.3) { | |
$pdfLib->fit_textflow( | |
$textFlow, | |
0, 0, | |
$maxDims['width'], $maxDims['height'], | |
implode(' ', array_merge( | |
$fitTextFlowOptions, | |
[ | |
"fontscale=$fontScale", | |
'blind', | |
'rewind=1', | |
] | |
)) | |
); | |
$textWidth = $pdfLib->info_textflow($textFlow, 'textwidth'); | |
$textHeight = $pdfLib->info_textflow($textFlow, 'textheight'); | |
if ($maxDims['width'] >= $textWidth && $maxDims['height'] >= $textHeight) | |
return $fontScale; | |
$fontScale *= 0.99; | |
} | |
return max(0.3, $fontScale); | |
} | |
$p = new PDFlib(); | |
$p->set_option("stringformat=utf8"); | |
$p->begin_document("", ""); | |
/* Create an A4 Landscape page */ | |
$p->begin_page_ext(0, 0, "width=a4.height height=a4.width"); | |
$createTextFlowOptList = [ | |
'hyphenchar=none', | |
'fontname=Helvetica', | |
'encoding=unicode', | |
'fontsize=32', | |
'leftindent=0', | |
'adjustmethod=nofit', | |
'charclass={letter .}', | |
]; | |
$fitTextFlowOpts = ['fitmethod=auto', 'showborder']; | |
$boxDims = ['width' => 200, 'height' => 100]; | |
$boxPos = ['llx' => 10, 'lly' => 200]; | |
$lines = [ | |
'bar@example.com', | |
'second line', | |
'third line', | |
'fourth line', | |
]; | |
$textFlow = $p->create_textflow(implode(PHP_EOL, $lines), implode(' ', $createTextFlowOptList)); | |
$fontScale = determineFittingFontScale($p, $textFlow, $fitTextFlowOpts, $boxDims); | |
$res = $p->fit_textflow( | |
$textFlow, | |
$boxPos['llx'], $boxPos['lly'], | |
$boxPos['llx'] + $boxDims['width'], | |
$boxPos['lly'] + $boxDims['height'], | |
implode(' ', array_merge($fitTextFlowOpts, ["fontscale=$fontScale", 'rewind=1'])) | |
); | |
$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=fitmethod-auto.pdf"); | |
print $buf; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment