├── .gitignore ├── .travis.yml ├── LICENSE ├── README.md ├── lib ├── draw.js ├── fontsize.js ├── index.js ├── resize.js ├── svgcompile.js ├── svgrender.js ├── titleparts.js └── topic │ ├── colors.json │ ├── index.js │ └── topics.json ├── package.json ├── scripts └── patch_pango.sh ├── templates ├── default.svg └── published-with-gitbook.svg └── test ├── draw.js └── title_parts.js /.gitignore: -------------------------------------------------------------------------------- 1 | # Logs 2 | logs 3 | *.log 4 | 5 | # Runtime data 6 | pids 7 | *.pid 8 | *.seed 9 | 10 | # Directory for instrumented libs generated by jscoverage/JSCover 11 | lib-cov 12 | 13 | # Coverage directory used by tools like istanbul 14 | coverage 15 | 16 | # Grunt intermediate storage (http://gruntjs.com/creating-plugins#storing-task-files) 17 | .grunt 18 | 19 | # Compiled binary addons (http://nodejs.org/api/addons.html) 20 | build/Release 21 | 22 | # Dependency directory 23 | # Deployed apps should consider commenting this line out: 24 | # see https://npmjs.org/doc/faq.html#Should-I-check-my-node_modules-folder-into-git 25 | node_modules 26 | test.jpeg 27 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | sudo: false 2 | language: node_js 3 | node_js: 4 | - "stable" 5 | - "4.2" 6 | - "0.12" 7 | addons: 8 | apt: 9 | sources: 10 | - ubuntu-toolchain-r-test 11 | packages: 12 | - libcairo2-dev 13 | - libjpeg8-dev 14 | - libpango1.0-dev 15 | - libgif-dev 16 | - g++-4.8 17 | env: 18 | - CXX=g++-4.8 19 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "{}" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright {yyyy} {name of copyright owner} 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | Cover Generation for GitBook 2 | ================ 3 | 4 | Generate a cover for the book. 5 | 6 | ## How to use it: 7 | 8 | To use this plugin in your book, add it to your `book.json`: 9 | 10 | ```js 11 | { 12 | "plugins": ["autocover"], 13 | "pluginsConfig": { 14 | "autocover": { 15 | // Configuration for autocover (see below) 16 | } 17 | } 18 | } 19 | ``` 20 | 21 | And run `gitbook install` to fetch and prepare all plugins. 22 | 23 | ## Installation of `canvas` 24 | 25 | This module use [node-canvas](https://github.com/LearnBoost/node-canvas). You need to install some modules on your system before being able to use it: [Wiki of node-canvas](https://github.com/LearnBoost/node-canvas/wiki/_pages). 26 | 27 | 28 | ## Configuration 29 | 30 | Here is default configuration of **autocover**, you can change it in your book.json: 31 | 32 | ```js 33 | { 34 | "title": "My Book", 35 | "author": "Author", 36 | "pluginsConfig": { 37 | "autocover": { 38 | "font": { 39 | "size": null, 40 | "family": "Impact", 41 | "color": "#FFF" 42 | }, 43 | "size": { 44 | "w": 1800, 45 | "h": 2360 46 | }, 47 | "background": { 48 | "color": "#09F" 49 | } 50 | } 51 | } 52 | } 53 | ``` 54 | -------------------------------------------------------------------------------- /lib/draw.js: -------------------------------------------------------------------------------- 1 | var Q = require('q'); 2 | var fs = require('fs'); 3 | var path = require('path'); 4 | var _ = require('lodash'); 5 | 6 | var geopattern = require('geopattern'); 7 | 8 | var fontSize = require('./fontsize'); 9 | var titleParts = require('./titleparts'); 10 | var svgCompile = require('./svgcompile'); 11 | var svgRender = require('./svgrender'); 12 | 13 | var topics = require('./topic/'); 14 | var colors = require('./topic/colors.json'); 15 | 16 | module.exports = function(output, options) { 17 | 18 | // 19 | // Default options 20 | // 21 | 22 | options = _.defaultsDeep(options || {}, { 23 | "title": "", 24 | "author": "", 25 | "font": { 26 | "size": null, 27 | "family": "Arial", 28 | "color": '#424242' 29 | }, 30 | "template": path.join(__dirname, "../templates/default.svg"), 31 | "watermark": path.join(__dirname, "../templates/published-with-gitbook.svg"), 32 | "size": { 33 | "w": 1800, 34 | "h": 2360 35 | }, 36 | "background": { 37 | "color": '#fff' 38 | } 39 | }); 40 | 41 | 42 | // Font 43 | var fontname = options.font.family; 44 | 45 | // 46 | // Topic color 47 | // 48 | 49 | var topic = topics(options.title)[0]; 50 | 51 | options.topic = options.topic || {}; 52 | options.topic.color = (topic && colors[topic]) ? colors[topic] : colors.default; 53 | 54 | 55 | // 56 | // Add pattern helper 57 | // 58 | var pattern = geopattern.generate(options.title); 59 | options.pattern = pattern; 60 | options.pattern_width = pattern.svg.svg.attributes.width; 61 | options.pattern_height = pattern.svg.svg.attributes.height; 62 | 63 | 64 | // 65 | // Title split in lines & size 66 | // 67 | 68 | // Dimensions of title's box 69 | var titleBox = { 70 | w: Math.floor(options.size.w * 0.8), 71 | h: Math.floor(options.size.h * 0.6), 72 | }; 73 | var maxLineHeight = Math.floor(titleBox.h * 0.1); 74 | 75 | var tParts = titleParts( 76 | options.title, 77 | fontname, 78 | titleBox.w, 79 | titleBox.h 80 | ); 81 | 82 | // The height of an individual line 83 | var lineHeight = Math.min( 84 | Math.floor(titleBox.h / tParts.length), 85 | maxLineHeight 86 | ); 87 | 88 | // Rewrite title to parts 89 | options.title = tParts; 90 | 91 | // Calculate title's default font size 92 | var defaultTitleSize = Math.min.apply(Math, options.title.map(function(part) { 93 | return fontSize( 94 | part, fontname, 95 | titleBox.w, 96 | lineHeight 97 | ); 98 | })); 99 | 100 | // Title size 101 | options.size.title = options.size.title || defaultTitleSize; 102 | 103 | // 104 | // Author size 105 | // 106 | 107 | options.size.author = options.size.author || fontSize( 108 | options.author, fontname, 109 | titleBox.w, options.size.h 110 | ); 111 | 112 | 113 | // 114 | // Generate the cover 115 | // 116 | 117 | var template = fs.existsSync('cover.svg') ? 'cover.svg' : options.template; 118 | 119 | // Make SVG with options 120 | return svgCompile(template, options) 121 | .then(function(svg) { 122 | // Render SVG to JPEG 123 | return svgRender(output, svg, options.size.w, options.size.h); 124 | }); 125 | }; 126 | -------------------------------------------------------------------------------- /lib/fontsize.js: -------------------------------------------------------------------------------- 1 | var Canvas = require('canvas'); 2 | 3 | function textsize(str, size, font) { 4 | // We only want the context to do our predictions 5 | var ctx = new Canvas().getContext('2d'); 6 | 7 | // Set font 8 | ctx.font = size+"px "+font; 9 | 10 | // Get dimensions it would occupy 11 | var dim = ctx.measureText(str); 12 | 13 | return { 14 | width: dim.width, 15 | height: dim.emHeightAscent + dim.emHeightDescent, 16 | }; 17 | } 18 | 19 | // Get the good font size for text to fit in a given width 20 | function fontSizeForDimensions(str, font, width, height, lower, upper) { 21 | // Lower and upper bounds for font 22 | lower = (lower === undefined) ? 0 : lower; 23 | upper = (upper === undefined) ? height : upper; 24 | 25 | // The font size we're guessing with 26 | var middle = Math.floor((upper + lower) / 2); 27 | 28 | if(middle === lower) { 29 | return middle; 30 | } 31 | 32 | // Get text dimensions 33 | var tsize = textsize(str, middle, font); 34 | 35 | return ( 36 | // Are we above or below ? 37 | (tsize.width <= width && tsize.height <= height) ? 38 | // Go up 39 | fontSizeForDimensions(str, font, width, height, middle, upper) : 40 | // Go down 41 | fontSizeForDimensions(str, font, width, height, lower, middle) 42 | ); 43 | } 44 | 45 | module.exports = fontSizeForDimensions; 46 | -------------------------------------------------------------------------------- /lib/index.js: -------------------------------------------------------------------------------- 1 | var fs = require('fs'); 2 | var path = require('path'); 3 | var _ = require('lodash'); 4 | var Q = require('q'); 5 | 6 | var createCover = require('./draw'); 7 | var resize = require('./resize'); 8 | 9 | // Copy a file 10 | function copy(from, to) { 11 | var d = Q.defer(); 12 | var r = fs.createReadStream(from); 13 | var w = fs.createWriteStream(to); 14 | 15 | w.on('finish', d.resolve); 16 | w.on('error', d.reject); 17 | r.on('error', d.reject); 18 | 19 | r.pipe(w); 20 | 21 | return d.promise; 22 | } 23 | 24 | module.exports = { 25 | book: {}, 26 | hooks: { 27 | "finish:before": function() { 28 | var that = this; 29 | var multiLangs = that.isMultilingual(); 30 | var pluginConfig = that.config.get('pluginsConfig.autocover', {}); 31 | 32 | var inputDir = that.resolve('.'); 33 | var outputDir = that.output.resolve('.'); 34 | 35 | if (multiLangs) { 36 | inputDir = path.resolve(inputDir, ".."); 37 | outputDir = path.resolve(outputDir, ".."); 38 | } 39 | 40 | return Q() 41 | 42 | // Generate big cover 43 | .then(function() { 44 | // Check if a cover already exists in the output 45 | if (fs.existsSync(path.join(outputDir, "cover.jpg"))) return Q(); 46 | 47 | // Check if a cover already exists in the input 48 | if (fs.existsSync(path.join(inputDir, "cover.jpg"))) { 49 | // Copy this cover 50 | return copy( 51 | path.join(inputDir, "cover.jpg"), 52 | path.join(outputDir, "cover.jpg") 53 | ); 54 | } 55 | 56 | return createCover( 57 | path.join(outputDir, "cover.jpg"), 58 | _.extend({}, { 59 | title: that.config.get('title'), 60 | author: that.config.get('author') 61 | }, pluginConfig) 62 | ); 63 | }) 64 | 65 | // Generate small cover 66 | .then(function() { 67 | // Check if a cover already exists in the output 68 | if (fs.existsSync(path.join(outputDir, "cover_small.jpg"))) return Q(); 69 | 70 | // Check if a cover already exists in the input 71 | if (fs.existsSync(path.join(inputDir, "cover_small.jpg"))) { 72 | // Copy this cover 73 | return copy( 74 | path.join(inputDir, "cover_small.jpg"), 75 | path.join(outputDir, "cover_small.jpg") 76 | ); 77 | } 78 | 79 | return resize( 80 | path.resolve(outputDir, "cover.jpg"), 81 | path.join(outputDir, "cover_small.jpg"), 82 | { 83 | width: 200 84 | } 85 | ); 86 | }) 87 | 88 | // Ignore error 89 | .fail(function(err) { 90 | console.log("Error with autocover: ", err.stack || err.message || err); 91 | return Q(); 92 | }); 93 | } 94 | } 95 | }; 96 | -------------------------------------------------------------------------------- /lib/resize.js: -------------------------------------------------------------------------------- 1 | var Q = require('q'); 2 | var fs = require('fs'); 3 | var Canvas = require('canvas'); 4 | 5 | function resize(input, output, nSize) { 6 | var d = Q.defer(); 7 | 8 | var img = new Canvas.Image(); 9 | 10 | img.onerror = function(err){ 11 | d.reject(err); 12 | }; 13 | 14 | img.onload = function(){ 15 | if (!nSize.height) nSize.height = (img.height*nSize.width)/img.width; 16 | 17 | var canvas = new Canvas(nSize.width, nSize.height); 18 | var ctx = canvas.getContext('2d'); 19 | 20 | ctx.imageSmoothingEnabled = true; 21 | ctx.drawImage(img, 0, 0, nSize.width, nSize.height); 22 | 23 | var out = fs.createWriteStream(output); 24 | var stream = canvas.createJPEGStream(); 25 | 26 | stream.on('data', function(chunk){ 27 | out.write(chunk); 28 | }); 29 | stream.on('end', function() { 30 | d.resolve(); 31 | }); 32 | }; 33 | 34 | // WARNING: 35 | // This is a hack to fix "Premature end of JPEG file" errors 36 | // Basically that error happens because data isn't flushed to the disk 37 | // By doing this setTimeout, we are forcing Node to go back to it's event loop 38 | // where it finishes the I/O and flushes the data to disk 39 | setTimeout(function() { 40 | img.src = input; 41 | }, 0); 42 | 43 | return d.promise; 44 | } 45 | 46 | module.exports = resize; 47 | -------------------------------------------------------------------------------- /lib/svgcompile.js: -------------------------------------------------------------------------------- 1 | var Q = require('q'); 2 | var fs = require('fs'); 3 | var _ = require('lodash'); 4 | 5 | function compileFromFile(filename, data, callback) { 6 | if (typeof filename !== 'string') throw new Error('filename must be a string'); 7 | if (typeof data !== 'object') throw new Error('data must be an object'); 8 | if (typeof callback !== 'function') throw new Error('must provide a callback'); 9 | 10 | fs.readFile(filename, 'utf8', function(err, contents) { 11 | if (err) callback(err); 12 | var template = _.template(contents); 13 | callback(null, template(data)); 14 | }); 15 | } 16 | 17 | function compileQ(filename, data) { 18 | return Q.nfcall(compileFromFile, filename, data); 19 | } 20 | 21 | module.exports = compileQ; 22 | -------------------------------------------------------------------------------- /lib/svgrender.js: -------------------------------------------------------------------------------- 1 | var Q = require('q'); 2 | var fs = require('fs'); 3 | 4 | var canvg = require('canvg'); 5 | var Canvas = require('canvas'); 6 | 7 | function renderSvg(outputfilename, svgdata, width, height) { 8 | var d = Q.defer(); 9 | 10 | try { 11 | var canvas = new Canvas(width, height); 12 | 13 | // Render SVG image 14 | canvg(canvas, svgdata, 15 | { 16 | ignoreAnimation: true, 17 | renderCallback: function() 18 | { 19 | // Create streams 20 | var out = fs.createWriteStream(outputfilename); 21 | var stream = canvas.jpegStream(); 22 | 23 | // Pipe 24 | stream.pipe(out); 25 | 26 | // Wait till finished piping/writing 27 | out.on('close', d.resolve); 28 | out.on('error', d.reject); 29 | } 30 | }); 31 | } catch(err) { 32 | return Q.reject(err); 33 | } 34 | 35 | return d.promise; 36 | } 37 | 38 | module.exports = renderSvg; 39 | -------------------------------------------------------------------------------- /lib/titleparts.js: -------------------------------------------------------------------------------- 1 | var fontSize = require('./fontsize'); 2 | 3 | // titleParts breaks a string into a list of lines 4 | // where each line fits inside the box of dimensions = width*height 5 | // for a given font family 6 | function titleParts(title, font, width, height) { 7 | // Words of title 8 | var parts = title.split(/\s+/); 9 | 10 | return parts 11 | .reduce(function(lines, part) { 12 | // First part 13 | if(lines.length === 0) return [part]; 14 | 15 | // Last processed part 16 | var prevPart = lines[lines.length - 1]; 17 | // Current part appended to last part 18 | var newPart = prevPart + ' ' + part; 19 | 20 | // Size of previous part by itself 21 | var fsize = fontSize( 22 | prevPart, font, 23 | width, height 24 | ); 25 | 26 | // How big is it if we add our new part ? 27 | var fsize2 = fontSize( 28 | newPart, font, 29 | width, height 30 | ); 31 | 32 | // If sizes are the same, then merge parts to same line 33 | if(fsize == fsize2 && fsize2) { 34 | lines[lines.length - 1] = newPart; 35 | return lines; 36 | } 37 | 38 | return lines.concat(part); 39 | }, []); 40 | } 41 | 42 | module.exports = titleParts; 43 | -------------------------------------------------------------------------------- /lib/topic/colors.json: -------------------------------------------------------------------------------- 1 | { 2 | "default": "#f1da50", 3 | "rust": "#dea584", 4 | "r": "#198ce7", 5 | "c++": "#f34b7d", 6 | "go": "#375eab", 7 | "php": "#4F5D95", 8 | "js": "#f1da50", 9 | "scala": "#f1da50", 10 | "java": "#b07219", 11 | "clojure": "#db5855", 12 | "python": "#3581ba", 13 | "swift": "#ffac45", 14 | "ruby": "#701516" 15 | } 16 | -------------------------------------------------------------------------------- /lib/topic/index.js: -------------------------------------------------------------------------------- 1 | var topics = require('./topics.json'); 2 | 3 | // Break up the incomming text into tokens 4 | function tokenize(str) { 5 | return str.toLowerCase().split(/\s+/).filter(Boolean); 6 | } 7 | 8 | // Intersection of two arrays 9 | function intersect(a, b) { 10 | var t; 11 | // Swap a and b (to use shortest for loop iteration) 12 | if (b.length > a.length) { 13 | t = b, b = a, a = t; 14 | } 15 | 16 | return a.filter(function (e) { 17 | if (b.indexOf(e) !== -1) return true; 18 | }); 19 | } 20 | 21 | function doIntersect(a, b) { 22 | return intersect(a, b).length > 0; 23 | } 24 | 25 | // Derive topic based on keywords in a string 26 | // this is meant for small corpuses of text (titles, etc ...) 27 | module.exports = function topic(str) { 28 | var tokens = tokenize(str); 29 | 30 | return Object.keys(topics).filter(function(key) { 31 | var topicTokens = topics[key]; 32 | 33 | return ( 34 | // Exact match of topic name 35 | tokens.indexOf(key) !== -1 || 36 | 37 | // Match of topic tokens 38 | doIntersect(tokens, topicTokens) 39 | ); 40 | }); 41 | }; 42 | -------------------------------------------------------------------------------- /lib/topic/topics.json: -------------------------------------------------------------------------------- 1 | { 2 | "rust": [ 3 | ], 4 | "r": [ 5 | ], 6 | "c++": [ 7 | "c" 8 | ], 9 | "go": [ 10 | "golang", 11 | "gopher", 12 | "martini" 13 | ], 14 | "php": [ 15 | "laravel", 16 | "wordpress" 17 | ], 18 | "js": [ 19 | "javascript", 20 | "nodejs", 21 | "node.js", 22 | "jquery", 23 | "angular", 24 | "angularjs" 25 | ], 26 | "scala": [ 27 | ], 28 | "java": [ 29 | "tomcat", 30 | "android" 31 | ], 32 | "clojure": [ 33 | "noir", 34 | "leiningen" 35 | ], 36 | "python": [ 37 | "django", 38 | "flask" 39 | ], 40 | "swift": [ 41 | ], 42 | "ruby": [ 43 | "rails", 44 | "sinatra", 45 | "chef" 46 | ] 47 | } 48 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gitbook-plugin-autocover", 3 | "description": "Generate a cover for a gitbook", 4 | "main": "./lib/index.js", 5 | "version": "2.0.1", 6 | "engines": { 7 | "gitbook": ">=3.0.0" 8 | }, 9 | "scripts": { 10 | "test": "mocha" 11 | }, 12 | "dependencies": { 13 | "q": "^1.4.1", 14 | "lodash": "^4.5.0", 15 | "canvas": "1.3.15", 16 | "canvg": "^0.0.8", 17 | "geopattern": "1.2.3" 18 | }, 19 | "devDependencies": { 20 | "mocha": "2.3.3" 21 | }, 22 | "homepage": "https://github.com/GitbookIO/plugin-autocover", 23 | "repository": { 24 | "type": "git", 25 | "url": "https://github.com/GitbookIO/plugin-autocover.git" 26 | }, 27 | "license": "Apache-2.0", 28 | "bugs": { 29 | "url": "https://github.com/GitbookIO/plugin-autocover/issues" 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /scripts/patch_pango.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | set -o nounset 4 | set -o errexit 5 | set -o pipefail 6 | 7 | # Dir of script 8 | DIR=$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd ) 9 | 10 | # Variables 11 | canvas="${DIR}/../node_modules/canvas" 12 | a="'with_pango%': 'false'" 13 | b="'with_pango%': 'true'" 14 | gyp="node-gyp" 15 | 16 | # Turn on pango support 17 | bash -c "sed -i -e \"s/$a/$b/g\" ${canvas}/binding.gyp" 18 | 19 | # Rebuild 20 | bash -c "cd ${canvas} && ${gyp} rebuild" 21 | -------------------------------------------------------------------------------- /templates/default.svg: -------------------------------------------------------------------------------- 1 | 2 | 7 | 8 | 12 | 13 | 19 | <% _.forEach(title, function(part){ %> 20 | <%= part %> 21 | <% }); %> 22 | 23 | 24 | <%= author %> 29 | 30 | 34 | 35 | -------------------------------------------------------------------------------- /templates/published-with-gitbook.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 6 | 7 | 8 | 13 | 14 | 15 | 18 | 19 | 20 | 24 | 25 | 26 | 27 | 30 | 31 | 32 | 33 | Publishedwith GitBook 34 | 35 | 36 | -------------------------------------------------------------------------------- /test/draw.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var draw = require('../lib/draw'); 3 | 4 | describe('draw', function() { 5 | it('should correctly write file', function() { 6 | return draw('./test.jpeg', { 7 | title: "The Swift Programming Language 中文版", 8 | author: "Samy Pessé" 9 | }); 10 | }); 11 | }); 12 | 13 | -------------------------------------------------------------------------------- /test/title_parts.js: -------------------------------------------------------------------------------- 1 | var assert = require('assert'); 2 | var titleParts = require('../lib/titleparts'); 3 | 4 | describe('title parts', function() { 5 | it('should split and group across lines', function() { 6 | var parts = titleParts( 7 | // Title 8 | "The Swift Programming Language 中文版", 9 | // Font 10 | "Helvetica", 11 | // Boundary dimensions 12 | 1800 * 0.8, // Width 13 | 2360 * 0.1 // Heigh 14 | ); 15 | 16 | assert.equal(parts.length, 3, "Title should be split across 4 lines"); 17 | }); 18 | }); 19 | 20 | --------------------------------------------------------------------------------