Html2Pdf, classe php per convertire file HTML in PDF

Venerdì, Febbraio 29, 2008 16:11 scritto da neryo

Html2Pdf, classe php per convertire file HTML in PDF

Qualche volta capita di dover convertire tramite i propri script php i file HTML in file PDF. Questo esempio mostra l’utilizzo di una classe php che utilizza in modo trasparente web services di ABCPDF o EasySW per convertire online i file sorgente HTML in documenti PDF, restituendoci un file pdf sul nostro web server.

Per la conversione esistono 2 metodi della classe HTML_TO_PDF:

  • convertHTML, che accetta una strigna contenente il codice HTML da scrivere su PDF.
  • convertURL, che accetta sempre una stringa, ma che é l’url del file da convertire.

E’ possibile chiaramente salvare il file con saveFile e inviare una richiesta di download automatico tramite il metodo downloadFile.

Qui sotto un semplice esempio di utilizzo:

  1. < ?php
  2.  
  3. require(‘html_to_pdf.inc.php’);
  4.  
  5. $htmltopdf = new HTML_TO_PDF();
  6. $htmltopdf->useURL(HKC_USE_EASYW);  // default HKC_USE_ABC other HKC_USE_EASYW$htmltopdf->saveFile("abc.pdf");
  7.  
  8. $htmltopdf->downloadFile("abc.pdf");
  9.  
  10. $result = $htmltopdf->convertHTML("<strong>MY TEST");
  11.  
  12. //$result = $htmltopdf->convertURL("http://www.google.it");
  13.  
  14. if($result==false)
  15.         echo $htmltopdf->error();
  16.  
  17. ?></strong>

La classe é stata sviluppata da un programmatore indiano di nome Harish Cahuan ed é scaricabile gratuitamente da phpclasses.org .

