unable to see header after fpdf creates file - wordpress

I am working on a wordpress plugin,
I want to create a pdf file, For this I used fpdf
By using this code I am able to generate pdf and save it to server
require('fpdf/html_table.php');
$pdf=new PDF_HTML();
$questions = $_POST['question'];
$count = count($questions);
$quests = "";
$pdf->SetFont('times','',12);
$pdf->SetTextColor(50,60,100);
$pdf->AddPage('P');
$pdf->SetDisplayMode(real,'default');
$pdf->SetFontSize(12);
for($i=1;$i<=$count;$i++)
{
$qus_id = $questions[$i-1];
$get_q = "select * from `SelleXam_question` where `id`='$qus_id'";
$get_q = $wpdb->get_results($get_q);
$questf = "Quest $i : ".$get_q[0]->question;
$pdf->Cell(0, 10, $questf."\n");
$pdf->Ln();
}
$dir='C:/wamp/www/';
$filename= "filename.pdf";
$pdf ->Output($dir.$filename);
echo "Save PDF in folder";
But when it saved and displayed the messge Save PDF in Folder. I am unable to see the header part of the wordpress website.
Or when I use
$pdf->Output($filename,'D');
then is there any way that I can show the file in a link

When you are developing for Wordpress, you can't just echo text at any time. Wordpress has a whole series of actions it goes through to progressively generate the output rendered to the browser. If you generate output at an inappropriate time, you'll mess up Wordpress' ability to generate output at the right time.
If I were developing this, I'd have this function be called as a filter on the_content. Your output code would change to something like this:
function append_pdf_to_content($content) {
//Your existing code
$pdf->Output($filename, 'F');
$pdf_link = "<br><a href='$filename' download>Download PDF</a>"
return $content . $pdf_link;
}
add_filter('the_content', 'append_pdf_to_content');
If you wanted to use the D option, you'll need to link your users to a separate php page using a target='_blank' that calls the download. Otherwise the PDFs headers will override any headers Wordpress is trying to send.
BTW, you also might want to also take a look at mPDF, it's a fork of fpdf and remains in active development.

Related

Google Cloud Vision PHP — Make Batch Request

I need to perform an OCR analysis on an image for an university project.
I am imposed to use PHP, unfortunately, on the Google Cloud Vision Documentation few are the code sample using PHP...
I succeed to perform OCR on one image at time but 80% of the time I have a lot of images (around 20) to treat at once.
So I tried to use BatchRequest, to minimize the API calls, as specified here but I can't found how to build the $requests array they put at the top.
Btw I tried other APIs like Tesseract but the recognition is not accurate enough to use.
If you only want to perform a batch request you can just use batchAnnotateImages using ImageAnnotatorClient. Below you can find a sample using it as well as a way to create a request variable. Also, I include below a asyncBatchAnnotateImages sample but I recommend the one I mentioned earlier.
Using ImageAnnotatorClient with batchAnnotateImages
<?php
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature_Type;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\Image;
use Google\Cloud\Vision\V1\ImageSource;
use Google\Cloud\Vision\V1\AnnotateImageRequest;
use Google\Cloud\Vision\V1\Likelihood;
$client = new ImageAnnotatorClient();
try {
$feature = (new Feature())
->setType(Feature_Type::FACE_DETECTION);
$image = (new Image())
->setContent(file_get_contents("../images/family.jpg","r"));
$request = (new AnnotateImageRequest())
->setImage($image)
->setFeatures([$feature]);
$requests = [$request];
# note: you can add as many requests you want to perform. ie: [$request,$request2,..,..]
$results = $client->batchAnnotateImages($requests);
foreach($results->getResponses() as $result){
foreach ($result->getFaceAnnotations() as $faceAnnotation) {
$likelihood = Likelihood::name($faceAnnotation->getJoyLikelihood());
echo "Likelihood of headwear: $likelihood" . PHP_EOL;
}
}
} finally {
$client->close();
}
Using ImageAnnotatorClient with asyncBatchAnnotateImages
<?php
require '../vendor/autoload.php';
use Google\Cloud\Storage\StorageClient;
use Google\Cloud\Vision\V1\Feature;
use Google\Cloud\Vision\V1\Feature_Type;
use Google\Cloud\Vision\V1\ImageAnnotatorClient;
use Google\Cloud\Vision\V1\Image;
use Google\Cloud\Vision\V1\ImageSource;
use Google\Cloud\Vision\V1\AnnotateImageRequest;
use Google\Cloud\Vision\V1\asyncBatchAnnotateImages;
use Google\Cloud\Vision\V1\OutputConfig;
use Google\Cloud\Vision\V1\GcsDestination;
$client = new ImageAnnotatorClient();
try {
$feature = (new Feature())
->setType(Feature_Type::FACE_DETECTION);
$gcsImageUri = 'gs://<YOUR BUCKET ID>/<YOUR IMAGE FILE>';
$source = new ImageSource();
$source->setImageUri($gcsImageUri);
$image = (new Image())
->setSource($source);
$request = (new AnnotateImageRequest())
->setImage($image)
->setFeatures([$feature]);
$requests = [$request];
$gcsDestination = (new GcsDestination())
->setUri("gs://<YOUR BUCKET>/<OUTPUT FOLDER>/");
$outputConfig = (new OutputConfig())
->setGcsDestination($gcsDestination);
$operationResponse = $client->asyncBatchAnnotateImages($requests, $outputConfig);
$operationResponse->pollUntilComplete();
if ($operationResponse->operationSucceeded()) {
$result = $operationResponse->getResult();
var_dump($result);
#Your Folder output will have your file processing results.
}
} finally {
$client->close();
}
Note: To add on this, you can also check an official implementation of a similar case using vision client on this link but its a sample to detect text on a pdf file.
You can also find additional information on these links:
ImageAnnotatorClient
AnnotateImageRequest
AsyncBatchAnnotateImages
BatchAnnotateImagesResponse
AsyncBatchAnnotateImagesResponse
PHP CLOUD VISION Github Project Page

