<?php if (!defined('PmWiki')) exit();
/*  Copyright 2005, 2006 Patrick R. Michaud (pmichaud@pobox.com)
    This file is generatepdf.php; you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published
    by the Free Software Foundation; either version 2 of the License, or
    (at your option) any later version.  

    This module adds ?action=pdf to PmWiki.  It relies on the
    existence of a program to convert html to PDF, such as
    htmldoc (www.htmldoc.org).  To use this recipe, install this
    file into the cookbook/ directory, then add the following
    to a local customization file:

        $HtmlToPdfCmd = "/path/to/htmldoc -t pdf --quiet --webpage";
        include_once('cookbook/generatepdf.php');

    where $HtmlToPdfCmd is the command to be used to generate
    a PDF file from HTML input.  (The recipe automatically appends
    the name of the file containing the html input to this command.)

    By default this recipe uses the 'print' skin, this can be changed
    by setting $ActionSkin['pdf'].
*/

SDV($RecipeInfo['GeneratePDF']['Version'], '2006-09-07');

SDV($HandleActions['pdf'], 'HandlePDF');
SDV($ActionSkin['pdf'], 'print');

function HandlePDF($pagename, $auth='read') {
  global $HandleActions, $WorkDir, $HtmlToPdfCmd;

  SDV($HtmlToPdfCmd, 'htmldoc -t pdf --quiet --webpage');

  ob_start();
  $browse = $HandleActions['browse'];
  $browse($pagename, $auth);
  $html = ob_get_contents(); 
  ob_end_clean();

  $tname = tempnam($WorkDir, "tmp");
  if ($tfp=fopen($tname, "w")) { fputs($tfp, $html); fclose($tfp); }

  putenv('HTMLDOC_NOCGI=1');

  header("Content-type: application/pdf");
  flush();
  passthru("$HtmlToPdfCmd $tname");
  @unlink($tname);
}