/jspdf.plugin.split_text_to_size.js

https://github.com/maplejan/jsPDF · JavaScript · 298 lines · 162 code · 37 blank · 99 comment · 30 complexity · c98ae61365b3677ae4049ec41b038f0a MD5 · raw file

  1. /** @preserve
  2. jsPDF split_text_to_size plugin
  3. Copyright (c) 2012 Willow Systems Corporation, willow-systems.com
  4. MIT license.
  5. */
  6. /**
  7. * Permission is hereby granted, free of charge, to any person obtaining
  8. * a copy of this software and associated documentation files (the
  9. * "Software"), to deal in the Software without restriction, including
  10. * without limitation the rights to use, copy, modify, merge, publish,
  11. * distribute, sublicense, and/or sell copies of the Software, and to
  12. * permit persons to whom the Software is furnished to do so, subject to
  13. * the following conditions:
  14. *
  15. * The above copyright notice and this permission notice shall be
  16. * included in all copies or substantial portions of the Software.
  17. *
  18. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  19. * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  20. * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
  21. * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
  22. * LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
  23. * OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
  24. * WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
  25. * ====================================================================
  26. */
  27. ;(function(API) {
  28. 'use strict'
  29. /**
  30. Returns an array of length matching length of the 'word' string, with each
  31. cell ocupied by the width of the char in that position.
  32. @function
  33. @param word {String}
  34. @param widths {Object}
  35. @param kerning {Object}
  36. @returns {Array}
  37. */
  38. var getCharWidthsArray = API.getCharWidthsArray = function(text, options){
  39. if (!options) {
  40. options = {}
  41. }
  42. var widths = options.widths ? options.widths : this.internal.getFont().metadata.Unicode.widths
  43. , widthsFractionOf = widths.fof ? widths.fof : 1
  44. , kerning = options.kerning ? options.kerning : this.internal.getFont().metadata.Unicode.kerning
  45. , kerningFractionOf = kerning.fof ? kerning.fof : 1
  46. // console.log("widths, kergnings", widths, kerning)
  47. var i, l
  48. , char_code
  49. , char_width
  50. , prior_char_code = 0 // for kerning
  51. , default_char_width = widths[0] || widthsFractionOf
  52. , output = []
  53. for (i = 0, l = text.length; i < l; i++) {
  54. char_code = text.charCodeAt(i)
  55. output.push(
  56. ( widths[char_code] || default_char_width ) / widthsFractionOf +
  57. ( kerning[char_code] && kerning[char_code][prior_char_code] || 0 ) / kerningFractionOf
  58. )
  59. prior_char_code = char_code
  60. }
  61. return output
  62. }
  63. var getArraySum = function(array){
  64. var i = array.length
  65. , output = 0
  66. while(i){
  67. ;i--;
  68. output += array[i]
  69. }
  70. return output
  71. }
  72. /**
  73. Returns a widths of string in a given font, if the font size is set as 1 point.
  74. In other words, this is "proportional" value. For 1 unit of font size, the length
  75. of the string will be that much.
  76. Multiply by font size to get actual width in *points*
  77. Then divide by 72 to get inches or divide by (72/25.6) to get 'mm' etc.
  78. @public
  79. @function
  80. @param
  81. @returns {Type}
  82. */
  83. var getStringUnitWidth = API.getStringUnitWidth = function(text, options) {
  84. return getArraySum(getCharWidthsArray.call(this, text, options))
  85. }
  86. /**
  87. returns array of lines
  88. */
  89. var splitLongWord = function(word, widths_array, firstLineMaxLen, maxLen){
  90. var answer = []
  91. // 1st, chop off the piece that can fit on the hanging line.
  92. var i = 0
  93. , l = word.length
  94. , workingLen = 0
  95. while (i !== l && workingLen + widths_array[i] < firstLineMaxLen){
  96. workingLen += widths_array[i]
  97. ;i++;
  98. }
  99. // this is first line.
  100. answer.push(word.slice(0, i))
  101. // 2nd. Split the rest into maxLen pieces.
  102. var startOfLine = i
  103. workingLen = 0
  104. while (i !== l){
  105. if (workingLen + widths_array[i] > maxLen) {
  106. answer.push(word.slice(startOfLine, i))
  107. workingLen = 0
  108. startOfLine = i
  109. }
  110. workingLen += widths_array[i]
  111. ;i++;
  112. }
  113. if (startOfLine !== i) {
  114. answer.push(word.slice(startOfLine, i))
  115. }
  116. return answer
  117. }
  118. // Note, all sizing inputs for this function must be in "font measurement units"
  119. // By default, for PDF, it's "point".
  120. var splitParagraphIntoLines = function(text, maxlen, options){
  121. // at this time works only on Western scripts, ones with space char
  122. // separating the words. Feel free to expand.
  123. if (!options) {
  124. options = {}
  125. }
  126. var spaceCharWidth = getCharWidthsArray(' ', options)[0]
  127. var words = text.split(' ')
  128. var line = []
  129. , lines = [line]
  130. , line_length = options.textIndent || 0
  131. , separator_length = 0
  132. , current_word_length = 0
  133. , word
  134. , widths_array
  135. var i, l, tmp
  136. for (i = 0, l = words.length; i < l; i++) {
  137. word = words[i]
  138. widths_array = getCharWidthsArray(word, options)
  139. current_word_length = getArraySum(widths_array)
  140. if (line_length + separator_length + current_word_length > maxlen) {
  141. if (current_word_length > maxlen) {
  142. // this happens when you have space-less long URLs for example.
  143. // we just chop these to size. We do NOT insert hiphens
  144. tmp = splitLongWord(word, widths_array, maxlen - (line_length + separator_length), maxlen)
  145. // first line we add to existing line object
  146. line.push(tmp.shift()) // it's ok to have extra space indicator there
  147. // last line we make into new line object
  148. line = [tmp.pop()]
  149. // lines in the middle we apped to lines object as whole lines
  150. while(tmp.length){
  151. lines.push([tmp.shift()]) // single fragment occupies whole line
  152. }
  153. current_word_length = getArraySum( widths_array.slice(word.length - line[0].length) )
  154. } else {
  155. // just put it on a new line
  156. line = [word]
  157. }
  158. // now we attach new line to lines
  159. lines.push(line)
  160. line_length = current_word_length
  161. separator_length = spaceCharWidth
  162. } else {
  163. line.push(word)
  164. line_length += separator_length + current_word_length
  165. separator_length = spaceCharWidth
  166. }
  167. }
  168. var output = []
  169. for (i = 0, l = lines.length; i < l; i++) {
  170. output.push( lines[i].join(' ') )
  171. }
  172. return output
  173. }
  174. /**
  175. Splits a given string into an array of strings. Uses 'size' value
  176. (in measurement units declared as default for the jsPDF instance)
  177. and the font's "widths" and "Kerning" tables, where availabe, to
  178. determine display length of a given string for a given font.
  179. We use character's 100% of unit size (height) as width when Width
  180. table or other default width is not available.
  181. @public
  182. @function
  183. @param text {String} Unencoded, regular JavaScript (Unicode, UTF-16 / UCS-2) string.
  184. @param size {Number} Nominal number, measured in units default to this instance of jsPDF.
  185. @param options {Object} Optional flags needed for chopper to do the right thing.
  186. @returns {Array} with strings chopped to size.
  187. */
  188. API.splitTextToSize = function(text, maxlen, options) {
  189. 'use strict'
  190. if (!options) {
  191. options = {}
  192. }
  193. var fsize = options.fontSize || this.internal.getFontSize()
  194. , newOptions = (function(options){
  195. var widths = {0:1}
  196. , kerning = {}
  197. if (!options.widths || !options.kerning) {
  198. var f = this.internal.getFont(options.fontName, options.fontStyle)
  199. , encoding = 'Unicode'
  200. // NOT UTF8, NOT UTF16BE/LE, NOT UCS2BE/LE
  201. // Actual JavaScript-native String's 16bit char codes used.
  202. // no multi-byte logic here
  203. if (f.metadata[encoding]) {
  204. return {
  205. widths: f.metadata[encoding].widths || widths
  206. , kerning: f.metadata[encoding].kerning || kerning
  207. }
  208. }
  209. } else {
  210. return {
  211. widths: options.widths
  212. , kerning: options.kerning
  213. }
  214. }
  215. // then use default values
  216. return {
  217. widths: widths
  218. , kerning: kerning
  219. }
  220. }).call(this, options)
  221. // first we split on end-of-line chars
  222. var paragraphs
  223. if (text.match(/[\n\r]/)) {
  224. paragraphs = text.split(/\r\n|\r|\n/g)
  225. } else {
  226. paragraphs = [text]
  227. }
  228. // now we convert size (max length of line) into "font size units"
  229. // at present time, the "font size unit" is always 'point'
  230. // 'proportional' means, "in proportion to font size"
  231. var fontUnit_maxLen = 1.0 * this.internal.scaleFactor * maxlen / fsize
  232. // at this time, fsize is always in "points" regardless of the default measurement unit of the doc.
  233. // this may change in the future?
  234. // until then, proportional_maxlen is likely to be in 'points'
  235. // If first line is to be indented (shorter or longer) than maxLen
  236. // we indicate that by using CSS-style "text-indent" option.
  237. // here it's in font units too (which is likely 'points')
  238. // it can be negative (which makes the first line longer than maxLen)
  239. newOptions.textIndent = options.textIndent ?
  240. options.textIndent * 1.0 * this.internal.scaleFactor / fsize :
  241. 0
  242. var i, l
  243. , output = []
  244. for (i = 0, l = paragraphs.length; i < l; i++) {
  245. output = output.concat(
  246. splitParagraphIntoLines(
  247. paragraphs[i]
  248. , fontUnit_maxLen
  249. , newOptions
  250. )
  251. )
  252. }
  253. return output
  254. }
  255. })(jsPDF.API);