Per completezza e per la consultazione vi inserisco il codice php della classe, in ogni caso fate riferimento alla versione scaricabile su phpclasses per evitare di utilizzare questa versione che potrebbe diventare obsoleta.

  1. < ?php
  2.  
  3.     /**
  4.      * Genereate PDF from HTML
  5.      * @author Harish Chauhan
  6.      * @version 1.0.0
  7.      * @name HTML_TO_PDF
  8.      */
  9.  
  10.     define ("HKC_USE_ABC",1);
  11.     define ("HKC_USE_EASYW",2);
  12.  
  13.     class HTML_TO_PDF
  14.     {
  15.         var $html     = "";
  16.         var $htmlurl= "";
  17.         var $error     = "";
  18.         var $host    = "";
  19.         var $port    = 80;
  20.         var $url    = "";
  21.         var $_useurl  = "";
  22.  
  23.         var $saveFile = "";
  24.         var $downloadFile = "";
  25.         var $_cookie = "";
  26.  
  27.         function HTML_TO_PDF($html="",$useurl = HKC_USE_ABC)
  28.         {
  29.             $this->html = $html;
  30.             $this->_useurl=$useurl;
  31.         }
  32.  
  33.         function useURL($useurl)
  34.         {
  35.             $this->_useurl = $useurl;
  36.         }
  37.  
  38.         function saveFile($file="")
  39.         {
  40.             if(empty($file))
  41.                 $this->saveFile = time().".pdf";
  42.             else
  43.                 $this->saveFile =$file;
  44.         }
  45.  
  46.         function downloadFile($file="")
  47.         {
  48.             if(empty($file))
  49.                 $this->downloadFile = time().".pdf";
  50.             else
  51.                 $this->downloadFile =$file;
  52.         }
  53.  
  54.         function error()
  55.         {
  56.             return  $this->error;
  57.         }
  58.  
  59.         function convertHTML($html="")
  60.         {
  61.             if(!empty($html))
  62.                 $this->html=$html;
  63.             $htmlfile = time().".html";
  64.             $url = "http://".$_SERVER[‘SERVER_NAME’].dirname($_SERVER[‘PHP_SELF’])."/".$htmlfile;
  65.  
  66.             $this->write_file($htmlfile,$this->html);
  67.  
  68.             $return = $this->convertURL($url);
  69.             if(is_file($htmlfile))
  70.                 @unlink($htmlfile);
  71.             return $return;
  72.         }
  73.  
  74.         function convertURL($url)
  75.         {
  76.             $this->htmlurl = $url;
  77.             if($this->_useurl == HKC_USE_ABC)
  78.                 return $this->_convertABC();
  79.             elseif ($this->_useurl == HKC_USE_EASYW)
  80.                 return $this->_convertEASYW();
  81.         }
  82.  
  83.         function _convertABC()
  84.         {
  85.             $this->host = "64.39.14.230";
  86.  
  87.             $this->url = "/pdf-net/cleardoc.aspx";
  88.             $this->_sendRequest($s_POST_DATA);
  89.             $s_POST_DATA = "url=".urlencode($this->htmlurl);
  90.             $s_POST_DATA.= "&PagedOutput=on";
  91.             $s_POST_DATA.= "&AddLinks=on";
  92.             $s_POST_DATA.= "&x=30";
  93.             $s_POST_DATA.= "&y=30";
  94.             $s_POST_DATA.= "&w=550";
  95.             $s_POST_DATA.= "&h=704";
  96.             $s_POST_DATA.= "&UserName=";
  97.             $s_POST_DATA.= "&Password=";
  98.             $s_POST_DATA.= "&Timeout=15550";
  99.             $s_POST_DATA.= "&Submit=Add URL";
  100.  
  101.             $this->url = "/pdf-net/addurl.aspx";
  102.             $this->_sendRequest($s_POST_DATA);
  103.             $this->url = "/pdf-net/showdoc.aspx";
  104.             $s_POST_DATA = "";
  105.  
  106.             $pdfdata = $this->_sendRequest($s_POST_DATA);
  107.             if($pdfdata===false) return false;
  108.  
  109.             if(!empty($this->saveFile))
  110.                 $this->write_file($this->saveFile,$pdfdata);
  111.             if(!empty($this->downloadFile))
  112.                 $this->download_file($pdfdata);
  113.             return $pdfdata;
  114.         }
  115.  
  116.         function _convertEASYW()
  117.         {
  118.             //http://www.easysw.com/htmldoc/pdf-o-matic.php
  119.             $this->url= "/htmldoc/pdf-o-matic.php";
  120.             $this->host="www.easysw.com";
  121.             $s_POST_DATA = "URL=".urlencode($this->htmlurl);
  122.             $s_POST_DATA .= "&FORMAT=.pdf";
  123.             $pdfdata = @file_get_contents("http://".$this->host.$this->url."?".$s_POST_DATA);
  124.             if(!empty($pdfdata))
  125.             {
  126.                 if(!empty($this->saveFile))
  127.                     $this->write_file($this->saveFile,$pdfdata);
  128.                 if(!empty($this->downloadFile))
  129.                     $this->download_file($pdfdata);
  130.                 return true;
  131.             }
  132.  
  133.             $pdfdata = $this->_sendRequest($s_POST_DATA);
  134.             if($pdfdata===false) return false;
  135.  
  136.             if(!empty($this->saveFile))
  137.                 $this->write_file($this->saveFile,$pdfdata);
  138.             if(!empty($this->downloadFile))
  139.                 $this->download_file($pdfdata);
  140.  
  141.             return $pdfdata;
  142.         }
  143.  
  144.         function _sendRequest($s_POST_DATA)
  145.         {
  146.             if(function_exists("curl_init"))
  147.                 return $this->_sendCRequest($s_POST_DATA);
  148.             else
  149.                 return $this->_sendSRequest($s_POST_DATA);
  150.         }
  151.  
  152.         function _sendSRequest($s_POST_DATA)
  153.         {
  154.             $s_Request = "POST ".$this->url." HTTP/1.0\n";
  155.             $s_Request .="Host: ".$this->host.":".$this->port."\n";
  156.             $s_Request .="Content-Type: application/x-www-form-urlencoded\n";
  157.             $s_Request .="Content-Length: ".strlen($s_POST_DATA)."\n";
  158.             if($this->_useurl == HKC_USE_ABC && !empty($this->_cookie))
  159.                 $s_Request .="Cookie: ".$this->_cookie."\n";
  160.             $s_Request .="\n".$s_POST_DATA."\n\n";
  161.  
  162.             $fp = fsockopen ($this->host, $this->port, $errno, $errstr, 30);
  163.             if(!$fp)
  164.             {
  165.                 $this->error = "ERROR: $errno - $errstr\n";
  166.                 return false;
  167.             }
  168.             fputs ($fp, $s_Request);
  169.             while (!feof($fp)) {
  170.                 $this->GatewayResponse .= fgets ($fp, 128);
  171.             }
  172.             fclose ($fp);
  173.  
  174.             if(empty($this->_cookie))
  175.             {
  176.                 @preg_match("/ASP.NET_SessionId[^;]*/s", $this->GatewayResponse, $match);
  177.                 $this->_cookie = $match[0];
  178.             }
  179.  
  180.             @preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $this->GatewayResponse, $match);
  181.             if($this->_useurl == HKC_USE_ABC)
  182.                 @preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $match[2], $match);
  183.             $this->GatewayResponse =$match[2];
  184.  
  185.             return $this->GatewayResponse;
  186.         }
  187.  
  188.         function _sendCRequest($s_POST_DATA)
  189.         {
  190.             $ch = curl_init();
  191.             //"http://".$this->host.":".$this->port.$this->url;
  192.             curl_setopt( $ch, CURLOPT_URL, "http://".$this->host.":".$this->port.$this->url );
  193.             curl_setopt( $ch, CURLOPT_POST, 1 );
  194.             curl_setopt( $ch, CURLOPT_POSTFIELDS,$s_POST_DATA);
  195.             if($this->_useurl == HKC_USE_ABC && !empty($this->_cookie))
  196.                 curl_setopt( $ch, CURLOPT_COOKIE,$this->_cookie);
  197.             curl_setopt( $ch, CURLOPT_RETURNTRANSFER, 1 );
  198.             curl_setopt( $ch, CURLOPT_TIMEOUT,30 );
  199.             curl_setopt($ch, CURLOPT_HEADER, 1);
  200.             $this->GatewayResponse=curl_exec( $ch );
  201.             if(curl_error($ch)!="")
  202.             {
  203.                 $this->error = "ERROR: ".curl_error($ch)."\n";
  204.                 return false;
  205.             }
  206.             curl_close($ch);
  207.  
  208.             if(empty($this->_cookie))
  209.             {
  210.                 @preg_match("/ASP.NET_SessionId[^;]*/s", $this->GatewayResponse, $match);
  211.                 $this->_cookie = $match[0];
  212.             }
  213.  
  214.             @preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $this->GatewayResponse, $match);
  215.             if($this->_useurl == HKC_USE_ABC)
  216.                 @preg_match("/^(.*?)\r?\n\r?\n(.*)/s", $match[2], $match);
  217.             $this->GatewayResponse =$match[2];
  218.  
  219.             return $this->GatewayResponse;
  220.         }
  221.  
  222.         function write_file($file,$content,$mode="w")
  223.         {
  224.             $fp=@fopen($file,$mode);
  225.             if(!is_resource($fp))
  226.                 return false;
  227.             fwrite($fp,$content);
  228.             fclose($fp);
  229.             return true;
  230.         }
  231.  
  232.         function download_file($pdfdata)
  233.         {
  234.             @header("Cache-Control: ");// leave blank to avoid IE errors
  235.             @header("Pragma: ");// leave blank to avoid IE errors
  236.             @header("Content-type: application/octet-stream");
  237.             @header("Content-Disposition: attachment; filename=".$this->downloadFile);
  238.             echo $pdfdata;
  239.         }
  240.  
  241.     }
  242. ?>
