I have tried those but still failed to use $pdf->page_script('');. First of all before to access $pdf variable I have set def("DOMPDF_ENABLE_PHP", true); in dompdf_config.inc.php and define("DOMPDF_ENABLE_PHP", true); in dompdf_config.costum.inc.php files and then restarted Apache service. And then I found an answer relative to this question about to use $pdf->script(''); inline the code to playing with the $PAGE_NUM and $PAGE_COUNT as if(){}else{} parameters. Since I have a task about to print page number which is the potision of last page is differ with the other pages, so that I need to run specific $x $y coordinate only for last page using if(){}else{} condition.
This what I did so far:
<?php
ob_start();
session_start();
require_once("../../../php/dompdf-0.6.2/dompdf_config.inc.php");
require_once("../../../php/koneksi.php");
$dompdf = new DOMPDF(); // DOMPDF INSTANCE
$html .= "<html>";
$html .= "<head>";
$html .= "<style>
#page{
margin-top:1.19cm;
margin-bottom:1.75cm;
margin-left:2cm;
margin-right:2cm;
}
</style>";
$html .= "</head>";
$html .= "<body>";
$html .= "<script type='text/php'>
if (isset($pdf) ) {
$pdf->page_script('
$text = $PAGE_NUM . '/' . $PAGE_COUNT;
$font = Font_Metrics::get_font('Arial, Helvetica, sans-serif', 'normal');
$size = 12;
$color = array(0,0,0);
$word_space = 0.0; // default
$char_space = 0.0; // default
$angle = 0.0; // default
if ( $PAGE_NUM > 1 && $PAGE_NUM == $PAGE_COUNT) {
$x = 299;
$y = 18;
$pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
}else{
$x = 299;
$y = 860;
$pdf->page_text($x, $y, $text, $font, $size, $color, $word_space, $char_space, $angle);
}
');
}
</script>";
...
...
...
$html .= "</body>";
$html .= "</html>";
ob_get_clean();
// $dompdf->set_option("isPhpEnabled", true); // Added on 26/03/2020
$dompdf->load_html($html);
$dompdf->set_paper("folio", "portrait");
$dompdf->render();
$dompdf->stream("SK Pelaksana.pdf", array("Attachment" => false));
exit(0);
By the way I am using PHP v5.1 and domPDF v.0.6.2.
Related
I have xml in my database and wanted to generate pdf from xml, but if xml is too big then it through timeout error. I don't want to change my server timeout instead of how to improve the timing of pdf generate.
I am using <pre> tag for good formatting.
Below code for pdf generate
public function generateCreditReport($form, $path=false, $htmlPath=false){
$this->load->library('fpdf/fpdf');
$this->load->library('fpdi/fpdi');
if(!empty($path) && !file_exists($path)){
$data['form'] = $form;
$data['date'] = $data['xml'] = null;
if($data['form']->credit_report != ''){
try{
$data['xml'] = new SimpleXMLElement($data['form']->credit_report);
}catch(Exception $e){
}
$timeStatus = $this->admin->get_timestamp($data['form']->id, 'credit_pulled');
if(!empty($timeStatus)) {
$data['date'] = $timeStatus->date;
}
}
$pdf = new TCPDF();
$pdf->SetFont('Helvetica');
$pdf->SetFontSize(10);
$pdf->SetTextColor(0, 0, 0);
$pdf->SetProtection(array('print','modify'),"$form->loan_id","sefinance",0);
$pdf->AddPage();
$html = $this->load->view('admin/credit_report_pdf', $data,true);
$generatedReport = file_put_contents($htmlPath, $html , FILE_APPEND | LOCK_EX);
$pdf->WriteHTML($html);
if($path){
$pdf->Output($path, "F");
}else{
$pdf->Output();
}
}
}
View file credit_report_pdf is as below
<h4>Report Results</h4>
<br>
<?php if(!empty($xml)){ ?>
<?php echo print_credit($xml->EfxReport->USPrintImage); ?>
<?php } ?>
I am formatting using <pre> to look good.
function print_credit($report) {
$split = " <div style='page-break-before: always;'></div>" . repeater(' ', 43);
$report = preg_replace('/\* \* \*[\s\S]+?USER REF./', $split, $report);
$output = "";
$output = '<pre>';
$length = strlen($report);
$count = $length / 81;
$position = 1;
for ($i = 0; $i < $count; $i++) {
if (strpos(substr($report, $position, 80), 'THIS FORM PRODUCED BY EQUIFAX') === FALSE) {
$output .= substr($report, $position, 80) . '<br>';
}
if ($i == 32) {
$output .= '</pre><pre>';
}
$position += 81;
}
$output .= '</pre>';
return $output;
}
Here is screenshot how pdf looks like.
Please help me to improve the timing of pdf, currently taking more than 10min for 10-page pdf.
I have a problem to put text into a image.
I have all letters in images on my folder named tekst.
Lets say I use $userinfo->name to get the user name and in this case the user is named zippo
Then I want the users name to return following HTML output:
<img src="tekst/z.png"><img src="tekst/i.png"><img src="tekst/p.png"><img src="tekst/p.png"><img src="tekst/o.png">
How can I do it with PHP to change each letter in the name to <img src="tekst/?.png>.
You can use this:
<?php
$name = "zippo";
for ($i = 0; $i < strlen($name); $i++) {
echo '<img src="tekst/' . $name[$i] . '.png">';
}
?>
Use str_split() function on your string and loop over result array as follows:
$letters = str_split($string);
foreach ($letters as $letter) {
echo '<img src="tekst/' . $letter . '.png" />';
}
try this one
$letters = str_split($string);
foreach ($letters as $letter) {
echo '<img src=".../tekst/' . $letter . '.png" />';
}
First you have to create a php file to convert your text to image :
<?php
/* image.php */
// Receive data
$char = $_GET['char'];
if(!empty($char)){
// This will get the first character from $char
$char = $char;
// Create a 100*30 image
$im = imagecreate(100, 30);
// White background and blue text
$bg = imagecolorallocate($im, 255, 255, 255);
$textcolor = imagecolorallocate($im, 0, 0, 255);
// Write the string at the top left
imagestring($im, 5, 0, 0, $char, $textcolor);
// Output the image
header('Content-type: image/png');
imagepng($im);
imagedestroy($im);
}
?>
Image String http://php.net/manual/en/function.imagestring.php
Then split its name into chars
<?php
$string = 'abcdefgh'; // For example
$chars = str_split($string);
foreach ($chars as $char) {
echo '<img src="tekst/image.php?char='.$char.'"/>';
}
?>
str_split http://php.net/manual/en/function.str-split.php
GOOD LUCK
my code:
save this file as captcha.php
<?php
ob_start();
session_start();
if(!isset($_POST['submit'])){
echo "<form method=\"post\" action=\"captcha.php\">\n";
echo "<table border=\"0\" cellspacing=\"3\" cellpadding=\"3\">\n";
echo "<tr><td>Type The Letters You See Below Into the Box</td></tr>\n";
echo "<tr><td align=\"center\"><img src=\"image.php\"></td></tr>\n";
echo "<tr><td align=\"center\"><input type=\"text\" name=\"image\"></td></tr>\n";
echo "<tr><td align=\"center\"><input type=\"submit\" name=\"submit\" value=\"Check CAPTCHA\"></td></tr>\n";
echo "</table></form>\n";
}else {
$image = $_POST['image'];
if ($image == $_SESSION['string'])
{
echo "<b>Great success!</b>\n";
}
else
{
echo "<em>Failure!</em>\n";
}
}
ob_end_flush();
?>
save this file as image.php
<?php
session_start();
$img = imagecreatetruecolor(118,80);
$white = imagecolorallocate($img, 255, 255, 255);
$black = imagecolorallocate($img, 0, 0, 0);
$red = imagecolorallocate($img, 255, 0, 0);
$grey = imagecolorallocate($img,150, 150, 150);
$pink = imagecolorallocate($img, 200, 0, 150);
$yellow = imagecolorallocate($img, 255, 246, 0);
function randomString($length){
$chars = "abcdefghijkmnopqrstuvwxyz023456789";
srand((double)microtime()*1000000);
$str = "";
$i = 0;
while($i <= $length){
$num = rand() % 33;
$tmp = substr($chars, $num, 1);
$str = $str . $tmp;
$i++;
}
return $str;
}
for($i=1;$i<=rand(1,5);$i++){
$color = (rand(1,2) == 1) ? $pink : $red;
imageline($img,rand(6,90),rand(6,40), rand(6,90)+6,rand(6,40)+6, $color);
}
imagefill($img, 0, 0, $yellow);
$string = randomString(rand(4,6));
$_SESSION['string'] = $string;
imagettftext($img, 20, 10, 10, 52, $black, "calibri.ttf", $string);
imagettftext($img, 20, 10, 12, 53, $grey, "calibri.ttf", $string);
header("Content-type: image/png");
imagepng($img);
imagedestroy($img);
?>
go to this address http://www.cufonfonts.com/en/font/12048/calibri and download the font and save it in the same root folder as the to .php files we just created.
NOTE!! THIS WILL WORK ON LOCALHOST BUT IM HAVING A PROBLEM WITH THE image.php file SHOWING UP LIKE THIS -> ����JFIF��>CREATOR: gd-jpeg v1.0 (using IJG JPEG v90), default quality ��C $.' ",#(7),01444'9=82<.342��C 2!!22222222222222222222222222222222222222222222222222��x"�����}!1AQa"q2���#B��R��$3br� .
THIS ONLY HAPPENS WHEN I TRY AND ADD IT TO THE CMS I CREATED. ALL I NEED TO KNOW IS WHY THIS IS HAPPENING I HAVE A FEELING ITS GOT SOMETHING TO DO WITH "header("Content-type: image/png");" although i could be way wrong. please help me. by the way im am trying to add a email form and have the captcha evaluate it
this is the form i am trying to insert the code into:
you can save it as form.php
<?php
$query = mysql_query("SELECT * FROM forms where id = '$formid'");
echo '<h2>'.mysql_result($query, 0, "title").'</h2>';
if(mysql_result($query, 0, "description") != "") {
echo '<p>'.mysql_result($query, 0, "description").'</p>';
}
error_reporting(E_ERROR);
?>
<form action="plugins/form_send.php" method="post" enctype="multipart/form-data" class="ajax" name="formplugin" id="form_<?php echo $formid; ?>">
<input name="formid" id="formid" type="hidden" value="<?php echo $formid; ?>" />
<p><span class="required">*</span> = required fields.</p>
<table border="0" cellspacing="5" cellpadding="5">
<?php
$field_labels_col = mysql_result($query, 0, "field_label");
$field_labels = array();
$field_labels =(explode('|', $field_labels_col));
$field_types_col = mysql_result($query, 0, "field_type");
$field_types = array();
$field_types =(explode('|', $field_types_col));
$field_option1_col = mysql_result($query, 0, "field_option1");
$field_option1 = array();
$field_option1 =(explode('|', $field_option1_col));
$field_option2_col = mysql_result($query, 0, "field_option2");
$field_option2 = array();
$field_option2 =(explode('|', $field_option2_col));
$field_validtype_col = mysql_result($query, 0, "field_validtype");
$field_validtype = array();
$field_validtype =(explode('|', $field_validtype_col));
$i = 0;
while (array_key_exists($i, $field_labels))
{
if(!isset($title)) { $title = ''; }
if($title != $field_labels[$i]) {
if(isset($field_labels[$i])) { $title = $field_labels[$i]; }
if(isset($title)) { $stripped = urlify($title); }
if(isset($field_types[$i])) { $type = $field_types[$i]; }
if(isset($field_option1[$i])) { $option1 = $field_option1[$i]; }
if(isset($field_option2[$i])) { $option2 = $field_option2[$i]; }
if(isset($field_validtype[$i])) { $valid = $field_validtype[$i]; }
echo '<tr>';
echo '<td align="left" valign="top">'.$title.'</td>';
echo '<td align="left" valign="top">';
// -- INPUT FIELDS --
if($type == "input") {
echo '<input name="'.$stripped.'" type="text" id="'.$stripped.'" size="'.$option1.'" maxlength="'.$option2.'" />';
if($valid != '') { echo '<span class="required">*</span>'; }
}
// -- TEXT AREAS --
if($type == "textarea") {
echo '<textarea name="'.$stripped.'" cols="'.$option1.'" rows="size="'.$option2.'"" id="'.$stripped.'"></textarea>';
}
// -- DROP DOWNS --
if($type == "dropdown") {
echo '<select name="'.$stripped.'" id="'.$stripped.'">';
$l = 0;
while (array_key_exists($l, $field_labels))
{
$thisoption = $field_option1[$l];
$thistitle = $field_labels[$l];
if($thistitle == $title) {
echo '<option value="'.$thisoption.'">'.$thisoption.'</option>';
}
$l++;
}
echo'</select>';
}
// -- RADIO BUTTONS --
if($type == "radiobutton") {
$l = 0;
while (array_key_exists($l, $field_labels))
{
$thisoption = $field_option1[$l];
$thistitle = $field_labels[$l];
$thisstripped = urlify($field_labels[$l]);
if($thistitle == $title) {
echo '<label><input type="radio" name="'.$thistitle.'" id="'.$thisstripped.'" value="'.$option1.'">'.$thisoption.'</label><br />';
}
$l++;
}
}
// -- SIMPLE YES / NO --
if($type == "yesno") {
echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="Yes">Yes</label>';
echo '<label><input type="radio" name="'.$stripped.'" id="'.$stripped.'" value="No">No</label>';
}
// -- FILE UPLOADS --
if($type == "fileupload") {
echo '<input type="file" name="'.$stripped.'" id="'.$stripped.'" size="10"> (2mb limit)';
}
echo '</td>';
echo '</tr>';
}
$i++;
}
?>
<tr id="comment-div"><td colspan="2"><input name="user-comment" size="3" value="" /></td></tr>
<tr>
<td colspan="2">
<?php if(mysql_result($query, 0, "submit_text") != "") { ?>
<p><br /><?php echo mysql_result($query, 0, "submit_text"); ?></p>
<?php } ?>
<div id="result"><strong>Loading... please wait.</strong></div>
<!-- <input type="submit" name="button" id="button" value="<?php echo mysql_result($query, 0, "submit_button"); ?>" /> -->
</td>
</tr>
</table>
</form>
I guess the code you posted is not the whole file: try to remove all the content before and after <?php and ?> tags. You could even remove the final tag ?> (it is a style convention adopted by many, because of this very issue).
This affects every other file you are executing: every space, newline or other content outside the PHP tags or echoed by PHP is added to the image content, and ends up with the image corruption. Also PHP notices and warnings are an issue.
For clarity, the executed files format must be:
<?php // nothing before this line
// no other PHP tags till the end
... // PHP code with no echo calls
// no closing tag
In your code, you do:
header( "Content-type: image/png" );
# ...
echo "<img src='image/png;base64," . base64_encode( $x )."'>";
You are outputting a PNG sorrounding it with HTML, which inevitably corrupts your image content. You have to remove the HTML (echo $x) and use the image from another file, f.e. with
<img src="png_generator_script.php"/>
Or use the script as HTML page, removing
header( "Content-type: image/png" );
i was faced same problem . Remove all html tag it will 100% work..
save as php file .. index.php
<?php
/**
* PHP GD
* create a simple image with GD library
*
*/
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = #imagecreate(800, 600)
or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300, "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>
instead of...
<html>
<head>
</head>
<body>
<?php
/**
* PHP GD
* create a simple image with GD library
*
*/
//setting the image header in order to proper display the image
header("Content-Type: image/png");
//try to create an image
$im = #imagecreate(800, 600)
or die("Cannot Initialize new GD image stream");
//set the background color of the image
$background_color = imagecolorallocate($im, 0xFF, 0xCC, 0xDD);
//set the color for the text
$text_color = imagecolorallocate($im, 133, 14, 91);
//adf the string to the image
imagestring($im, 5, 300, 300, "I'm a pretty picture:))", $text_color);
//outputs the image as png
imagepng($im);
//frees any memory associated with the image
imagedestroy($im);
?>
</body>
</html>
This code is working fine. I have tested it locally on chrome & firefox.
This is my code
<?php
class Diagram
{
function outLet()
{
$boothsizer = 3;
if($boothsizer == 3){
$cellWidth = '112px';
$cellHeight = '52px';
$innerDivElectricTop = '41px';
$innerDivElectricLeft = '110px';
$backgroundImage = 'url(booth_top_images/5X20TOP.jpg)';
$width = '900px';
$height = '225px';
$sidewalls = 2;
$backwalls = 6;
}
else
if($boothsizer == 19)
{
$cellWidth = '144px';
$cellHeight = '145px';
$innerDivElectricTop = '105px';
$innerDivElectricLeft = '73px';
$backgroundImage = 'url(booth_top_images/10X10TOP.jpg)';
$width = '599px';
$height = '605px';
$sidewalls = 3;
$backwalls = 3;
}
$innerDivElectricWidth = $backwalls * $cellWidth;
$innerDivElectricHeight = $sidewalls * $cellHeight;
$output = '<div style="width:'.$width.'; height:'.$height.'; background-image:'.$backgroundImage.'">';
$output .= '<div id="inner_div_electric" style="position: relative; top: '.$innerDivElectricTop.'; left: '.$innerDivElectricLeft.';width:'.$innerDivElectricWidth.';height:'.$innerDivElectricHeight.'">';
for($i=1; $i<=$sidewalls; $i++)
{
for($j=1; $j<=$backwalls; $j++)
{
$output .= '<span class="droppable_class" style="width:'.($cellWidth-2).'; height:'.($cellHeight-2).'; border:1px solid red; float:left;display:inline-block;margin:0px;padding:0px;"></span>';
}
}
$output .= '</div></div>';
echo $output;
include("test/mpdf/mpdf.php");
$mpdf=new mPDF();
$mpdf->ignore_invalid_utf8 = true;
$stylesheet = file_get_contents('appstyle_pdf.css');
$mpdf->WriteHTML($stylesheet,1);
$mpdf->WriteHTML($output);
$comname = "vam";
$name = "test/generated_pdfs/".str_replace(" ","-",$comname).".pdf";
$mpdf->Output($name,"F");
}
}
$diag = new Diagram;
print $diag->outLet();
?>
In my code I am trying to generate some squares upon images and trying to generate a pdf, when I echoed the $output I can see squares on images, but in my generated pdf only the image is printing, squares are not?
Anybody any ideas???
Change the <span> tags to <div> tags and it should work.
Unfortunately I don't have any explaination for the solution at the moment. According the mpdf script <span> tags are part of the enabledtags collection - mpdf.php Line 23249. So I'm not totally sure why <div> works and <span> doesn't.
I am using the dompdf library of php to generate PDF report from an HTML template. In that html template there is a section table of contents. When genrating PDF i need to update the page number of table of contents. Does anyone know how I can achieve this in dompdf library of php?
Thanks in advance.
I have achieved this in Drupal and guess it works on other php opensource and frameworks as well.
I have kept this code inside script tag
$GLOBALS['entity_page'][] = $pdf->get_page_number();
in template that stores the page number. Template is with extension tpl.php
Now in the module
after other codes for export I have added......
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "normal");
$canvas->page_text(520, 805, "Page {PAGE_NUM}", $font, 9, array(0.4, 0.4, 0.4));
foreach ($GLOBALS['entity_page'] as $key => $val) {
$GLOBALS["entity_val"] = 0;
$GLOBALS["entity_y"] = 110;
$canvas->page_script('if($PAGE_NUM == 3 && $PAGE_NUM < 4){
$font = Font_Metrics::get_font("helvetica", "normal");
$x = 380;
$y = $GLOBALS["entity_y"];
$pdf->text($x, $y, "-------------------------".$GLOBALS["entity_page"][$GLOBALS["entity_val"]]."", $font, 12, array(0, 0, 0, 0.8));
$GLOBALS["entity_y"] = $GLOBALS["entity_y"] + 33;
$GLOBALS["entity_val"] = $GLOBALS["entity_val"] + 1;
}');
}
$pdf->text this part adds the page numbers with constant increment in y axis position. Other global variables entity_y and entity_val are used to store the values.
Generating a Table of Contents from HTML (with h1,h2,h3), I did the following:
First give every header an unique ID (because we are using PrinceXML) and is a good pratice.
Then create an OL/LI structure of it, although that piece of code can contain bugs.
$matches = null;
$smatches = null;
$had_headers = array();
preg_match_all('/<h[0-9].*?>.*?<\/h[0-9]>/i', $content, $matches);
if (!empty($matches[0]) && count($matches[0]) > 0)
foreach ($matches[0] as $headertag) {
preg_match('/>(.*?)<\/(h[0-9])>/i', $headertag, $smatches);
if (!empty($smatches[1]) && count($smatches[1]) > 0) {
$headerid = strip_tags($headertag);
$headerid = trim(strtolower(preg_replace('/[^a-z0-9]/i', '', $headerid)));
$smatches[2] = strtolower($smatches[2]);
$header_depth = intval(trim(str_ireplace('h', '', $smatches[2])));
while (in_array($headerid, $had_headers)) {
$headerid .= '1';
}
$had_headers[] = $headerid;
$content = str_replace($headertag, '<'. $smatches[2] . ' id="' . htmlentities($headerid) . '">' . $smatches[1] . '</' . $smatches[2] . '>', $content);
}
}
$matches = null;
$smatches = null;
$toc_html = '<ol id="toc">' . "\n";
$old_depth = 0;
$hadfirst = false;
preg_match_all('/<h[0-9].*?>.*?<\/h[0-9]>/i', $content, $matches);
if (!empty($matches[0]) && count($matches[0]) > 0)
for ($i=0; $i < count($matches[0]); $i++) {
$headertag = $matches[0][$i];
preg_match('/<h[0-9][^>]*?id="(.*?)".*?>(.*?)<\/(h[0-9])>/i', $headertag, $smatches);
if (!empty($smatches[1]) && count($smatches[1]) > 0) {
$headerid = trim($smatches[1]);
$header_depth = intval(trim(str_ireplace('h', '', $smatches[3]))) - 1;
// don't take heigher than h3 in TOC
if ($header_depth > 2)
continue;
if ($header_depth < $old_depth) {
$diff = $old_depth - $header_depth; //if going multiple levels up
$toc_html .= '</li>'.str_repeat('</ol></li>', $diff);
} elseif ($header_depth > $old_depth) {
$toc_html .= '<ol>';
} else {
$toc_html .= ($hadfirst) ? '</li>' : null;
}
$toc_html .= '<li>' . htmlentities(trim(strip_tags($smatches[2]))) . '';
$old_depth = $header_depth;
$hadfirst = true;
}
}
$toc_html .= str_repeat('</li></ol>', ($old_depth + 1));
You may have solved this already? I've not used dompdf, but i did a similar thing in Zend_Pdf: I made a blank page for the table of contents and then went on creating all the other later pages, keeping an array of page_number => title. At the end I went back and updated the contents page using the reference saved earlier...
As an extension to vicky shrestha's answer here is what I have for a table of contents that expands more than a single page.
36 is just an arbitrary number of items that fit in the design.
foreach ($GLOBALS['entity_page'] as $key => $val) {
$GLOBALS["entity_y"] = 88;
$GLOBALS["entity_val"] = 0;
$GLOBALS["entity_per_page"] = 36;
if($val) {
$canvas->page_script('
if(isset($GLOBALS["entity_page"][$GLOBALS["entity_val"]])) {
if($PAGE_NUM == $GLOBALS["entity_page_number"]){
$x = 505;
$y = $GLOBALS["entity_y"];
$font = $fontMetrics->get_font("Open Sans", "Helvetica Neue", "Helvetica, Arial, sans-serif");
$pdf->text($x, $y, $GLOBALS["entity_page"][$GLOBALS["entity_val"]]."", $font, 7, array(0, 0, 0, 1));
$GLOBALS["entity_y"] = $GLOBALS["entity_y"] + 19;
$GLOBALS["entity_val"] = $GLOBALS["entity_val"] + 1;
if (($GLOBALS["entity_val"] + 1) % $GLOBALS["entity_per_page"] == 0 ) {
$GLOBALS["entity_page_number"] = $GLOBALS["entity_page_number"] + 1;
$GLOBALS["entity_y"] = 31;
}
}
}');
}
}
the isset is important as for some reason the foreach will loop an additional time and you will get an out of bounds exception thrown at the end.
My idea to create TOC in pdf is following:
generate pdf where title of page would contain random token instead of name
parse generated pdf (using Smalot\PdfParser) and find page number which contains the token
generate the pdf where replace tokens with real name and found page number.
Example:
$html = "<html>
<div class='toc'>
<a>Article1 ..... {article_1_num}</a>
</div>
...
<div class='article'>
<div>{article_1_title}</div>
<div>Article content</div>
</div>
</html>";
//prepare variables to replace in template with random token
$vars = ["{article_1_title}"=>'676TGZGHVGFTRR655R66TTFTF', "{article_1_num}"=>0];
//genetate pdf
$options = new Options();
$options->set('defaultFont', 'Courier');
$options->set('isRemoteEnabled', TRUE);
$options->set('debugKeepTemp', TRUE);
$options->set('isPhpEnabled', TRUE);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
//load html with variables replaced
$dompdf->loadHtml(strtr($html, $vars));
$dompdf->setPaper('A4');
#$dompdf->render();
//create tamporary file
$temp = tempnam(sys_get_temp_dir(), 'prefix');
$output = $dompdf->output();
//save to temporary file
file_put_contents($temp, $output);
// parse pdf
$parser = new \Smalot\PdfParser\Parser();
$pdf = $parser->parseFile($temp);
$pages = $pdf->getPages();
$pageNum = 0;
//loop the pages and find the one with the token
foreach ($pages as $k=>$page) {
if(strpos($page,'676TGZGHVGFTRR655R66TTFTF') !== false){
$pageNum = $k+1;
break;
}
}
// remove temp file
unlink($temp);
//prepare variables with real values to replace in template
$vars = ["{article_1_title}"=>'Article no. 1', "{article_1_num}"=>$pageNum];
// generate pdf and stream it to user
$options = new Options();
$options->set('defaultFont', 'Courier');
$options->set('isRemoteEnabled', TRUE);
$options->set('debugKeepTemp', TRUE);
$options->set('isPhpEnabled', TRUE);
$options->set('isHtml5ParserEnabled', true);
$dompdf = new Dompdf($options);
//load html with variables replaced
$dompdf->loadHtml(strtr($html, $vars));
$dompdf->setPaper('A4');
#$dompdf->render();
$dompdf->stream("pdf.pdf", array('Attachment' => 0));