Capture the image in background and save in folder in PHP - php

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

Related

attach img on pdf download using laravel dompdf server provider

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.'">';

How to display data from mysql embed in html

Hey i want to display some html/css depending on how many rows there are in database basically. Is there a way to do this without echo? Because i'm lost when i have to use many ' '. Here is code sample
<?php foreach ($result as $row) {
}?>
<div id="abox">
<div class="abox-top">
Order x
</div>
<div class="abox-panel">
<p>lorem ipsum</p>
</div>
<br>
<div class="abox-top">
lorem</div>
<div class="abox-panel">
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Ut ac convallis diam, vitae rhoncus enim. Proin eu turpis at ligula posuere condimentum nec eu massa. Donec porta tellus ante, non semper risus sagittis at. Pellentesque sollicitudin sodales fringilla. Ut efficitur urna eget arcu luctus lobortis. Proin ut tellus non lacus dapibus vehicula non sit amet ante. Ut nibh justo, posuere sit amet fringilla eget, aliquam mattis urna.</p>
</div>
There's nothing complicated about it:
Simple/ugly:
<?php while($row = fetch()) { ?>
<div>
<?php echo $row['somefield'] ?>
</div>
<? } ?>
Alternative:
<?php
while ($row = fetch()) {
echo <<<EOL
<div>
{$row['somefield']}
</div>
EOL;
}
and then of course there's any number of templating systems, which claim to separate logic from display, and then litter the display with their OWN logic system anyways.
you can simply use <?= short opening tag introduced in php 5.3 before PHP 5.4.0 came out you had to enable short_open_tag ini but after 5.4.0 tag
here is an example
<?php $var='hello, world'; ?>
<?=$var ?> // outputs world
hope it helps.
Templates engines makes your life a pie
Take Smarty for example, it's pretty good template library. What template engine does is fetch variables to pre defined templates.
Your code in simple php:
<?php
echo 'My name is '. $name. ', that's why I'm awesome <br>';
foreach ($data as $value) {
echo $value['name'].' is awesome to!';
}
?>
Code in smarty:
My name is {$name}, that's why I'm awesome <br>
{foreach $data as $value}
{$value} is awesome to!
{/foreach}
Template engines pros:
Templates are held in separate custom named files. (i.e users.tpl, registration.tpl etc)
Smarty Caches your views (templates).
Simple to use i.e {$views + ($viewsToday/$ratio)}.
A lot of helpers.
You can create custom plugins/functions.
Easy to use and debug.
Most importantly: It separates your php code from html!
Template engines cons:
Sometimes hard to grip the concept of working for beginner.
Don't know any more actually
When I dont want to use a template engine (I like Twig, btw), I do something like this:
1) Write a separate file with the html code and some custom tags where data should be presented:
file "row_template.html":
<div class="abox-top">{{ TOP }}</div>
<div class="abox-panel"><p>{{ PANEL }}</p></div>
2) And then, read that file and do the replacements in the loop:
$row_template = file_get_contents('row_template.html');
foreach ($result as $row) {
$replaces = array(
'{{ TOP }}' => $row['top'],
'{{ PANEL }}' => $row['panel']
);
print str_replace(
array_keys($replaces),
array_values($replaces),
$row_template
);
}
In addition, you can change the content of "row_template.html" without touching the php code.
Clean and nice to the eye!

PHP : How to break a line

I am programming on wordpress and I want to edit a php file. I want the text to be displayed with line breaks and not all in one line.
Here is my code(I want jonh in one line and travolta in another but it gets displayed in one):
<div class="slide">
<img class="animated fade_left" src='<?php echo esc_url(onepage_get_option('onepage_testimonial_2_image', ONEPAGE_DIR_URI . "assets/images/team2.jpg")); ?>' onmouseover="javascript: this.title = '';" title="">
<div class="bx-caption animated fade_right"><span><a class="arrow"></a><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_content', __('Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam.','one-page'))); ?><a class="testimonial"><?php echo esc_attr(onepage_get_option('onepage_testimonial_2_name', __('john \n travolta','one-page'))); ?></a></span></div>
Any suggestions?
If you want the link / element with the class testimonial on a new line, I would use css as that keeps it flexible and makes it easy to change if you want to do it differently in the future.
So in your css file:
.testimonial {
display: block;
}
In general, I would try to keep presentational stuff out of the php code.

Image is not taking 100% of div?

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%

Fulltext-search in php without database

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

Categories