Edit an existing Pastebin document via API

I am trying to write a function in LUA to edit my pastebin code.
I can use this code to make a HTTP post:
http.post(string url, string postData [, table headers])
I can also use this code for a HTTP get:
http.get(string url [, table headers])
on the Pastebin website https://pastebin.com/api are information about using the API.
I am not sure, if this website can help me to solve my problem.
Does someone know how to fill the headers table?
this is the program i tried:
headers = {}
headers["api_dev_key"]= 'myDevKey...'; // your api_developer_key
headers["api_paste_code"] = 'my edited text'; // your paste text
headers["api_paste_private"] = '0'; // 0=public 1=unlisted 2=private
headers["api_paste_name"] = 'justmyfilename.php'; // name or title of your paste
headers["api_paste_expire_date"] = '10M';
headers["api_paste_format"] = 'php';
headers["api_user_key"] = ''; // if an invalid or expired api_user_key is used, an error will spawn. If no api_user_key is used, a guest paste will be created
headers["api_paste_name"] = myPastebinName;
headers["api_paste_code"] = myPastebinPassword;
http.get("https://pastebin.com/edit/dQMDfbkM", headers)
unfortunately this is not working and on the pastebin API help site is no exsample for editing a paste. just for creating a new one.
for me it is also not clear if I have to use post or get
There is no API for editing pastes directly.
You can only delete old paste and create new with updated text.

PHPexcel load an html formatted variable

