TCPDF how do I create several pdf's without opening a browser - tcpdf

I need to create like 350 pdf's at once. Now the browser opens a window for each pdf. I takes longer to open all the 350 windows than to create the pdf's. How do I create and save the pdf's without opening a browser windows? (In my pdf I use Header, body and footer all with variables)
Now I do a loop on php_page_1 which opens the pdf create file.
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
}

You can use curl to make the request to the URL instead of opening it directly in the browser or you can just include the file that generates the PDF. Try this code
$sql = "SELECT id FROM shipping_id WHERE datum BETWEEN $date_range AND acc_id=$acc_id;";
$STH = $dbo->prepare( $sql );
$STH->execute();
$contains_files = 0;
$client_id='';
while ( $row = $STH->fetch( PDO::FETCH_ASSOC ) ) {
$contains_files++;
$link = "vb_print_1_no_screen.php?id=" . $row[ 'id' ] . "&nr=".$contains_files;
// echo '<script>window.open("https://' . $website_admin . $link . '");</script>';
// method 1 using curl
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $website_admin . $link);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$return = curl_exec($ch);
curl_close($ch);
// method 2 include pdf generator script
$_GET['id'] = $row['id'];
$_GET['nr'] = $contains_files;
include "vb_print_1_no_screen.php";
}
Kindly make sure to use just one method.

Related

Google Translate in Flash (SWF) Action Script

