PDF from a PHP

Asked

Viewed 3,183 times

-1

What is the most practical and fast way to generate a PDF report from a PHP? I’ve seen some examples but all very confusing and always using the same method.

  • 1

    http://www.fpdf.org/

2 answers

0

The fastest way to generate PDF files by PHP is with the TCPDF class (http://www.tcpdf.org/) that renders html code and generates PDF, this solution is very simple compared to others because you do not have to write again to generate this format, simply you use your html code and ask the class to render in PDF.

Check out this link http://www.tcpdf.org, the documentation is quite rich.

I hope I’ve helped

  • Your answer will be more useful if it contains a practical example of how to use the suggested one. The way it looks like you’re promoting a product!

  • Reading here seems to be mto good the solution. I will test. Grateful.

0

The class DOMPDF is a good alternative for your purpose

It allows you to convert HTML to PDF by reading its DOM structure.

Below is an extremely simple example of its use

<?php
// Inclui a classe DOMPDF
include_once("dompdf_config.inc.php");

/**
 * Gera um arquivo PDF lendo o conteúdo HTML proveniente de uma string
 * @param string $titulo Define o título do arquivo PDF
 * @param string $html A string de origem contendo a strutura HTML a ser convertida para PDF
 * @param string $tipo Define o tipo do documento PDF (P = Retrato ou L = Paisagem
 * @return bool Retorna se o arquivo foi gerado com sucesso ou não
 */
function toPDF($titulo, $html, $tipo = "P") {
    $dompdf = new DOMPDF();

    // Define internamente o tipo do documento
    if ($tipo == "L") {
        $dompdf->set_paper("legal", "landscape");
    }

    // Carrega o $html de entrada para a classe
    $dompdf->load_html($html); 

    // "Renderiza" o conteúdo
    $dompdf->render();

    // Cria e obtém o PDF gerado
    $pdf = $dompdf->output();

    // Define o caminho onde será salvo
    $arquivo = "arquivos/" . $titulo; 
    return ( file_put_contents($arquivo,$pdf) );
}
?>

Mode of use:

<?php
// Html de teste
$html = '
    <!DOCTYPE html>
    <html>
        <head>
            <title>Teste de HTML</title>
        </head>
        <body>
            <div>Olá, mundo!</div>
        </body>
    </html>
';

// Tenta criar o arquivo PDF
toPDF("arquivo.pdf", $html);
?>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.