generate weekly report pdf with mpdf - functions.php - php

I'm using mpdf on wordpress for generating PDF files. I'm working on a functionality which will send weekly report to my users and that report should be send as email and pdf will be attached in email.
My issue is that I'm running code in functions.php file because for running this code every week, I'm going to use server side cron job and my function should be inside functions.php file to execute it. So I added this code in functions.php file:
function weeklyReportFunc(){
include('mpdf/mpdf.php');
$mpdf = new mPDF();
ob_start();
require get_template_directory() . '/includes/report.php';
$x = ob_get_contents();
ob_end_clean();
$mpdf->WriteHTML($x);
$today = date('Y-m-d');
$pdfName = 'weekly-report-'.$today;
$mpdf->Output($pdfName.'.pdf', 'D');
}
And this shows me below error:
Warning: Cannot modify header information - headers already sent by (output started at
/home/user/public_html/doms/wp-admin/includes/template.php:1995) in /home/user/public_html/
doms/wp-content/themes/mytheme/mpdf/mpdf.php on line 8314
Warning: Cannot modify header information - headers already sent by (output started at
/home/user/public_html/doms/wp-admin/includes/template.php:1995) in
/home/user/public_html/doms/wp-content/themes/mytheme/mpdf/mpdf.php on line 1706
mPDF error: Some data has already been output to browser, can't send PDF file
How can I solve this? Maybe I need to use my function in some action? but which one? Any ideas please?

Finally found solution. So I created a php file in my theme folder and at the very top of the file added require('../../../wp-load.php'); code which makes all wordpress functions available inside it, even if this file is not a wordpress template page. So as now all functions are available inside this file, I moved my code from functions.php file to this file and I'm already running cron job on this file. Hope this will help someone else.

Save report.php output buffer to $x using exec():
function weeklyReportFunc(){
ob_start();
include('mpdf/mpdf.php');
$mpdf = new mPDF();
exec('php -f '.get_template_directory().'/includes/report.php',$output);
$x = $output[0];
$mpdf->WriteHTML($x);
$today = date('Y-m-d');
$pdfName = 'weekly-report-'.$today;
$mpdf->Output($pdfName.'.pdf', 'D');
}

Related

PHP Wkhtmltopdf not found

I want to convert a webpage to PDF in PHP using the library wkhtmltopdf. I'm using this PHP wrapper mikehaertl/phpwkhtmltopdf available here. I downloaded wkhtmltopdf binary from here and I used the below PHP code to point to it :
require __DIR__.'/vendor/autoload.php';
$pdfName = 'Invoice1.pdf';
$pdf = new mikehaertl\wkhtmlto\Pdf("some HTML code here");
$pdf->binary = __DIR__.'/wkhtmltopdf_0.12.4/bin/wkhtmltopdf';
if (!$pdf->send($pdfName, true)) {
echo $pdf->getError();
}
I'm getting this error: sh: 1: /var/www/mysite/public_html/wkhtmltopdf_0.12.4/bin/wkhtmltopdf: not found
I don't understand why it is saying file not found. I tried to check with PHP if the file exists using file_exists and it returns true when I provide to it that location.
Any help please?
Thanks.

Starting external programme from PHP

I am running in a Windows10 environment. My php script writes a pdf file and I simply want to have the file open up in the pdf viewer that I specify. I am using the "runAsynchronously" function given in the PHP manual and I have tried many variations. I have no problem getting the process to run in the background - it appears every time in my TaskManager process listing, but no window appears - what am I doing wrong? If I double click the link file that has been written it works fine. It is nothing to do with the path to the executable or the filename - I can replace the pdf viewer with "notepad.exe" and the $file with a suitable text file - the same thing happens, notepad appears as a process, but not as a window, and the link works fine.
Here are some code snippets
$cmd = "C:\\Program Files (x86)\\SumatraPDF\\SumatraPDF.exe";
runAsynchronously($cmd, $file, 7, null, true);
function runAsynchronously($path, $arguments, $windowstyle=1, $lnkfile=null, $exec=true) {
$tmp = (is_null($lnkfile)) ? 'C:\temp\temp.lnk' : $lnkfile;
try {
if(file_exists($tmp)) { unlink($tmp); }
$WshShell = new COM("WScript.Shell");
$oShellLink = $WshShell->CreateShortcut($tmp);
$oShellLink->TargetPath = $path;
$oShellLink->Arguments = $arguments;
$oShellLink->WorkingDirectory = dirname($path);
$oShellLink->WindowStyle = 1;
$oShellLink->Save();
$waitforcompletion = false;
if($exec) {
// Run kicks off the process in the background, but no window gets opened
$oExec = $WshShell->Run($tmp, $windowstyle, $waitforcompletion);
unlink($tmp);
} // if not executed link is left available for manual running
unset($WshShell,$oShellLink,$oExec);
} catch(Exception $ex) {
print $ex->getMessage();
}
}
If opening in the browser a pdf or downloading it solves your problem, try a class called PDFMerger:
https://github.com/clegginabox/pdf-merger
It uses an API called setasign FPDI and FPDF (https://packagist.org/packages/setasign/fpdi-fpdf#p-456)
I tested it here, because it also interested me and worked ok. (Wamp in Windows 8.1)
I put everything together(classes and folders of fpdi and fpdf) in a folder called pdfmerger because I was having some difficulty with namespaces and my code worked ok, but I know this is not the best way to include the classes - the example in GitHub page must help if you have problems with classes not finding classes):
<?php
include "pdfmerger/fpdf.php";
include "pdfmerger/fpdi.php";
include 'pdfmerger/PDFMerger.php';
$pdf = new PDFMerger();
//generate a pdf with the pages 1,2 and 3 and send to browser
$pdf->addPDF('originalpdfsavedintheserver.pdf', '1,2,3')
->merge('browser', 'nameinbrowser.pdf');
// REPLACE 'browser' WITH 'file', 'download', 'string', or 'browser' for output options
If you use the option 'download' you can choose the program that will open the pdf file in your windows settings(Choose default program to open pdfs):
https://www.cnet.com/how-to/how-to-set-default-programs-in-windows-10/