We tried to code Google Translate in action script for Flash Professional CS6, but it does not function .
Can anyone help ?
The code does not return the trasnlated result .
The Code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
result_lv.onLoad = function () {
var str:String = unescape(this);
var txtContent;
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
}
Code Explained :
Sample
LoadVars.sendAndLoad( )
Method Code Explained :
https://flylib.com/books/en/4.13.1.377/1/
================================================
Edit 1:
I edited my code :
I added the return code to the main function , so the main function has output .
but still the function does not return any transalted content .
The improved code :
private function translate(e)
{
var result_lv:LoadVars = new LoadVars();
var txtContent;
result_lv.onLoad = function () {
var str:String = unescape(this);
var translatedText:String = str.split('":"')[1].split('"}, ')[0];
if(translatedText != undefined)
txtContent.text = translatedText.split('r').join('n').split('"').join("'");
return txtContent.text;
}
var lorem_lv:LoadVars = new LoadVars();
var from:String = "fa";
var to:String = "en"
lorem_lv.v = "1.0";
lorem_lv.format = "text";
lorem_lv.q = e;
lorem_lv.langpair = from + "|" + to;
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
return txtContent.text;
}
================================================
Edit 2:
We have found a working PHP function that return the translated result properly :
https://github.com/statickidz/php-google-translate-free/blob/1.1.1/src/GoogleTranslate.php
Now we are trying to load the PHP function result in the Action Script 2 for Adobe Flash Professional CS6.
here is some explanation about how this is possible :
Flash calling a PHP function
================================================
Edit 3:
A Good and Complete Book about PHP for Flash :
Foundation PHP for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-Steve-Webster/dp/1903450160
================================================
Edit 4:
Some Other Good and Complete Books about PHP for Flash :
Foundation PHP 5 for Flash 1st Edition :
https://www.amazon.com/Foundation-PHP-Flash-David-Powers/dp/B0096EPX7Q
Advanced PHP for Flash 1st ed. Edition :
https://www.amazon.com/Advanced-PHP-Flash-Steve-Webster/dp/1590591879
================================================
Edit 5:
We have rewritten the action script function that now use the PHP GoogleTranslate function .
See the answers below .
But it does not return the Translated result .
Please can someone help ?
Thanks
In the PHP-script that you've mentioned in comments, authors used the link https://translate.google.com/translate_a/single?... with some client authenticaton data like iid and also set User-Agent to Android phone:
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
I think this script is trying to masquerade request like it was sent from Android Google Translate App.
But in your AcrionScript code you are using another URL:
lorem_lv.sendAndLoad(" http://ajax.googleapis.com/ajax/services/language/translate ", result_lv, "GET");
This simple-HTTP Google Translate API v1 is very old and already not available.
You can check it yourself by following this link - it's responds 404.
Here is the code that we have written :
Our function is written using the sample code on the below address :
Easy way to bring a php variable on flash with AS2
but it does not return the translated result . when I set the return String value to e variable the function work . but when I set the return to $output variable it does not function .
Action Script 2 Code :
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// define onLoad Callback
lv.onLoad = onLoadCallBack;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", lv, "POST");
var $output;
// onLoad Callback
function onLoadCallBack(succes)
{
// if succes
if(succes)
{
// trace variables
$output = this.lVarresult;
}
else
{
// loading failed
$output = "Loading Error!!";
}
}
return $output;
}
=============================================================
Edit :
The PHP (google-translate-result.php) Code is changed :
$_POST changed to $_GET and now the result php code is working itself through using this url :
Server_URL/google-translate-result.php?sVar1=fa&sVar2=en&sVar3=%DA%A9%D8%AA%D8%A7%D8%A8%20%D8%AA%D8%B3%D8%AA
but still the ActionScript does not return the Translated Result .
=============================================================
PHP Code (google-translate-result.php) :
<?php
require_once('GoogleTranslate.php');
// get variables
$var1 = $_GET['sVar1'];
$var2 = $_GET['sVar2'];
$var3 = $_GET['sVar3'];
$result = GoogleTranslate::translate($var1,$var2,$var3);
// send variables
echo "&lVarresult=$result&";
PHP Code (GoogleTranslate.php) :
<?php
/**
* GoogleTranslate.class.php
*
* Class to talk with Google Translator for free.
*
* #package PHP Google Translate Free;
* #category Translation
* #author Adrián Barrio Andrés
* #author Paris N. Baltazar Salguero <sieg.sb#gmail.com>
* #copyright 2016 Adrián Barrio Andrés
* #license https://opensource.org/licenses/GPL-3.0 GNU General Public License 3.0
* #version 2.0
* #link https://statickidz.com/
*/
/**
* Main class GoogleTranslate
*
* #package GoogleTranslate
*
*/
class GoogleTranslate
{
/**
* Retrieves the translation of a text
*
* #param string $source
* Original language of the text on notation xx. For example: es, en, it, fr...
* #param string $target
* Language to which you want to translate the text in format xx. For example: es, en, it, fr...
* #param string $text
* Text that you want to translate
*
* #return string a simple string with the translation of the text in the target language
*/
public static function translate($source, $target, $text)
{
// Request translation
$response = self::requestTranslation($source, $target, $text);
// Get translation text
// $response = self::getStringBetween("onmouseout=\"this.style.backgroundColor='#fff'\">", "</span></div>", strval($response));
// Clean translation
$translation = self::getSentencesFromJSON($response);
return $translation;
}
/**
* Internal function to make the request to the translator service
*
* #internal
*
* #param string $source
* Original language taken from the 'translate' function
* #param string $target
* Target language taken from the ' translate' function
* #param string $text
* Text to translate taken from the 'translate' function
*
* #return object[] The response of the translation service in JSON format
*/
protected static function requestTranslation($source, $target, $text)
{
// Google translate URL
$url = "https://translate.google.com/translate_a/single?client=at&dt=t&dt=ld&dt=qca&dt=rm&dt=bd&dj=1&hl=es-ES&ie=UTF-8&oe=UTF-8&inputm=2&otf=2&iid=1dd3b944-fa62-4b55-b330-74909a99969e";
$fields = array(
'sl' => urlencode($source),
'tl' => urlencode($target),
'q' => urlencode($text)
);
// URL-ify the data for the POST
$fields_string = "";
foreach ($fields as $key => $value) {
$fields_string .= $key . '=' . $value . '&';
}
rtrim($fields_string, '&');
// Open connection
$ch = curl_init();
// Set the url, number of POST vars, POST data
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, count($fields));
curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
curl_setopt($ch, CURLOPT_USERAGENT, 'AndroidTranslate/5.3.0.RC02.130475354-53000263 5.1 phone TRANSLATE_OPM5_TEST_1');
// Execute post
$result = curl_exec($ch);
// Close connection
curl_close($ch);
return $result;
}
/**
* Dump of the JSON's response in an array
*
* #param string $json
* The JSON object returned by the request function
*
* #return string A single string with the translation
*/
protected static function getSentencesFromJSON($json)
{
$sentencesArray = json_decode($json, true);
$sentences = "";
foreach ($sentencesArray["sentences"] as $s) {
$sentences .= isset($s["trans"]) ? $s["trans"] : '';
}
return $sentences;
}
}
According to the Comments of the previous answer Action Script 2 Code changed to:
function googletranslate(e:String):String
{
/*LoadVars send example*/
// init LoadVars Object
var lv:LoadVars = new LoadVars();
var result_lv:LoadVars = new LoadVars();
// set Variables
lv.sVar1 = "fa";
lv.sVar2 = "en";
lv.sVar3 = e;
// send and load variables
lv.sendAndLoad("google-translate-result.php?", result_lv, "POST");
return result_lv.lVarresult;
}

