I want attach an image on my pdf when pdf is downloaded, I am using dompdf service provider in laravel 8 version, I am using public path method but the image still not attaching the pdf file.
public function invoicepdf($productid, $orderId)
{
$orderHistory = Order::where('order_id',$orderId)->orderBy('id', 'DESC')->first();
$orderProductDetails[]=json_decode($orderHistory->product_details,true);
foreach($orderProductDetails as $orderdata)
{
foreach($orderdata as $orderDetail )
{
if($orderDetail['product_id']== $productid)
{
$productDetails = $orderDetail;
$marchantdetails = UserData::where('user_id',$orderDetail['marchent_id'])->first();
}
}
}
$pdf = PDF::loadView('front_end.invoice',compact('orderHistory','productDetails','marchantdetails'))->setOptions(['defaultFont' => 'sans-serif']);
// download PDF file with download method
return $pdf->download('pdf_file.pdf');
} ```
this is my pdf download function or method
<div style="text-align: center;">
<img src="{{ public_path('public/image.png') }}" style="width: 100px; height: 100px">
</div>
<p>ut aliquip ex ea commodoconsequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidata.</p>
this is my pdf blade file code
when I am using this pubic_path function pdf is downloading but the image is not attached with pdf file, please help me with this.
use
this code at your blade file where $data
echo '<img src="data:image/jpg;base64,' . $data->image.'">';
Related
I am getting errors when I tried to include image in dompdf. I am using version 1.2.1
I tried with base4 encoded image as well from one of the solutions mentioned in forums, that also not working.
<?php
namespace Dompdf;
require_once 'dompdf/autoload.inc.php';
$_dompdf_show_warnings = true;
$_dompdf_warnings = [];
$path="http://localhost/dompdf/assets/images/logo.png";
$data = file_get_contents($path);
$image = 'data:image/' . $type . ';base64,' . base64_encode($data);
$htmldata = '<!DOCTYPE html>
<html>
<head>
<title>Results</title>
<style>
body {
background-color: lightblue;
}
.container {
width: 90%;
max-width: 600px;
margin: 0 auto;
}
</style>
</head>
<body>
<div class="container">
<h1>test pdf</h1>
<img src="/assets/images/logo.png" alt="image">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer egestas elementum justo, eget maximus odio ultricies eu. Aenean faucibus varius massa, sit amet sagittis neque vulputate luctus.</p>
<img src="'.$image.'" alt="base64">
</div>
</body>
</html>';
$options = new Options();
$options->getChroot($_SERVER['DOCUMENT_ROOT']."/dompdf/");;
$options->setisRemoteEnabled(true);
$options->setIsHtml5ParserEnabled(true);
$dompdf = new Dompdf($options);
$dompdf->loadHtml($htmldata);
$dompdf->render();
$dompdf->stream("",array("Attachment" => false));
exit(0);
?>
Getting these errors, first is when I include the image path and second for base64 encoded one. I tried to enable remote, added chroot path and tried several solutions found on internet. Nothing helped.
Permission denied on /assets/images/logo.png. The file could not be found under the paths specified by Options::chroot. /assets/images/logo.png
Unable to create temporary image in /var/folders/bc/tnbzrzvd1k370wftgbm5lnqh0000gn/T data:image/;base64,iVBORw0KGgoAAAANSUhEUgA
EDIT:
Tried with file_exists() from the same directory and it works.
Can anyone suggest a solution for this?
Capture the image in the background and save it in a folder in PHP.
I have created a PHP page in which we capture the image of an HTML using html2canvas() and via ajax save that image in a folder.
When I run the code from the browser it shows an HTML and saves the image in a given folder. (Here it is working fine).
The issue is when I run the same file using cmd like via PHP cmd or via CRON (php test.php) then that is not generating an image just render HTML in the terminal.
How I run the same code in the background and save in the generated image in a folder?
test.php
<!DOCTYPE html>
<html>
<head>
<title></title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<button type="button" id="capture">Capture & Save</button>
<div class="parent-wrapper">
<div class="wrapper-box" id="canvas" width="1080" height="1080">
<div class="heading">
Lorem Ipsum
</div>
<div class="sub-heading">
Lorem ipsum , Lorem
</div>
<div class="paragraph">
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod
tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam,
quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo
consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse
cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non
proident, sunt in culpa qui officia deserunt mollit anim id est laborum.
</div>
<div class="bottom-heading">
#Lorem
</div>
</div>
</div>
<script type="text/javascript">
function truncate(source, size) {
return source.length > size ? source.slice(0, size - 1) + "..." : source;
}
var para = document.querySelector('.paragraph');
var res = truncate(para.innerHTML, 280);
para.innerHTML = res;
</script>
<script src="jquery-3.5.1.min.js"></script>
<script src="html2canvas.min.js"></script>
<script type="text/javascript">
$(function(){
$('.movable_div').on('contextmenu', function(){
return false;
});
$('#capture').click(function(){
div_content = document.querySelector("#canvas");
html2canvas(div_content, {
dpi: 96,
width: 1080,
height: 1080,
}).then(canvas => {
data = canvas.toDataURL('image/jpeg', 1);
save_img(data);
});
});
// Onload Click capture
$('#capture').click();
});
//to save the canvas image
function save_img(data){
//ajax method.
$.post('save_jpg1.php', {data: data}, function(res){
});
}
</script>
</body>
</html>
save_jpg1.php
<?php
//just a random name for the image file
$random = rand(100, 1000);
$savefile = #file_put_contents("output/$random.jpg", base64_decode(explode(",", $_POST['data'])[1]));
//if the file saved properly, print the file name
if($savefile){
echo $random;
}
?>
Thanks in advance.
Tried below code also but not work for me:
setTimeout(function(){
div_content = document.querySelector("#canvas");
html2canvas(div_content, {
dpi: 96,
width: 1080,
height: 1080,
}).then(canvas => {
data = canvas.toDataURL('image/jpeg', 1);
save_img(data);
});
}, 5000);
You can achieve this by using below library.
Source: https://github.com/stil/gd-text
Wrote the script in PHP and run via terminal to create image in background.
The terminal doesn't know how to render an html file like a browser does - the terminal will simply output the html as a text file. I think there may be a way to programmatically trigger such a rendering, and you could update the javascript to trigger the html2canvas when the page loads rather than after a click. In that way, you could trigger it from the command line, it would render, and fire the save function with the image.
Looks like this might have some ideas for how to run an html file from the terminal:
How can I run a html file from terminal?
Specifically, you may want to try serving the html file locally, and triggering a browser view
I am trying to create a paragraph and next to that paragraph are images that are generated randomly from a database table. The main container is called ".container" and this includes every element. .container is set to width: 90%. The paragraph (.header) floats to the left and has a width of 70%. The generated images (.recommend) floats to the right and has a width of 30%. Everything works out fine, but the only problem is that when I set the images to take up the whole space of the .recommend div (width: 100%), but it doesn't do that. Instead, the width of the images are 30%. How do I make the images take up the whole space of the .recommend div?
<!DOCTYPE html>
<html>
<head><link type="text/css" rel="stylesheet" href="/science/template.css"></head>
<body>
<div class="container">
<div class="header">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</p>
</div>
<div class="recommend">
<?php
$numArray = array();
for ($i = 1; $i <=10; $i++)
{
$numArray[$i] = $i;
}
shuffle($numArray);
$resultSet = $db->query("SELECT * FROM table");
if ($resultSet->num_rows != 0)
{
while ($rows = $resultSet->fetch_assoc())
{
$id = $rows["id"];
$image1 = $rows["image1"];
$image2 = $rows["image2"];
$image3 = $rows["image3"];
$title = $rows["title"];
$title2 = $rows["title2"];
$title3 = $rows["title3"];
echo "<div class=row>";
if ($id == $numArray[0])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[1])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
if ($id == $numArray[2])
{
echo "<div class=col-md-4 id=left><img src=$image1><p>$title</p></div>";
}
echo "</div>";
}
}
?>
</div>
</div>
</body>
</html>
CSS
.container{
background--color: green;
width: 90%;
height: auto;
}
.header{
background-color: blue;
float: left;
width: 70%;
}
.recommend{
background-color: red;
width: 30%;
float: right;
}
.recommend img{
width: 100%;
}
It would be FAR more useful to see the rendered HTML than the PHP that generates the html.
The image is taking the full width of the containing div - which is set to 30% width. This markup: <div class=col-md-4 id=left> is using a Bootstrap grid class. And, col-md-4 tells the div to be 4/12 (or 30%) of the width of the parent. Since the parent is .recommend, then the div is 30%, and the image inside is 100% of THAT (which means it is 30% of the .recommend div)
So, you can either remove the col-md-4 class from the divs, or you can try and resolve it another way.
According to the CSS provided .recommend div is set to width:30%
All the child elements that have width:100% (images) will only take up as much space as .recommend div, which is 30%
I have a really small webpage written in php (approx. 5 pages + blog entries). All pages are located in php files on the server side (no database is used). So far I managed to search inside my 'blog entries' - because these are just plain textfiles with HTML markup (I strip the tags & performing a search operation):
$file_name=array();
$search_string="";
if(isSet($_GET["query"])){
$search_string=$_GET["query"];
}
$search_result="";
$files="";
$phpfilename="";
$i=0;
if (!$search_string){
echo 'No query entered<br />';
}else{
if ($handle = opendir('content/')) {
while (false !== ($file = readdir($handle))){
if(strrchr($file, '.') === ".txt"){
$filename[]= $file;
}
}
closedir($handle);
}
foreach($filename as $value){
$files="content/$value";
$fp = strip_tags(file_get_contents($files));
if(stripos($fp, $search_string)) {
$search_result.=preg_replace('/<[^>]*>[^<]*<[^>]*>/', '', substr($fp,0,255)); // append a preview to search results
}
if($search_result!=""){
echo $search_result;
}else{
echo "No Results<br />";
}
}
}
Of course that works just because the files are plain text. But I've got also pages that are real 'php' files and want to perform a search operation on them too. But I don't want to search inside the 'php code' of course. I figured out, that I would need the preparsed files that the browser gets from the webserver - I thought about using file_get_contents() with http requests to all my pages (ok, 'just' about 5 pages but still)...
I've read here on SO that it's considered bad practice to do so and it feels like I'm taking the wrong approach.
Any ideas & suggestions would be highly appreciated.
Edit: A example for a regular page that I want to be able to search in
index.php
<?php ob_start(); require_once("./include/common.php"); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title><?php echo $lang['WEBSITE_TITLE']; ?></title>
<meta http-equiv="content-type" content="text/html; charset=UTF-8" />
<meta name="keywords" content="keyword, keyword, keyword" />
<link href="css/main.css" type="text/css" rel="stylesheet" />
</head>
<body>
<div id="page">
<!-- Header Area -->
<?php include("./include/header.php"); ?>
<?php include("./include/banner.php"); ?>
<div id="content">
<?php
$page = '';
if(isSet($_GET["page"])){
$page=$_GET["page"];
}
switch($page){
case 'category_1':
include("./include/category_1.php");
break;
case 'about':
include("./include/category_2.php");
break;
case 'contact':
include("./include/contact.php");
break;
default:
include("./include/home.php");
}
?>
<!-- /content --></div>
<!-- /page --></div>
<br />
<br /><br /><br />
<!-- Footer Area -->
<?php include("./include/footer.php"); ob_end_flush(); ?>
</body>
</html>
/include/category_1.php
<?php echo '<h2>'.$lang['NAVI_CAT_1'].'</h2>'; ?>
<div id="entry">
<br/>
<?php echo $lang['CAT_1_TEXT']; ?>
</div>
language file
<?php
$lang = array();
$lang['NAVI_CAT_1'] = 'Category 1';
$lang['CAT_1_TEXT'] = 'Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim.';
?>
Why not include into a buffer and then search the buffer's contents?
ob_start();
include ('index.php');
$contents = ob_get_clean();
//the $contents now includes whatever the php file outputs
I actually use this method in production code for all kinds of things, but mainly previewing site-generated emails before users send them. The nice thing is, you can use this on all the files, not just the php files.
this is failed by design.
consider not using plain mixed html sides. try to use xml files or wathever.
the alternative is crawling your own side. take a look at http://symfony.com/doc/current/components/dom_crawler.html
Note: I'm using Wordpress, but I don't believe it's relevant to the answer, so I've asked it on SO. If I'm wrong, please tell me/move the question.
Okay, I'm loading up blocks of rich content (via Wordpress) which frequently contain many images wrapped in anchor tags. I'd like to step through all of them in order to display them as a tags with their relevant imgs inside.
I've already found this handy bit of regex-powered code which gets me the images perfectly well:
// Get the all post content in a variable
$posttext = $post->post_content;
//$posttext1 = get_cleaned_excerpt();
// We will search for the src="" in the post content
$regular_expression = '~src="[^"]*"~';
$regular_expression1 = '~<img [^\>]*\ />~';
// WE will grab all the images from the post in an array $allpics using preg_match_all
preg_match_all( $regular_expression, $posttext, $allpics );
// Count the number of images found.
$NumberOfPics = count($allpics[0]);
// This time we replace/remove the images from the content
$only_post_text = preg_replace( $regular_expression1, '' , $posttext1);
/*Only text will be printed*/
// Check to see if we have at least 1 image
if ( $NumberOfPics > 0 )
{
$this_post_id = get_the_ID();
for ( $i=0; $i < $NumberOfPics ; $i++ )
{ $str1=$allpics[0][$i];
$str1=trim($str1);
$len=strlen($str1);
$imgpath=substr_replace(substr($str1,5,$len),"",-1);
$theImageSrc = $imgpath;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
I'd really like to wrap that bottom img with the relevant parent a. Any help here would be greatly appreciated.
An example of the content to be searched might be:
<h5>
<a href="http://www.example.com/imagefoo.jpg">
<img class="size-thumbnail wp-image-4091 alignleft" src="http://www.example.com/imagefoo-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Bar.jpg">
<img class="wp-image-4087 alignleft" title="Image - Bar" src="http://www.example.com/Image-Bar-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<h5>
<a href="http://www.example.com/Image-Alphe.jpg">
<img class="wp-image-4090 alignleft" title="Image-Alpha" src="http://www.example.com/Image-Alpha-150x150.jpg" alt="" width="150" height="150" />
</a>
</h5>
<img class="size-thumbnail wp-image-4088 alignleft" title="EXAMPLE-image-150" src="http://www.example.com/EXAMPLE-image-150-150x150.jpg" alt="" width="150" height="150" />
<h5>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.</h5>
<a href="http://www.example.com/insanely-long-permalink-created-as-if-by-a-madman-who-knows-no-bounds-of-shame/" rel="attachment wp-att-2780">
<img class="alignright size-thumbnail wp-image-2780" title="Exhibition Title: Image Name by Artist Person" src="http://www.example.com/wp-content/uploads/2011/12/ExtraordinaryImage-150x150.jpg" alt="Example UK | Exhibition: Image by Artist Person" width="150" height="150" />
</a>
Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat.
EDIT: Here's the working code based on my needs. It uses XPath, based on cHao's answer below. (For what it's worth, I found Tizag's webpage very useful as an XPath primer, alongside this EarthInfo page.):
// Get the all post content in a variable
$posttext = $post->post_content;
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
$i = 0;
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a/img/..') as $link) :
$img = $link->getElementsByTagName('img')->item(0);
$link_src = $link->getAttribute('href');
$link_title = $link->getAttribute('title');
$img_src = $img->getAttribute('src');
$theImageSrc = $img_src;
global $blog_id;
if (isset($blog_id) && $blog_id > 0) {
$imageParts = explode('/files/', $theImageSrc);
if (isset($imageParts[1])) {
$theImageSrc = '/blogs.dir/' . $blog_id . '/files/' . $imageParts[1];
}
}
?>
<a href="<?php echo $link_src; ?>" rel="lightbox[<?php echo $this_post_id; ?>]" title="<?php if ($link_title) {
echo $link_title;
} else { the_title(); } ?>" class="cboxElement">
<img class="alignleft" src='<?php echo get_bloginfo('template_directory').'/timthumb.php?src=' . $theImageSrc . '&h=150&w=150'; ?>' height="150" width="150" alt=""/>
</a>
<?php
endforeach;
?>
You'd be better off not trying to use regular expressions for finding the images. They suck at parsing HTML.
Instead, check out the DOMDocument and DOMXPath classes.
$document = DOMDocument::loadHTML($posttext);
$xpath = new DOMXPath($document);
# for each link that has an image inside it, set its href equal to
# the image's src.
foreach ($xpath->query('//a[/img]') as $link) {
$img = $link->getElementsByTagName('img')->item(0);
$src = $img->getAttribute('src');
# do your mangling of $src here, resulting in $href.
# for example...
$href = preg_replace('/-\d+x\d+(?=\.[^.]*$)/', '', $src);
$link->setAttribute('href', $href);
}
$fixed_html = $document->saveHTML();