How to process PHP code in a text string, to prevent it from being seen as text?

I'm using the Redactor editor in a custom built CMS. Redactor has an option, phpTags, which when set to true allows PHP code to be entered and saved as part of the content.
The issue is that this PHP code is being seen as text, not PHP code, and is being escaped rather than being processed.
For example, if I enter this in the editor:
<?php echo date('Y'); ?>
Instead of the year being displayed, the code is commented out in the page's markup, like so:
<!--?php echo date('Y'); ?-->
How can I prevent this from happening? To make sure the PHP code is processed/interpreted as such by the server?
I should probably mention that there are a lot of people using this CMS, so there's no way to know what PHP code may be added in advance.
Perhaps
<!-- <?php echo date('Y') ?> -->
You can't change PHP's opening/closing tags like you are, not without a recompile of PHP. If you want to hide php's output, then surround the entire php code block with html comment tags.
PHP won't care about the html comments. It couldn't care at all what it's embedded in. You could stuff a PHP code block into the middle of a .jpg file and it'd still execute, as long as the webserver's configured to run .jpg files through the PHP interpreter.
To fix this issue I took the content I was previously just displaying via echo, and saved it to a temporary file.
Then I turned on output buffering, included that temporary file in the PHP script, and grabbed its contents via ob_get_contents().
This allowed me to display the content with all the PHP within having been parsed. Here's the code for reference:
// Create path to temporary file
$tmpPath = '/temp.php';
// Set file variable to null for error checking
$tmpFile = NULL;
// Try creating the temporary file
if ( $tmpFile = fopen($tmpPath, 'w') ) {
if ( fwrite($tmpFile, $postContent) === FALSE ) {
// Do something if the file can't be written to
} else {
// Close file
fclose($tmpFile);
}
}
// Start output buffereing
ob_start();
// Include the temporary file created above
include $tmpPath;
// Save buffered contents to a variable
$content = ob_get_contents();
// End output buffering
ob_end_clean();
// Display content
echo $content;
I appreciate the various comments to my question, as it helped prod me in the right direction to getting this figured out.

pass mysql value from php page to a joomla article and display relevant data inside of a joomla article

we are developing an application.website is being developed by joomla.Admin panel is being developed using a pure php.on index page(joomla), we are displaying some details from the backend.
my question is this, when we click on one of the records on that page can we display the relevant data inside of a article?
Hope i asked the question clearly.
please share your thoughts with us.
thanks in advance
Yes, you can do this, if I understand your question correctly.
Open up Joomla's main index.php. This is the index.php in the html root, not the index.php in one of the template folders.
Near the bottom of the file, or maybe the very last line you will see something like this:
// Return the response.
echo $app
Replace this line with the following:
// Return the response.
// parse $app for server side includes statements and execute them
// note: this will only work for executable code, it will not import text or html files
// we would need to check to see if the file were executable, then read it rather than execute it if it were not
$output = $app;
while(ereg('(<!--#include virtual="([^&]+)" -->)',$output,$groups)){ // extract the ssi command and the command
$i = 0;
while(!$inline){ // sometimes exec() fails for want of memory so we try a few times
exec($groups[2],$array); // get the output from the command
foreach ($array as $element) // concatenate the lines of output into a single string
$inline = $inline . $element . "\n"; // appending a new line makes the html source more readable
$i++;
if($inline | $i > 5)
break;
sleep(1);
}
$output = ereg_replace($groups[1],$inline,$output); // replace the ssi command with the output
}
echo $output;
This will allow you to place a standard server side includes statement in your article. Fore example if you want to execute a php file in the same directory as your index.php and the file is called dynamic_content.php you would type this in your article:
<!--#include virtual="dynamic_content.php"-->
The output of that script will then be included in the text of the article. You can have multiple ssi commands in the same article.

Return html response from PHP page in to variable

I am trying to generate an email with some HTML that is created via another PHP file.
Email generating file is run by a cron running every hour.
Another file exists that generates the HTML required for the email.
The HTML generating file does not have a function that I can call, for instance:
$emailBody = generateHTML($id);
The HTML generating file was designed to be included on a page that you wished to display the HTML, for instance:
include "htmlGenerator.php";
My question is: How can I get what the htmlgenerator.php file returns in to a variable, ready to be pushed in to an email.
Apologies if this is not very clear, I will be happy to answer any questions.
Thanks in advance!
If I understood what you said, you can use output buffering,
so that you can get the output of htmlGenerator.php
For example:
ob_start();
// as an example
echo "Hello World";
// or in our case
include "htmlGenerator.php";
$result = ob_get_contents();
ob_end_clean();
You can also create a simple function like this:
function include_output($filename)
{
ob_start();
include $filename;
$contents = ob_get_contents();
ob_end_clean();
return $contents;
}
$mycontent = include_output("htmlGenerator.php");
Read the php documentation for further details.
Check out the built-in functions ob_start and ob_get_clean.
You can then do something like:
ob_start();
include( "file.php");
$var = ob_get_clean();

Categories