HTML on image not printing in pdf - php

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.

Related

Generating pdf from XML response taking so much time

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.

XML parsing in php

I am parsing a xml and but there is a tag which contain image and text both and i want to seprate both image and text in diffrent columns of table in my design layout but i dont know how to do it. please help me. my php file is :
<?php
$RSS_Content = array();
function RSS_Tags($item, $type)
{
$y = array();
$tnl = $item->getElementsByTagName("title");
$tnl = $tnl->item(0);
$title = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("link");
$tnl = $tnl->item(0);
$link = $tnl->firstChild->textContent;
$tnl = $item->getElementsByTagName("description");
$tnl = $tnl->item(0);
$img = $tnl->firstChild->textContent;
$y["title"] = $title;
$y["link"] = $link;
$y["description"] = $img;
$y["type"] = $type;
return $y;
}
function RSS_Channel($channel)
{
global $RSS_Content;
$items = $channel->getElementsByTagName("item");
// Processing channel
$y = RSS_Tags($channel, 0); // get description of channel, type 0
array_push($RSS_Content, $y);
// Processing articles
foreach($items as $item)
{
$y = RSS_Tags($item, 1); // get description of article, type 1
array_push($RSS_Content, $y);
}
}
function RSS_Retrieve($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
RSS_Channel($channel);
}
}
function RSS_RetrieveLinks($url)
{
global $RSS_Content;
$doc = new DOMDocument();
$doc->load($url);
$channels = $doc->getElementsByTagName("channel");
$RSS_Content = array();
foreach($channels as $channel)
{
$items = $channel->getElementsByTagName("item");
foreach($items as $item)
{
$y = RSS_Tags($item, 1);
array_push($RSS_Content, $y);
}
}
}
function RSS_Links($url, $size = 15)
{
global $RSS_Content;
$page = "<ul>";
RSS_RetrieveLinks($url);
if($size > 0)
$recents = array_slice($RSS_Content, 0, $size + 1);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0) continue;
$title = $article["title"];
$link = $article["link"];
$img = $article["description"];
$page .= "$title\n";
}
$page .="</ul>\n";
return $page;
}
function RSS_Display($url, $click, $size = 8, $site = 0, $withdate = 0)
{
global $RSS_Content;
$opened = false;
$page = "";
$site = (intval($site) == 0) ? 1 : 0;
RSS_Retrieve($url);
if($size > 0)
$recents = array_slice($RSS_Content, $site, $size + 1 - $site);
foreach($recents as $article)
{
$type = $article["type"];
if($type == 0)
{
if($opened == true)
{
$page .="</ul>\n";
$opened = false;
}
$page .="<b>";
}
else
{
if($opened == false)
{
$page .= "<table width='369' border='0'>
<tr>";
$opened = true;
}
}
$title = $article["title"];
$link = $article["link"];
$img = $article["description"];
$page .= "<td width='125' align='center' valign='middle'>
<div align='center'>$img</div></td>
<td width='228' align='left' valign='middle'><div align='left'><a
href=\"$click\" target='_top'>$title</a></div></td>";
if($withdate)
{
$date = $article["date"];
$page .=' <span class="rssdate">'.$date.'</span>';
}
if($type==0)
{
$page .="<br />";
}
}
if($opened == true)
{
$page .="</tr>
</table>";
}
return $page."\n";
}
?>
To separate the image and description you need to parse the HTML that is stored inside the description element again as XML. Luckily it is valid XML inside that element, therefore you can do this straight forward with SimpleXML, the following code-example take the URL and converts each item *description* into the text only and extracts the src attribute of the image to store it as the image element:
<item>
<title>Fake encounter: BJP backs Kataria, says CBI targeting Modi</title>
<link>http://ibnlive.in.com/news/fake-encounter-bjp-backs-kataria-says-cbi-targeting-modi/391802-37-64.html</link>
<description>The BJP lashed out at the CBI and questioned its 'shoddy investigation' into the Sohrabuddin fake encounter case.</description>
<pubDate>Wed, 15 May 2013 13:48:56 +0530</pubDate>
<guid>http://ibnlive.in.com/news/fake-encounter-bjp-backs-kataria-says-cbi-targeting-modi/391802-37-64.html</guid>
<image>http://static.ibnlive.in.com/ibnlive/pix/sitepix/05_2013/bjplive_kataria3.jpg</image>
</item>
The code-example is:
$url = 'http://ibnlive.in.com/ibnrss/top.xml';
$feed = simplexml_load_file($url);
$items = $feed->xpath('(//channel/item)');
foreach ($items as $item) {
list($description, $image) =
simplexml_load_string("<r>$item->description</r>")
->xpath('(/r|/r//#src)');
$item->description = (string)$description;
$item->image = (string)$image;
}
You can then import the SimpleXML into a DOMElement with dom_import_simplexml() however honestly, I just would wrap that little HTML creation as well into a foreach of SimpleXML because you can make use of LimitIterator for the paging as well as you could with DOMDocument and the data you access is actually easily at hand with SimpleXML, it's just easy to pass along the XML elements as SimpleXMLElements instead of parsing into an array first and then processing the array. That's moot.