1 Stella2 Stelle3 Stelle4 Stelle5 Stelle (2 voti, media: 3 di 5)
Loading ... Loading ...

14 Risposte a “Html2Pdf, classe php per convertire file HTML in PDF”

  1. tasso dice:

    18-03-2008 alle 14:41

    a me da questo errore:
    Notice: Undefined variable: s_POST_DATA in C:\Programmi\EasyPHP\www\intranet\prove\fpdf\html_to_pdf-2006-04-19\html_to_pdf.inc.php on line 88
    ERROR: Empty reply from server

  2. admin dice:

    18-03-2008 alle 14:52

  3. tasso dice:

    19-03-2008 alle 15:21

    ora con questo codice:
    useURL(HKC_USE_EASYW); //default HKC_USE_ABC other HKC_USE_EASYW

    $htmltopdf->saveFile(”abc.pdf”);

    $htmltopdf->downloadFile(”abc.pdf”);

    //$result = $htmltopdf->convertHTML(”MY TEST“);

    $result = $htmltopdf->convertURL(”http://google.com/”);

    if($result==false)

    echo $htmltopdf->error();

    ?>

    mi segnala questo errore:
    ERROR: Empty reply from server

    :(

  4. admin dice:

    19-03-2008 alle 16:02

    fai una ricerca su google con: ERROR: Empty reply from server

    sembra essere un problema inerente a CURL

  5. IT Outsourcein dice:

    11-04-2008 alle 08:41

    its really niec

  6. bob dice:

    08-05-2008 alle 08:47

    2VOaqi hi nice site thanks

  7. ale dice:

    18-11-2008 alle 11:24

    a me da questo errore
    Warning: fsockopen() [function.fsockopen]: unable to connect to 64.39.14.230:80 (Impossibile stabilire la connessione. Risposta non corretta della parte connessa dopo l’intervallo di tempo oppure mancata risposta dall’host collegato. ) in C:\www\html_to_pdf.inc.php on line 161

    Fatal error: Maximum execution time of 30 seconds exceeded in C:\www\html_to_pdf.inc.php on line 161

    devo cambiare il valore di $this->host nell’indirizzo della mia macchina?

  8. ale dice:

    18-11-2008 alle 11:26

    se metto l’indirizzo della mia macchina non mi da l’errore, ma mi restituisce pagina bianca

  9. admin dice:

    18-11-2008 alle 11:46

    ciao ale, il primo consiglio che ti posso dare è intanto comprendere come funziona la classe.. perchè è vero che è già fatta e basta usarla, ma per capire quando ci fornisce errori è necessario a volte scendere un pò nel dettaglio.

    Questa classe si appoggia a dei web services per creare il pdf e la scelta tra i due web services viene fatta da questa configurazione:

    $htmltopdf->useURL(HKC_USE_EASYW); // default HKC_USE_ABC other

    Quindi evidentemente o è cambiato l’ip del web services che stai usando o è semplicemente attualmente down. Puoi quindi usare l’altro cambiando la costante nel richiamo del metodo useURL().

    Se tu metti il tuo ip locale della tua macchina chiaramente fa una richiesta ad un web services locale che non esiste..
    spero di esserti stato di aiuto..

    a presto
    ciao, neryo

  10. ale dice:

    18-11-2008 alle 12:00

    adesso non mi da più l’errore, ma mi restituisce una pagina bianca, e il file da scaricare non me lo apre, dice che acrobat non riesce ad aprirlo perchè abc.pdf è danneggiato o non è un formato adatto… tieni presente che io al momento sto facendo test, quindi il mio codice è quello che si scarica da phpclasses come esempio… puoi aiutarmi?
    ah un’altra cosa… prima che mi ci spacco ancora il craneo, è possibile assegnare un’intestazione e un piè di pagina? non vedo metodi che lo consentono, ma ad esempio fpdf lo consente
    aspetto tue notizie, grazie

  11. admin dice:

    18-11-2008 alle 12:42

    per forza ti restituisce pagina bianca.. come ti ho detto nella riposta precedente non ha senso sostituire l ip 64.39.14.230 del metodo _convertABC() della classe con il tuo ip locale, così non potrà mai funzionare. Eventualmente puoi solo switchare il web services a cui si appoggia come ti ho indicato, o se pubblicano un nuovo ip o ancora meglio il dominio puoi cambiarlo.. ma non certamente con localhost. :)

    Per quanto riguarda le intestazioni come vedi anche tu dalla classe non cè modo di inserirle.. questa è un classe veloce utile nel caso si vogliano generare pdf da html senza troppe complicazioni, perchè il lavoro sporco viene fatto in remoto sul web services a cui ti appoggi.. ma se vuoi qualcosa di più custom allora usa classi come fpdf..

    a presto
    ciao

  12. ale dice:

    18-11-2008 alle 12:45

    non ho più localhost, cmq mi sono reso conto che non posso utilizzare delle librerie che si appoggiando ad un web services, quindi devo abbondonare questa nave.. grazie comunque ciao

  13. admin dice:

    18-11-2008 alle 13:06

    si tra l’altro cè scritto all’inizio della guida che usa i web services ;) ciao

  14. Daniele Pignedoli dice:

    04-06-2009 alle 13:09

    Raccomando anche wkhtmltopdf, ottimo per convertire html in pdf mantenendo la compatibilità con i css :)

Lascia una commento

(*) campi obbligatori

Spam protection by WP Captcha-Free