XPATH - Multiple Url's

The code bellow, can count the number of times that the following words appearing on the URL consultor imobiliario , Consultora Imobil and Consultor Imobil repeats:
<?php
ini_set('display_errors', 1);
ini_set('display_startup_errors', 1);
error_reporting(E_ALL);
require_once dirname(__FILE__).'/../public_html/include/functions.php';
require_once dirname(__FILE__).'/phpQuery.php';
//header('Content-Type:application/json');
//Decisoes e Solucoes - Consultores
$current_page = 1;
$max_page = 999999999999;
$countTotalConsultores=0;
while($max_page >= $current_page){
$url = "https://decisoesesolucoes.com/agencias/albergaria/consultores?page=";
$url .= $current_page;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$res = curl_exec($ch);
curl_close($ch);
$dom = new DomDocument();
# $dom->loadHTML($res);
$xpath = new DOMXpath($dom);
$tables = $xpath->query("//*[text()[contains(normalize-space(), 'consultor imobiliario') or contains(normalize-space(),'Consultora Imobil') or contains(normalize-space(),'Consultor Imobil')]]");
$count = $tables->length;
$countTotalConsultores = $countTotalConsultores+$count;
echo " Página atual:" .$current_page . "No. of agents " . $countTotalConsultores;
$current_page = $current_page+1;
if ($count < 1){
break;
}
}
How can I add more than one URL for this Words searching count with this code?
I want to search in this following url's:
https://decisoesesolucoes.com/agencias/albergaria/consultores?page=
https://decisoesesolucoes.com/agencias/ABRANTES/consultores?page=
https://decisoesesolucoes.com/agencias/albufeira/consultores?page=
Can anyone help me please?
Thanks
Why don't you loop on those url ?
If you want to count you can use this XPATH query
count(//*[text()[contains(normalize-space(), 'consultor imobiliario') or contains(normalize-space(),'Consultora Imobil') or contains(normalize-space(),'Consultor Imobil')]])

Access specific node (custom_field) simplexml

This XML file, which can be accessed here # http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/ - has a custom_fields node with 2 fields called custom-bgcolor, and custom-fontcolor. I have tried numerous ways to try, and access the data inside them with no luck.
I have been accessing other nodes with simplexml, but haven't been able to get the custom_fields working. Here is what I have so far.
$curl = curl_init();
curl_setopt ($curl, CURLOPT_URL,'http://afdclinics.com/persistentpresence/category/brentwood/lobby-1/feed/');
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$result = curl_exec ($curl);
if ($result === false) {
die('Error fetching data: ' . curl_error($curl));
}
curl_close ($curl);
//we can at this point echo the XML if you want
//echo $result;
//parse xml string into SimpleXML objects
$xml = simplexml_load_string($result);
if ($xml === false) {
die('Error parsing XML');
}
//now we can loop through the xml structure
foreach ($xml->channel->item as $item) {
//print $item->title; rss feed article title
//print $item->description; rss feed article description
//print $item->link; rss feed article link
//print $item->pubDate; rss feed article publish date
print $item->children('content', true); //rss feed article content
// here is where is would like to print the custom values
print $item->custom_fields->custom-bgcolor; // this line doesn't seem to work
//gets img url's and appends them to offline manifest file
$imgUrl = array();
$doc2 = new DOMDocument();
$doc2->loadHTML($item->children('content', true));
$imgUrl = simplexml_import_dom($doc2);
$images = $imgUrl->xpath('//img');
foreach ($images as $img) {
$imgUrl = $img['src'] . "\r\n";
print $imgUrl; //rss feed image url's
$i++;
}

How to correctly use oembed to pull thumbs from youtube

I show a lot of thumbs on my homepage from youtube videos. I was using this function below to grab the thumb from a youtube url which works fast but it doesn't work for url's in the shortned form like youtu.be/JSHDLSKL.
function get_youtube_screen_link( $url = '', $type = 'default', $echo = true ) {
if( empty( $url ) )
return false;
if( !isset( $type ) )
$type = '';
$url = esc_url( $url );
preg_match("|[\\?&]v=([^&#]*)|",$url,$vid_id);
if( !isset( $vid_id[1] ) )
return false;
$img_server_num = 'i'. rand(1,4);
switch( $type ) {
case 'large':
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/0.jpg";
break;
case 'first':
// Thumbnail of the first frame
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/1.jpg";
break;
case 'small':
// Thumbnail of a later frame(i'm not sure how they determine this)
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/2.jpg";
break;
case 'default':
case '':
default:
$img_link = "http://{$img_server_num}.ytimg.com/vi/{$vid_id[1]}/default.jpg";
break;
}
if( $echo )
echo $img_link;
else
return $img_link;
}
So I tried to use Oembed to get the thumbs instead which works for all variations of the youtube url but it retrieves the 480px/360px thumb which causes a lot of cropping to get it down to the 120px/90px size I use to display them. The other issue was it caused my page speed to increase by 4 seconds which Im guessing is a problem with the way I'm implementing it. Here's how I call the thumb inside a loop.
<?php
require_once(ABSPATH.'wp-includes/class-oembed.php');
$oembed= new WP_oEmbed;
$name = get_post_meta($post->ID,'video_code',true);
$url = $name;
//As noted in the comments below, you can auto-detect the video provider with the following
$provider = $oembed->discover($name);
//$provider = 'http://www.youtube.com/oembed';
$video = $oembed->fetch($provider, $url, array('width' => 300, 'height' => 175));
$thumb = $video->thumbnail_url; if ($thumb) { ?>
<img src="<?php echo $thumb; ?>" width="120px" height="90px" />
<?php } ?>
So how should I be doing this to maximize efficiency?
I came across this page from youtube explaining their oembed support, They mentioned that they output to json format so I made a function that gets the json data and then enables you to use it.
Feel free to ask if you need more help.
<?php
$youtube_url = 'http://youtu.be/oHg5SJYRHA0'; // url to youtube video
function getJson($youtube_url){
$baseurl = 'http://www.youtube.com/oembed?url='; // youtube oembed base url
$url = $baseurl . $youtube_url . '&format=json'; // combines the url with format json
$json = json_decode(file_get_contents($url)); // gets url and decodes the json
return $json;
}
$json = getJson($youtube_url);
// from this point on you have all your data placed in variables.
$provider_url = $json->{'provider_url'};
$thumbnail_url = $json->{'thumbnail_url'};
$title = $json->{'title'};
$html = $json->{'html'};
$author_name = $json->{'author_name'};
$height = $json->{'height'};
$thumbnail_width = $json->{'thumbnail_width'};
$thumbnail_height = $json->{'thumbnail_height'};
$width = $json->{'width'};
$version = $json->{'version'};
$author_url = $json->{'author_url'};
$provider_name = $json->{'provider_name'};
$type = $json->{'type'};
echo '<img src="'.$thumbnail_url.'" />'; // echo'ing out the thumbnail image
Ok I came up with a solution from pieces of other questions. First we need to get the id from any type of url youtube has using this function.
function getVideoId($url)
{
$parsedUrl = parse_url($url);
if ($parsedUrl === false)
return false;
if (!empty($parsedUrl['query']))
{
$query = array();
parse_str($parsedUrl['query'], $query);
if (!empty($query['v']))
return $query['v'];
}
if (strtolower($parsedUrl['host']) == 'youtu.be')
return trim($parsedUrl['path'], '/');
return false;
}
Now we can get use YouTube Data API to get the thumbnail from the video id. Looks like this.
<?php
$vid_id = getVideoId($video_code);
$json = json_decode(file_get_contents("http://gdata.youtube.com/feeds/api/videos/$vid_id?v=2&alt=jsonc"));
echo '<img src="' . $json->data->thumbnail->sqDefault . '" width="176" height="126">';
?>
The problem is that is causing an extra 2 seconds load time so I simply use the $vid_id and place it inside http://i3.ytimg.com/vi/<?php echo $vid_id; ?>/default.jpg which gets rid of the 2 seconds added by accessing the youtube api.

How to get the total number of tweets, retweets and replies on a particular tag or account, in Twitter using its API?

I have a requirement to get the total no.of tweets, retweets and replies on a particular tag or user account. How to get these numbers efficiently? The numbers should be exact and not like 100+.
I also need to get the total no.of direct messages.
Using this site as a starting point I've been trying the same thing:
Pull Twitter feed into your site
<?php
require_once 'db-functions.inc.php' ; //custom database functions
function saveTweets($screen_name) {
global $link;
$screen_name = dbEscape(strtolower(trim($screen_name)));
if (!$screen_name) { echo "<p><strong>Error: No screen name declared.</strong></p>\n"; return false; }
$row = dbGetRow("SELECT `id` FROM `retweet` WHERE `screen_name`='$screen_name' ORDER BY `id` DESC LIMIT 1");
$last_id = $row['id'];
$url = "http://api.twitter.com/1/statuses/user_timeline.xml?screen_name=$screen_name&count=1500&include_rts=true" ;
if ($last_id) { $url .= "&since_id=$last_id" ; }
$ch = curl_init($url);
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, TRUE);
$xml = curl_exec ($ch);
curl_close ($ch);
$affected = 0;
$twelement = new SimpleXMLElement($xml);
foreach ($twelement->status as $status) {
$text = dbEscape(trim($status->text));
$time = strtotime($status->created_at);
$id = $status->id;
$retweet_count = $status->retweet_count;
dbQuery("INSERT INTO `twit` (`id`,`screen_name`,`time`,`text`,`hidden`,`retweet_count`) VALUES ('$id','$screen_name','$time','$text','n','$retweet_count')");
$affected = $affected + dbAffectedRows();
}
return "<p>".number_format($affected)." new tweets from $screen_name saved.</p>\n" ;
}
echo saveTweets('stackoverflow');
echo saveTweets('Apple');
echo saveTweets('Android');
echo saveTweets('Google');
?>
<h3>Stackoverflow</h3>
<?php
require_once 'databaseconnection.php' ; //database connection function
$result = dbQuery("SELECT * FROM `retweet` WHERE `hidden` != 'y' ORDER BY `retweet_count` DESC");
while ($row = mysql_fetch_array($result)) {
echo $row[0];
echo "<br>";
echo date("l, M j, Y, G:i a",$row[3]);
echo " : ";
echo stripslashes($row[2]);
echo "<br>";
echo stripslashes($row[4]);
echo "<br>Retweet: ";
echo stripslashes($row[6]);
echo "<br>";
echo "<br>";
}
?>
At the present time this doesn't have an "UPDATE" clause in it to take into account the retweet_count increasing, and you can remove:
return "<p>".number_format($affected)." new tweets from $screen_name saved.</p>\n" ;
If you don't need to see what has been updated.
Hope that helps

Resources