Wordpress is generating thumbnails at 400px x 300px how do I change this to 210px x 210px

I have a theme that displays posts as a thumbnail using the code below but it is cropping it at the wrong ratio (400px x 300px) and I can't figure out what's telling it to do that. How would I change the thumbnails to be generated at 210px x 210px?
<?php
foreach($all_photo_arr as $key => $portfolio_item)
{
$cur_post++;
$image_url = '';
if(has_post_thumbnail($portfolio_item->ID, 'portfolio2'))
{
$image_id = get_post_thumbnail_id($portfolio_item->ID);
$image_url = wp_get_attachment_image_src($image_id, 'portfolio2', true);
$full_image_url = wp_get_attachment_image_src($image_id, true);
}
$last_class = '';
$line_break = '';
if(($key+1) % 4 == 0)
{
$last_class = ' last';
$line_break = '<br class="clear"/>';
}
$portfolio_link_url = get_post_meta($portfolio_item->ID, 'portfolio_link_url', true);
if(empty($portfolio_link_url))
{
$permalink_url = get_permalink($portfolio_item->ID);
}
else
{
$permalink_url = $portfolio_link_url;
}
$portfolio_item_class = 'one_fourth';
if(($key+1) % 4 == 0)
{
$portfolio_item_class.= ' last';
}
$pp_portfolio_image_height = 210;
?>
You can change the thumbnail size in Settings > Media.
This might help:
http://wordpress.org/support/topic/change-featured-image-size-only-on-homepage

How to code php function or set parameters to return NO height values for images?

This question comes from this How to proportionally size images to fit dimensions of 200px x 150px thumbnail in css?, but since I feel it`s not a CSS related question anymore I thought I would create a new question. I am trying to proportionally fit images into thumbnails here http://giantmango.com/contest. I tried setting the css img tag to the below, but all images have the size of 200px x 200px. There is not another css line that has 200px as a height. I am suspecting it is something else.
img {
max-height: 150px;
max-width: 200px;
}
This function is called to return the images and thinking it might be this.
<?php
$content = get_the_content('Concept');
$content = apply_filters('the_content', $content);
list($col_class, $grid_img) = adjust_grid_image(
$content,
$col_w,
$gap_w,
$max_col,
$flg_img_forcelink,
$flg_obj_fit
);
?>
<div <?php post_class('grid-item ' . $col_class); ?> id="post-<?php the_ID(); ?>">
<?php if ($grid_img) echo '<div class="grid-image">' . $grid_img . '</div>'; ?>
These are the parameters that I have it set to.
$col_w = 200; // width of grid column
$gap_w = 7; // padding + margin-right (15+15+5)
$max_col = 5; // max column size (style div.x1 ~ xN)
$flg_img_forcelink = true; // add/overwrite a link which links to a single post (permalink).
$flg_img_extract = true; // in single post page, extract thumbnail link to an original image.
$flg_obj_fit = 'large-fit'; // none | small-fit | large-fit ... how to fit size of object tag.
This is the functions.php file that runs adjust_grid_image, but I am unsure of what it is doing. Is this setting my images to 200px x 200px? If so, what parameter must I change in order for it to not hardcode 200px as the height of images so I can set it in the css?
/*
* return class name and image tag (resized w/h attributes) to fit a grid.
*/
function adjust_grid_image($content, $col_w, $gap_w, $max_col, $flg_img_forcelink, $flg_obj_fit) {
global $post;
$col_class_base = 'x';
$col_class = $col_class_base . '1'; // default column-width class
$arr_w = array();
for ($i=0; $i<$max_col; $i++) {
$arr_w[] = ($col_w * ($i+1)) + ($gap_w * $i);
}
$grid_img = '';
$w = $h = 0;
$matches1 = $matches2 = $matches3 = array();
// search *first* img/object tag
preg_match('/<(img|object)(?:[^>]+?)>/', $content, $matches1);
if ($matches1[1] == 'img') {
preg_match('/<img(?:.+?)src="(.+?)"(?:[^>]+?)>/', $content, $matches2);
$img_url = ($matches2[1]) ? $matches2[1] : '';
if ($img_url) {
// first, try to get attributes
$matches_w = $matches_h = array();
preg_match('/width="([0-9]+)"/', $matches2[0], $matches_w);
preg_match('/height="([0-9]+)"/', $matches2[0], $matches_h);
if ($matches_w[1] and $matches_h[1]) {
$w = $matches_w[1];
$h = $matches_h[1];
}
else {
// ... or get original size info.
$upload_path = trim( get_option('upload_path') );
$mark = substr(strrchr($upload_path, "/"), 1); // default mark is 'uploads'
preg_match("#$mark(/.+)$#", $img_url, $split_url);
// split($mark, $img_url)
if ($split_url[1] != null) {
$img_path = $upload_path . $split_url[1];
list($w, $h) = #getimagesize($img_path);
}
}
}
for ($i=0; $i<$max_col; $i++) { // set new width and col_class
if ( ($i >= $max_col - 1) or ($w < $arr_w[$i+1]) ) {
$nw = $arr_w[$i];
$col_class = $col_class_base . ($i+1);
break;
}
}
$nh = (!$w or !$h) ? $nw : intval( ($h * $nw) / $w ); // set new height
$grid_img = $matches2[0];
// add width/height properties if nothing
$flg_no_w = (strpos($grid_img_edit, 'width=') === false);
$flg_no_h = (strpos($grid_img_edit, 'height=') === false);
if ($flg_no_w or $flg_no_h) {
$grid_img_close = (substr($grid_img, -2) == '/>') ? '/>' : '>';
$grid_img_edit = substr( $grid_img, 0, -(strlen($grid_img_close)) );
$grid_img_edit .= ($flg_no_w) ? ' width="0"' : '';
$grid_img_edit .= ($flg_no_h) ? ' height="0"' : '';
$grid_img = $grid_img_edit . $grid_img_close;
}
// replace new width/height properties
$grid_img = preg_replace('/width="(\d+)"/', 'width="'. $nw .'"', $grid_img);
$grid_img = preg_replace('/height="(\d+)"/', 'height="'. $nh .'"', $grid_img);
// check image link
//$chk_imglink = '/(<a(?:.+?)rel="(?:lightbox[^"]*?)"(?:[^>]*?)>)'. preg_quote($matches2[0], '/') .'/';
$chk_imglink = '/(<a(?:.+?)href="(?:.+?\.(?:jpe?g|png|gif))"(?:[^>]*?)>)'. preg_quote($matches2[0], '/') .'/';
if ($flg_img_forcelink) {
$grid_img = '' . $grid_img . '';
}
else if ( preg_match($chk_imglink, $content, $matches3) ) {
$grid_img = $matches3[1] . $grid_img . '</a>';
}
}
else if ($matches1[1] == 'object') {
preg_match('/<object(.+?)<\/object>/', $content, $matches2);
$matches_w = $matches_h = array();
preg_match('/width="([0-9]+)"/', $matches2[0], $matches_w);
preg_match('/height="([0-9]+)"/', $matches2[0], $matches_h);
if ($matches_w[1] and $matches_h[1]) {
$w = $matches_w[1];
$h = $matches_h[1];
}
else {
$flg_obj_fit = 'none';
}
//set col_class (and new width if in '*-fit' condition)
if ($flg_obj_fit == 'small-fit') {
for ($i=0; $i<$max_col; $i++) {
if ($i >= $max_col -1) {
$nw = $arr_w[$i];
$col_class = $col_class_base . ($i+1);
break;
}
else if ( $w < $arr_w[$i+1] ) {
$nw = $arr_w[$i];
$col_class = $col_class_base . ($i+1);
break;
}
}
}
else if ($flg_obj_fit == 'large-fit') {
for ($i=$max_col -1; $i>=0; $i--) {
if ( $w > $arr_w[$i] ) {
if ($i >= $max_col -1) {
$nw = $arr_w[$i];
$col_class = $col_class_base . ($i+1);
}
else {
$nw = $arr_w[$i+1];
$col_class = $col_class_base . ($i+2);
}
break;
}
if ($i == 0) {
$nw = $arr_w[$i];
$col_class = $col_class_base . ($i+1);
}
}
}
else {
for ($i=0; $i<$max_col; $i++) {
if ($i >= $max_col -1) {
$col_class = $col_class_base . ($i+1);
break;
}
else if ( $w < $arr_w[$i] ) {
$col_class = $col_class_base . ($i+1);
break;
}
}
}
$nh = (!$w or !$h) ? $nw : intval( ($h * $nw) / $w ); // set new height
$grid_img = $matches2[0];
if ($flg_obj_fit == 'small-fit' or $flg_obj_fit == 'large-fit') {
// replace new width/height properties
$grid_img = preg_replace('/width="(\d+)"/', 'width="'. $nw .'"', $grid_img);
$grid_img = preg_replace('/height="(\d+)"/', 'height="'. $nh .'"', $grid_img);
}
}
return array($col_class, $grid_img);
}
Thank you for looking at all of this.
This is some intermediate function. There will be probably some other part in the code which uses the return value from this function and actually outputs HTML. You should locate this part and comment the piece which output the width and height settings.
Pay attention, though, that if your images have variable proportions and you rescale them mantaining these proportions (via CSS), they will not fit in a grid anymore. They will look more scattered on the page than they are now.
EDIT Now that you have added more details, I think it should be enough to remove the section starting with the comment // add width/height properties if nothing

How to generate table of contents using dompdf?

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));

Categories