0

I am trying to generate a PDF from a PHP page. I have the code as below and it works. However, when trying to use the ob_get_clean() as I have seen others do I get a 500 error.

Ideas on other ways I can get the finished generated page? Can Javascript work?

The other issue is that the page requires a login and is also being generated by a POST form so the page can't be easily grabbed.

</html>
<?php
$content = "This will work";//ob_get_clean();
require_once dirname(__FILE__).'/html2pdf/vendor/autoload.php';

use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;

try {

    //ob_clean();
    $html2pdf = new Html2Pdf();
    $html2pdf->writeHTML($content);
    $html2pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/output.pdf', 'F');
} catch (Html2PdfException $e) {
    $formatter = new ExceptionFormatter($e);
    echo $formatter->getHtmlMessage();
}


?>

1 Answers1

0

Like that question in Stack you can use file_get_contents if your server allow fopen or use CURL (universal and best approach for me):

</html>
<?php
require_once dirname(__FILE__).'/html2pdf/vendor/autoload.php';
$content = file_get_contents('yourphppage.php'); //first option
//OR CURL MODE
$c = curl_init('yourpage.php');
curl_setopt($c, CURLOPT_RETURNTRANSFER, true);
//curl_setopt(... other options you want...)

$content = curl_exec($c);

if (curl_error($c))
    die(curl_error($c));

// Get the status code
$status = curl_getinfo($c, CURLINFO_HTTP_CODE);

curl_close($c);
//execute your code bellow checking $status of cURL, else thrown an error

use Spipu\Html2Pdf\Html2Pdf;
use Spipu\Html2Pdf\Exception\Html2PdfException;
use Spipu\Html2Pdf\Exception\ExceptionFormatter;

try {

    //ob_clean();
    $html2pdf = new Html2Pdf();
    $html2pdf->writeHTML($content);
    $html2pdf->Output($_SERVER['DOCUMENT_ROOT'] . '/output.pdf', 'F');
} catch (Html2PdfException $e) {
    $formatter = new ExceptionFormatter($e);
    echo $formatter->getHtmlMessage();
}

?>

Or you can use Javascript using jsPDF like that example in Stack:

var doc = new jsPDF();

// We'll make our own renderer to skip this editor PS: An example if you want to take out some elements from the renderer
var specialElementHandlers = {
    '#editor': function(element, renderer){
        return true;
    }
};

// All units are in the set measurement for the document
// This can be changed to "pt" (points), "mm" (Default), "cm", "in"
doc.fromHTML($('body').get(0), 15, 15, {
    'width': 170, 
    'elementHandlers': specialElementHandlers
});
Community
  • 1
  • 1
capcj
  • 1,535
  • 1
  • 16
  • 23