measure-text.js 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. // SPDX-License-Identifier: GPL-3.0-or-later
  2. 'use strict';
  3. var path = require('path');
  4. var fs = require('fs');
  5. var PDFDocument = require('pdfkit');
  6. var doc = new PDFDocument({size:'A4', layout:'landscape'});
  7. function loadFont(fontPaths, callback) {
  8. for (let fontPath of fontPaths) {
  9. try {
  10. doc = doc.font(fontPath);
  11. if (callback) { callback(null); }
  12. return; // Exit once a font is loaded successfully
  13. } catch(err) {
  14. // Log error but continue to next font path
  15. console.error(`Failed to load font from path: ${fontPath}. Error: ${err.message}`);
  16. }
  17. }
  18. // If we reached here, none of the fonts were loaded successfully.
  19. console.error('All font paths failed. Stopping execution.');
  20. process.exit(1); // Exit with an error code
  21. }
  22. loadFont(['IBMPlexSans-Bold.ttf'], function(err) {
  23. if (err) {
  24. console.error('Could not load any of the specified fonts.');
  25. }
  26. });
  27. doc = doc.fontSize(250);
  28. function measureCombination(charA, charB) {
  29. return doc.widthOfString(charA + charB);
  30. }
  31. function getCharRepresentation(charCode) {
  32. return (charCode >= 32 && charCode <= 126) ? String.fromCharCode(charCode) : '';
  33. }
  34. function generateCombinationArray() {
  35. let output = "static const unsigned short int ibm_plex_sans_bold_250[128][128] = {\n";
  36. for (let i = 0; i <= 126; i++) {
  37. output += " {"; // Start of inner array
  38. for (let j = 0; j <= 126; j++) {
  39. let charA = getCharRepresentation(i);
  40. let charB = getCharRepresentation(j);
  41. let width = measureCombination(charA, charB) - doc.widthOfString(charB);
  42. let encodedWidth = Math.round(width * 100); // Multiply by 100 and round
  43. if(charA === '*' && charB == '/')
  44. charB = '\\/';
  45. if(charA === '/' && charB == '*')
  46. charB = '\\*';
  47. output += `${encodedWidth} /* ${charA}${charB} */`;
  48. if (j < 126) {
  49. output += ", ";
  50. }
  51. }
  52. output += "},\n"; // End of inner array
  53. }
  54. output += "};\n"; // End of 2D array
  55. return output;
  56. }
  57. console.log(generateCombinationArray());
  58. console.log('static const unsigned short int ibm_plex_sans_bold_250_em_size = ' + Math.round(doc.widthOfString('M') * 100) + ';');