private static byte[] toPDF(final byte[] tex) throws IOException {

    // find command
    synchronized (PDF_LATEX_ARGS) {
      if (pdfLaTeX == null) {
        final File mac = new File("/usr/texbin/pdflatex");
        if (mac.canExecute()) {
          pdfLaTeX = mac.getPath();
        } else {
          final String other = Programs.which("pdflatex");
          if (other == null) throw new IOException(
              "Can't find 'pdflatex', please check your "
                  + "PATH environment variable.");
          pdfLaTeX = other;
        }
      }
    }

    final File temp = IOUtils.tempFile(tempDir, "tex");
    final FileOutputStream fos = new FileOutputStream(temp);
    try {
      fos.write(tex);
    } finally {
      fos.close();
    }

    // create a subprocess for pdflatex and send it the TEX file
    final String[] args = PDF_LATEX_ARGS.clone();
    args[0] = String.format(args[0], temp.getName());

    try {
      IOUtils.exec(pdfLaTeX, args, null, tempDir);
    } catch (final InterruptedException e) {
      throw new IOException(e);
    }

    final File pdf = new File(temp.getPath().replaceFirst("\\.tex$", ".pdf"));

    return IOUtils.readFully(pdf);
  }