title: How use async functions with node-pdfkit?
body: <p>I am trying to create a PDF file with <a href="http://pdfkit.org" rel="nofollow">PDFKit</a>. I insert an image with like this:</p>
  
  <pre><code>var PDFDocument = require('pdfkit');
  var doc = new PDFDocument();
  
  doc.image(some_image_as_buffer);
  </code></pre>
  
  <p>and it is working like expected. But now want the image be trimmed and I found <a href="http://aheckmann.github.io/gm/" rel="nofollow">GraphicsMagick for node.js</a>. But the problem that I have is to make it work with PDFKit. <code>doc.image</code> expects a filename or a buffer, but since I already have a buffer I want to work with buffers (there is no file anywhere because the buffer comes directly from the database).</p>
  
  <p>The trimming works like this:</p>
  
  <pre><code>var gm = require('gm');
  gm(some_image_as_buffer, 'image.png')
    .trim()
    .toBuffer(function(err, trimmed_image_buffer) {
      // trimmed_image_buffer is correct,
      // but I can't put it to the document like this:
      doc.image(trimmed_image_buffer);
      // beacause I don't know which page and/or position
      // the doc is currently on, because of the asynchronous
      // nature of this callback.
    });
  </code></pre>
  
  <p><strong>UPDATE</strong>:</p>
  
  <p>For clarification: I want to be able to use the asynchronous trimmed image in the synchronous code for PDFKit. PDFKit only works synchronously and <code>gm</code> doesn't offer a synchronous interface.</p>
  
  <p><strong>UPDATE2</strong>:</p>
  
  <pre><code>var gm = require('gm');
  gm(some_image_as_buffer, 'image.png')
    .trim()
    .toBuffer(function(err, trimmed_image_buffer) {
      // trimmed_image_buffer is correct,
      // but I can't put it to the document like this:
      doc.image(trimmed_image_buffer);
      // beacause I don't know which page and/or position
      // the doc is currently on, because of the asynchronous
      // nature of this callback.
    });
  doc.text('some text');
  // is not guaranteed to run after image is inserted
  // and a couple of hundred lines more
  </code></pre>
  
  <p>After the last line in this example there are a lot more lines of code which add content to the PDF, but I don't want to put everything (couple of hundred lines) in one callback just because I need on asynchronous function to manipulate the image.</p>
  
  <p>Is there any way to make this manipulation synchronous?</p>