i am trying to load an html snippet variable into a spreadsheet.I have differnet sections which may have different dynamic html content. So i cant just convert manually.
$dynamic_code_snippet = '<ul><li>item one</li><li>item two</li></ul>';
At the moment i am trying this but get errors:
if(!empty($dynamic_code_snippet)){
$excelHTMLReader = PHPExcel_IOFactory::createReader('HTML');
$snippet = $excelHTMLReader->load($dynamic_code_snippet);
$snippetWriter = PHPExcel_IOFactory::createWriter($snippet,'Excel2007');
ob_start();
$snippetWriter->save('php://output');
$code = ob_get_clean();
$table->getActiveSheet()->setCellValue('A1, $code);
}
I get an error:
Fatal error: Uncaught PHPExcel_Reader_Exception: Could not open in PHPExcel\Reader\Abstract.php on line 196
Do you think its because its a snippet not a full page html document(no <html><head><body> tags)?
Can it be done? or do i have to rethink?
PHPExcel does provide a helper wizard that can be used to convert basic html markup to Riche Text Objects that can be set as a cell value:
$wizard = new PHPExcel_Helper_HTML;
$richText = $wizard->toRichTextObject($html);
$objPHPExcel->setActiveSheetIndex(0)
->setCellValue('A1', $richText);
However, only some markup tags are actively supported, and ordered/unordered lists aren't included.
If you want to take a look at it, and see how the code actually works, possibly modify it to work with lists, then it's the HTML.php file in /Classes/PHPExcel/Helper.

Query strip is removed from open graph url

In relation to this question: Dynamic generation of Facebook Open Graph meta tags
I have followed these instructions but the api seems to remove my query string so that the url passed into the aggregation contains none of my dynamic information. If I enter the url with the query string into the debugger it doesn't remove it and works fine. I can confirm my og:url meta tag does also contain the same query string not just the base url. What am I doing wrong?
I was having a similar issue and solved it like this:
So assuming you're doing your post request like it shows in the tutorial, youre Javascript probably looks something like this:
function postNewAction()
{
passString = '&object=http://yoursite.com/appnamespace/object.php';
FB.api('/me/APP_NAMESPACE:ACTION' + passString,'post',
function(response) {
if (!response || response.error) {
alert(response.error.message);
}
else {
alert('Post was successful! Action ID: ' + response.id);
}
}
);
}
And since you say you want to generate meta tags dynamically, you're probably adding a parameter to the url (passString) there like so:
passString = '&object=http://yoursite.com/appnamespace/object.php?user=' + someuser;
This is wrong.
What you need to do is to make the url a 'pretty url' and use htaccess to decipher it. So:
passString = '&object=http://yoursite.com/appnamespace/object/someuser';
Then your htaccess file will tell your site that that url actually equates to
http://yoursite.com/appnamespace/object/object.php?user=someuser
Then you can use GET to store the user parameter with php and insert it however you like into your meta tags.
In case youre wondering, in the og:url meta tag's content will be:
$url = 'http://yoursite.com/appnamespace/object/object.php?user=' . $_GET[$user];
Does that help?

Add filter to FileUpload Control

How to add filter to the fileupload control in asp.net? I want a filter for Word Template File (.dot).
You could also do a javascript alternative to filtering it server side (you'd probably want to do that as well) but this saves the client from spending the time waiting on an upload to finish just to find out it was the wrong type.
http://javascript.internet.com/forms/upload-filter.html
So basically you just run a javascript function on submit that parses off the extension of the uploaded file and gives them an alert if its not of the right type.
You could also use document.forms[0].submit(); instead of passing the form reference through (as ASP.NET really only uses a single form (unless your doing something funky))
string fileName = fuFiles.FileName;
if(fileName.Contains(".dot"))
{
fuFiles.SaveAs(Server.MapPath("~/Files/" + fileName));
}
If you mean to filter the file extensions client/side, with the standard browser's file selector, isn't possible.
To do that you have to use a mixed type of upload, such as SWFUpload, based on a flash uploader system (that's a really nice techinque: it allows you to post more than a file at time).
The only thing you can do in standard mode is to filter the already posted file, and I suggest to use System.IO.Path namespace utility:
if (Path.GetExtension(upFile.FileName).ToUpper().CompareTo(".DOT") == 0)
{
/* do what you want with file here */
}
Check the filename of the uploaded file serverside:
FileUpload1.PostedFile.FileName
Unless you want to use java or something similar on the client, there's really not much you can do for filtering uploaded files before they're sent to the server.
Here I have a small method that I used to filter which types of files can be uploaded by the fileupload control named fuLogo.
if (fuLogo.HasFile)
{
int counter = 0;
string[] fileBreak = fuLogo.FileName.Split(new char[] { '.' });
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString()+ "." + fileBreak[1]);
if (fileBreak[1].ToUpper() == "GIF" || fileBreak[1].ToUpper() == "PNG")
{
while (System.IO.File.Exists(logo))
{
counter++;
logo = Server.MapPath("../Images/Logos/" + fileBreak[0] + counter.ToString() + "." + fileBreak[1]);
}
}
else
{
cvValidation.ErrorMessage = "This site does not support any other image format than .Png or .Gif . Please save your image in one of these file formats then try again.";
cvValidation.IsValid = false;
}
fuLogo.SaveAs(logo);
}
basically, I first Iterates through the directory to see if a file already exists. Should the file exist, (example picture0.gif) , it will increase the counter (to picture1.gif). It prevents that different users will overwrite each other's pictures should their pictures have the same name.

Resources