Permalink
Browse files

Add new self-generating guide

Takes Literate CoffeeScript (Markdown) files and generates a PDF. Includes syntax highlighting for the examples, and even runs them to show the results inline. Good example of new rich text features. Eventually, the website will be generated from the same Markdown files.
  • Loading branch information...
1 parent a0901c7 commit e11a800af3ed0c5d203b4fb11fc55cf332466447 @devongovett committed Feb 18, 2014
View
@@ -0,0 +1,22 @@
+# PDFKit Guide
+
+The PDFKit guide can be read a number of ways. The first is online at [http://pdfkit.org/](pdfkit.org).
+You can also read the guide in PDF form, in this directory or [online](http://pdfkit.org/docs/guide.pdf).
+
+Both the website and the PDF guide are generated from the Literate CoffeeScript (runnable Markdown) files
+in this directory. The examples are actually run when generating the PDF in order to show the results inline.
+The `generate.coffee` file in this directory is actually quite short. It parses the markdown files into a
+tree structure using [markdown-js](https://github.com/evilstreak/markdown-js), syntax highlights the code
+examples using [codemirror](https://github.com/marijnh/codemirror), compiles and runs the code examples and puts the results
+inline, and generates the PDF using PDFKit. You can read the generator script source code to get a feeling for
+how you might do something slightly more complex than the guide itself shows.
+
+The markdown syntax used is pretty much standard, with a couple tweaks.
+
+1. Code example output is references using the image notation, using the alt text as the example number starting from
+ zero in the current file, and the title as the example output height. E.g. `![x](name "height")`.
+
+2. Page breaks are added before `h1` and `h2`s, unless there are two in a row. `h3` is treated the same as `h2` but
+ can be used to avoid this in the case you need multiple `h2`s on the same page.
+
+3. The horizontal rule syntax (`* * *`) denotes an explicit page break
@@ -0,0 +1,97 @@
+# Annotations in PDFKit
+
+Annotations are interactive features of the PDF format, and they make it
+possible to include things like links and attached notes, or to highlight,
+underline or strikeout portions of text. Annotations are added using the
+various helper methods, and each type of annotation is defined by a rectangle
+and some other properties. Here is a list of the available annotation methods:
+
+* `note(x, y, width, height, contents, options)`
+* `link(x, y, width, height, url, options)`
+* `highlight(x, y, width, height, options)`
+* `underline(x, y, width, height, options)`
+* `strike(x, y, width, height, options)`
+* `lineAnnotation(x1, y1, x2, y2, options)`
+* `rectAnnotation(x, y, width, height, options)`
+* `ellipseAnnotation(x, y, width, height, options)`
+* `textAnnotation(x, y, width, height, text, options)`
+
+Many of the annotations have a `color` option that you can specify. You can
+use an array of RGB values, a hex color, or a named CSS color value for that
+option.
+
+If you are adding an annotation to a piece of text, such as a link or
+underline, you will need to know the width and height of the text in order to
+create the required rectangle for the annotation. There are two methods that
+you can use to do that. To get the width of any piece of text in the current
+font, just call the `widthOfString` method with the string you want to
+measure. To get the line height in the current font, just call the
+`currentLineHeight` method.
+
+You must remember that annotations have a stacking order. If you are putting
+more than one annotation on a single area and one of those annotations is a
+link, make sure that the link is the last one you add, otherwise it will be
+covered by another annotation and the user won't be able to click it.
+
+* * *
+
+Here is an example that uses a few of the annotation types.
+
+ # Add the link text
+ doc.fontSize(25)
+ .fillColor('blue')
+ .text('This is a link!', 20, 0)
+
+ # Measure the text
+ width = doc.widthOfString('This is a link!')
+ height = doc.currentLineHeight()
+
+ # Add the underline and link annotations
+ doc.underline(20, 0, width, height, color: 'blue')
+ .link(20, 0, width, height, 'http://google.com/')
+
+ # Create the highlighted text
+ doc.moveDown()
+ .fillColor('black')
+ .highlight(20, doc.y, doc.widthOfString('This text is highlighted!'), height)
+ .text('This text is highlighted!')
+
+ # Create the crossed out text
+ doc.moveDown()
+ .strike(20, doc.y, doc.widthOfString('STRIKE!'), height)
+ .text('STRIKE!')
+
+The output of this example looks like this.
+
+![0](images/annotations.png)
+
+Annotations are currently not the easiest things to add to PDF documents, but
+that is the fault of the PDF spec itself. Calculating a rectangle manually isn't
+fun, but PDFKit makes it easier for a few common annotations applied to text, including
+links, underlines, and strikes. Here's an example showing two of them:
+
+ doc.fontSize 20
+ .fillColor 'red'
+ .text 'Another link!', 20, 0,
+ link: 'http://apple.com/',
+ underline: true
+
+The output is as you'd expect:
+
+![1]()
+
+# You made it!
+
+That's all there is too creating PDF documents in PDFKit. It's really quite
+simple to create beautiful multi-page printable documents using Node.js!
+
+This guide was actually generated from Markdown/Literate CoffeeScript files using a
+PDFKit generation script. The examples are actually run to generate the output shown
+inline. The script generates both the website and the PDF guide, and
+can be found [on Github](http://github.com/devongovett/pdfkit/tree/master/docs/generate.coffee).
+Check it out if you want to see an example of a slightly more complicated renderer using
+a parser for Markdown and a syntax highlighter.
+
+If you have any questions about what you've learned in this guide, please don't
+hesitate to [ask the author](http://twitter.com/devongovett) or post an issue
+on [Github](http://github.com/devongovett/pdfkit/issues). Enjoy!
Binary file not shown.
Binary file not shown.
Binary file not shown.
View
Binary file not shown.
Binary file not shown.
Binary file not shown.
Binary file not shown.
View
@@ -0,0 +1,251 @@
+fs = require 'fs'
+vm = require 'vm'
+md = require('markdown').markdown
+coffee = require 'coffee-script'
+CodeMirror = require 'codemirror/addon/runmode/runmode.node'
+PDFDocument = require '../'
+
+# setup code mirror coffeescript mode
+filename = require.resolve('codemirror/mode/coffeescript/coffeescript')
+coffeeMode = fs.readFileSync filename, 'utf8'
+vm.runInNewContext coffeeMode, CodeMirror: CodeMirror
+
+# style definitions for markdown
+styles =
+ h1:
+ font: 'fonts/Alegreya-Bold.ttf'
+ fontSize: 25
+ padding: 15
+ h2:
+ font: 'fonts/Alegreya-Bold.ttf'
+ fontSize: 18
+ padding: 10
+ h3:
+ font: 'fonts/Alegreya-Bold.ttf'
+ fontSize: 18
+ padding: 10
+ para:
+ font: 'fonts/Merriweather-Regular.ttf'
+ fontSize: 10
+ padding: 10
+ code:
+ font: 'fonts/SourceCodePro-Regular.ttf'
+ fontSize: 9
+ code_block:
+ padding: 10
+ background: '#2c2c2c'
+ inlinecode:
+ font: 'fonts/SourceCodePro-Bold.ttf'
+ fontSize: 10
+ listitem:
+ font: 'fonts/Merriweather-Regular.ttf'
+ fontSize: 10
+ padding: 6
+ link:
+ font: 'fonts/Merriweather-Regular.ttf'
+ fontSize: 10
+ color: 'blue'
+ underline: true
+ example:
+ font: 'Helvetica'
+ fontSize: 9
+ color: 'black'
+ padding: 10
+
+# syntax highlighting colors
+# based on Github's theme
+colors =
+ keyword: '#cb4b16'
+ atom: '#d33682'
+ number: '#009999'
+ def: '#2aa198'
+ variable: '#108888'
+ 'variable-2': '#b58900'
+ 'variable-3': '#6c71c4'
+ property: '#2aa198'
+ operator: '#6c71c4'
+ comment: '#999988'
+ string: '#dd1144'
+ 'string-2': '#009926'
+ meta: '#768E04'
+ qualifier: '#b58900'
+ builtin: '#d33682'
+ bracket: '#cb4b16'
+ tag: '#93a1a1'
+ attribute: '#2aa198'
+ header: '#586e75'
+ quote: '#93a1a1'
+ link: '#93a1a1'
+ special: '#6c71c4'
+ default: '#002b36'
+
+# shared lorem ipsum text so we don't need to copy it into every example
+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;'
+
+codeBlocks = []
+lastType = null
+
+# This class represents a node in the markdown tree, and can render it to pdf
+class Node
+ constructor: (tree) ->
+ # special case for text nodes
+ if typeof tree is 'string'
+ @type = 'text'
+ @text = tree
+ return
+
+ @type = tree.shift()
+ @attrs = {}
+
+ if typeof tree[0] is 'object' and not Array.isArray tree[0]
+ @attrs = tree.shift()
+
+ # parse sub nodes
+ @content = while tree.length
+ new Node tree.shift()
+
+ switch @type
+ when 'header'
+ @type = 'h' + @attrs.level
+
+ when 'code_block'
+ # use code mirror to syntax highlight the code block
+ code = @content[0].text
+ @content = []
+ CodeMirror.runMode code, 'coffeescript', (text, style) =>
+ color = colors[style] or colors.default
+ opts =
+ color: color
+ continued: text isnt '\n'
+
+ @content.push new Node ['code', opts, text]
+
+ @content[@content.length - 1]?.attrs.continued = false
+ codeBlocks.push code
+
+ when 'img'
+ # images are used to generate inline example output
+ # compiles the coffeescript to JS so it can be run
+ # in the render method
+ @type = 'example'
+ code = codeBlocks[@attrs.alt]
+ @code = coffee.compile code if code
+ @height = +@attrs.title or 0
+
+ @style = styles[@type] or styles.para
+
+ # sets the styles on the document for this node
+ setStyle: (doc) ->
+ if @style.font
+ doc.font @style.font
+
+ if @style.fontSize
+ doc.fontSize @style.fontSize
+
+ if @style.color or @attrs.color
+ doc.fillColor @style.color or @attrs.color
+ else
+ doc.fillColor 'black'
+
+ options = {}
+ options.align = @style.align
+ options.link = @attrs.href
+ options.continued = @attrs.continued if @attrs.continued?
+ return options
+
+ # renders this node and its subnodes to the document
+ render: (doc, continued = false) ->
+ switch @type
+ when 'example'
+ @setStyle doc
+
+ # translate all points in the example code to
+ # the current point in the document
+ doc.moveDown()
+ doc.save()
+ doc.translate(doc.x, doc.y)
+ x = doc.x
+ y = doc.y
+ doc.x = doc.y = 0
+
+ # run the example code with the document
+ vm.runInNewContext @code,
+ doc: doc
+ lorem: lorem
+
+ # restore points and styles
+ y += doc.y
+ doc.restore()
+ doc.x = x
+ doc.y = y + @height
+ when 'hr'
+ doc.addPage()
+ else
+ # loop through subnodes and render them
+ for fragment, index in @content
+ if fragment.type is 'text'
+ # add a new page for each heading, unless it follows another heading
+ if @type in ['h1', 'h2'] and lastType? and lastType isnt 'h1'
+ doc.addPage()
+
+ # set styles and whether this fragment is continued (for rich text wrapping)
+ options = @setStyle doc
+ options.continued ?= continued or index < @content.length - 1
+
+ # remove newlines unless this is code
+ unless @type is 'code'
+ fragment.text = fragment.text.replace(/[\r\n]\s*/g, ' ')
+
+ doc.text fragment.text, options
+ else
+ fragment.render doc, index < @content.length - 1 and @type isnt 'bulletlist'
+
+ lastType = @type
+
+ if @style.padding
+ doc.y += @style.padding
+
+# reads and renders a markdown/literate coffeescript file to the document
+render = (doc, filename) ->
+ codeBlocks = []
+ tree = md.parse fs.readFileSync(filename, 'utf8')
+ tree.shift()
+
+ while tree.length
+ node = new Node tree.shift()
+ node.render(doc)
+
+# renders the title page of the guide
+renderTitlePage = (doc) ->
+ title = 'PDFKit Guide'
+ author = 'By Devon Govett'
+ version = 'Version ' + require('../package.json').version
+
+ doc.font 'fonts/AlegreyaSans-Light.ttf', 60
+ doc.y = doc.page.height / 2 - doc.currentLineHeight()
+ doc.text title, align: 'center'
+ w = doc.widthOfString(title)
+
+ doc.fontSize 20
+ doc.y -= 10
+ doc.text author,
+ align: 'center'
+ indent: w - doc.widthOfString(author)
+
+ doc.font styles.para.font, 10
+ doc.text version,
+ align: 'center'
+ indent: w - doc.widthOfString(version)
+
+ doc.addPage()
+
+# render all sections of the guide and write the pdf file
+do ->
+ doc = new PDFDocument
+ renderTitlePage doc
+ render doc, 'getting_started.coffee.md'
+ render doc, 'vector.coffee.md'
+ render doc, 'text.coffee.md'
+ render doc, 'images.coffee.md'
+ render doc, 'annotations.coffee.md'
+ doc.write 'guide.pdf'
Oops, something went wrong.

0 comments on commit e11a800

Please sign in to comment.