Skip to content

Instantly share code, notes, and snippets.

@sheck
Forked from nrkn/fittedSize.js
Created October 8, 2019 18:29
Show Gist options
  • Save sheck/44952ef329c193e8329b833471e0e480 to your computer and use it in GitHub Desktop.
Save sheck/44952ef329c193e8329b833471e0e480 to your computer and use it in GitHub Desktop.
Get best fontSize to use to fit text in bounds in PDFKit
var Pdf = require( 'pdfkit' );
var fs = require( 'fs' );
var lorem = 'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Etiam in suscipit purus. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Vivamus nec hendrerit felis. Morbi aliquam facilisis risus eu lacinia. Sed eu leo in turpis fringilla hendrerit. Ut nec accumsan nisl. Suspendisse rhoncus nisl posuere tortor tempus et dapibus elit porta. Cras leo neque, elementum a rhoncus ut, vestibulum non nibh. Phasellus pretium justo turpis. Etiam vulputate, odio vitae tincidunt ultricies, eros odio dapibus nisi, ut tincidunt lacus arcu eu elit. Aenean velit erat, vehicula eget lacinia ut, dignissim non tellus. Aliquam nec lacus mi, sed vestibulum nunc. Suspendisse potenti. Curabitur vitae sem turpis. Vestibulum sed neque eget dolor dapibus porttitor at sit amet sem. Fusce a turpis lorem. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae;';
var temp = new Pdf();
function measureHeight( text, fontSize, min, width ){
temp.fontSize( fontSize );
temp.x = 0;
temp.y = 0;
temp.text( text, { width: width } );
return temp.y;
}
function fittedSize( text, fontSize, min, step, bounds ){
if( fontSize <= min ) return min;
var height = measureHeight( text, fontSize, min, bounds.width );
if( height <= bounds.height ) return fontSize;
return fittedSize( text, fontSize - step, min, step, bounds );
}
var bounds = {
width: 200,
height: 400
};
var bestSize = fittedSize( lorem, 14, 8, 0.25, bounds );
var doc = new Pdf();
doc.fontSize( bestSize );
doc.rect( doc.x, doc.y, bounds.width, bounds.height ).stroke();
doc.text( lorem, {
width: bounds.width,
height: bounds.height,
ellipsis: true
});
doc.pipe( fs.createWriteStream( 'fittedSize.pdf' ) );
doc.end();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment