I need to save my generated PDF file into my server. I am using JasperReports.
Code sample for PDF generation:
$this->widget('ext.Yiijasperserver.Yiijasperserver', array(
'path' => '/reports/Crescent/call_list_report',
'format' => 'pdf',
'out' => 'I',
'file' => 'call_list_report',
'parameter' => array(
'user_id' => $user_id,
'from_date' => $from_date,
'to_date' => $to_date,
'status_id' => $status_id
)
));
Finally i got the answer. Added below code in Yiijasperserver.php file in extension folder yii
public function run()
{
$client = new Jasper\JasperClient('localhost',
8080,
'jasperadmin',
'jaspSyo#321*',
'/jasperserver');
$report = $client->runReport($this->path, $this->format,$this->page,$this->parameter);
header('Content-type: '.$this->mimetype[$this->format]);
if($this->out=="I")
header('Content-Disposition: inline; filename="'.$this->file.'.'.$this->format.'"');
if($this->out=="D")
header('Content-Disposition: attachment; filename="'.$this->file.'.'.$this->format.'"');
$file1 = 'C:\HostingSpaces\new.pdf';//New code added
file_put_contents($file1, $report);//New code added
echo $report;
}
Related
Actually this code is uploading files to normal Gdrive but i need to upload my files into the shared drive can anyone help me. All i need is to Upload my files to to my shared drive. Below is my current code :-
require __DIR__ . '/vendor/autoload.php';
use Google\Client;
use Google\Service\Drive;
# TODO - PHP client currently chokes on fetching start page token
function uploadBasic()
{
try {
$client = new Client();
putenv('GOOGLE_APPLICATION_CREDENTIALS=./credentials.json');
$client->useApplicationDefaultCredentials();
$client->addScope(Drive::DRIVE);
$driveService = new Drive($client);
$file = getcwd().'/637fdc0994855.mp4';
$filename = basename($file);
$mimeType = mime_content_type($file);
$fileMetadata = new Drive\DriveFile(array(
'name' => $filename,
'parents' => ['1VBi8C04HBonM6L4CfL-jHWZ0QoQRyrCL']
));
$content = file_get_contents('637fdc0994855.mp4');
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
printf("File ID: %s\n", $file->id);
return $file->id;
} catch (Exception $e) {
echo "Error Message: " . $e;
}
}
uploadBasic();
In order to upload the file to the shared drive, please modify as follows.
From:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id'
));
To:
$file = $driveService->files->create($fileMetadata, array(
'data' => $content,
'mimeType' => $mimeType,
'uploadType' => 'multipart',
'fields' => 'id',
'supportsAllDrives' => true // <--- Added
));
Note:
In this case, your client has no permission for writing the shared drive, an error occurs. Please be careful about this.
Reference:
Files: create
I am using kartik mpdf extension to generate using the mention below code it work and show the pdf in next tab
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
return $pdf->render();
Now for send the generatd pdf on mail i want to send the mail before save it on server using below code
$content = $pdf->content;
$filename = $pdf->filename;
$sendemail=Yii::$app->mail->compose()
->attachContent($content, [
'fileName' => $filename,
'contentType' => 'application/pdf'
])
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
Try my best to hit api and generate pdf but this also doesnt work.
$mpdf = $pdf->getApi();
$mpdf->WriteHTML($content);
$path = $mpdf->Output(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf', 'F');
It also retrn Null
First i have save the generated pdf in the server directory and then send it to mail and unlink after sending succcessfully using the below code
$pdf = new Pdf([
'mode' => Pdf::MODE_UTF8, // leaner size using standard fonts
'filename' => 'Bill_of_lading_'.$exportDetail->booking_number.'_'.$customerDetail->customer_name.'_'.$customerDetail->company_name.'.pdf',
'content' => $this->renderPartial('landing', [
'model' => $this->findModel($id),
]),
'options' => [
'title' => 'Privacy Policy - Krajee.com',
'subject' => 'Generating PDF files via yii2-mpdf extension has never been easy'
],
'methods' => [
'SetHeader' => ['Generated By: ARIANA WORLDWIDE||Generated On: ' . date("r")],
'SetFooter' => ['|Page {PAGENO}|'],
]
]);
if($mail){
$content = $pdf->content;
$filename = $pdf->filename;
// $mpdf = $pdf->getApi();
// $mpdf->WriteHtml($content);
$path = $pdf->Output($content,Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf',\Mpdf\Output\Destination::FILE);
$sendemail=Yii::$app->mail->compose()
->attach(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf')
->setFrom('mushahidh224#gmail.com')
->setTo('rajwabarocho#gmail.com')
->setSubject('Design Beta sending subject here')
->send();
if($sendemail)
{
unlink(Yii::getAlias('#backend').'/uploads/pdf/'.$filename.'.pdf');
return $this->render('mailed');
}
I cant find where the exact error is but I had successfully generated pdf via mpdf with
$model= $this->findModel($id);
// get your HTML raw content without any layouts or scripts
$content = $this->renderPartial('print_salaryslip',['model'=>$model]);
// setup kartik\mpdf\Pdf component
$pdf = new Pdf([
// set to use core fonts only
'mode' => Pdf::MODE_BLANK,
// A4 paper format
'format' => Pdf::FORMAT_A4,
// portrait orientation
'orientation' => Pdf::ORIENT_PORTRAIT,
// stream to browser inline
'destination' => Pdf::DEST_BROWSER,
// your html content input
'content' => $content,
// format content from your own css file if needed or use the
// enhanced bootstrap css built by Krajee for mPDF formatting
'cssFile' => '#vendor/kartik-v/yii2-mpdf/assets/kv-mpdf-bootstrap.min.css',
// any css to be embedded if required
'cssInline' => '.kv-heading-1{font-size:18px}',
// set mPDF properties on the fly
'options' => ['title' => 'Krajee Report Title'],
// call mPDF methods on the fly
'methods' => [
'SetHeader'=>[' PAYSLIP'],
'SetFooter'=>['{PAGENO}'],
]
]);
// return the pdf output as per the destination setting
return $pdf->render();
and make sure the$contentis pure html.
Do something like this
...
if (!empty($id)) {
$emailSend = Yii::$app->mailer->compose(['html' =>'My-template-html'],[
'email' => $receiver->email,
'name' => $receiver->name
])
->setFrom(["info#mail.com"])
->setTo($email)
->setSubject($subject)
->attach(Yii::getAlias('#backend').'/web/uploads/pdf/'.'Certificate'.'.pdf');
return $emailSend->send();
Yii::$app->session->setFlash('success', 'Email Sent Successfully');
}
...
I have a form that once submitted pulls some data from my database that I attempted to have download immediately into a csv document.
For some reason the data is all fine, in the correct csv format however it only appears in the console log in my Firefox browser rather than a file that is automatically downloaded e.g exported.csv
I have the following functions - I get no errors as everything is working but for some reason it doesn't download the csv automatically.. I presume my issue is within my outputCsv function.
Any ideas?
public function actionSurveyStats()
{
$id = Yii::app()->getRequest()->getQuery('id');
$model = SurveyQuestionnaires::model()->findByPK($id);
$this->bodyTitle = 'Your Survey';
if (isset($_POST[get_class($model)])) {
set_time_limit(0);
ini_set('memory_limit', '786M');
$filename = 'questionnaire_' .time(). '.csv';
$completed->questionnaire_id = Yii::app()->request->getPost('questionnaire_id');
$organisation_id = $_POST[get_class($model)]['organisation_id'];
$this->outputCsv($model->getExportData($organisation_id), $filename);
}
$this->render('survey_stats',array(
'model' => $model,
));
}
protected function outputCsv($rows, $filename = '') {
if (empty($filename)) {
$filename = (!is_null($this->model)) ? (strtolower(get_class($this->model)."_".$this->model->getPrimaryKey().".csv")) : "export.csv";
}
header('Content-Description: File Transfer');
header("Content-Type: application/csv") ;
header("Content-Disposition: attachment; filename=$filename");
header("Pragma: no-cache");
header("Cache-control: private");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
$fp = fopen('php://output', 'w');
foreach($rows as $row) {
fputcsv($fp, $row);
}
echo stream_get_contents($fp);
fclose($fp);
app()->end();
}
My fix... was the ajax in the form.. set this to false & it works now! Thanks Yogesh
Simply needed to set 'enableAjaxValidation' to false.
<?php $form=$this->beginWidget('bootstrap.widgets.TbActiveForm',array(
'id' => get_class($model),
'type' => 'horizontal',
'enableAjaxValidation' => false,
'clientOptions' => array(
'validateOnSubmit' => true,
'validateOnChange' => false,
'validateOnType' => false,
),
'htmlOptions' => array(
'class' => '',
'autocomplete' => 'off',
'enctype' => 'multipart/form-data'
),
)); ?>
I have set up my database collation to utf8_unicode_ci, and on my CakePHP database setup.
class DATABASE_CONFIG {
public $default = array(
'datasource' => 'Database/Mysql',
'persistent' => false,
'host' => 'xxx',
'login' => 'xxx',
'password' => 'xxx',
'database' => 'thisisdatabase',
'prefix' => '',
'encoding' => 'utf8',
);
}
I set up download binary file like this:
$this->viewClass = 'Media';
$params = array(
'id' => $download_list[0],
'download' => true,
'extension' => $download_file_ext,
'path' => $fileDownloadPath . DS,
);
$this->set($params);
When the user uploads a file, the filename will be recorded in the database as unicode-utf8. When I download through Chrome, FF, it comes out fine (the Japanese name will still be intact). But when I download through IE, the filename is garbage. Although the file itself is fine (I can open it, etc).
Anyone know how to solve this?
I am not sure about how CakePHP handles this scenario, but IE has problems with sending Unicode letters in filename header for content-disposition: attachment. So to fix this in IE, we need to url-encode the filename before setting it into the header:
$filename = 'someunicodefilename.txt';
if(// IE) {
$filename = urlencode($filename);
}
header('Content-Disposition: attachment; filename="' . $filename . '"');
So I am not sure how to achieve this in CakePHP, but you can try this:
$this->viewClass = 'Media';
$filename = 'someunicodefilename.txt';
if(// IE) {
$filename = urlencode($filename);
}
$params = array(
'id' => $download_list[0],
'name' => $filename,
'download' => true,
'extension' => $download_file_ext,
'path' => $fileDownloadPath . DS,
);
$this->set($params);
I have one form. When user submit the form, I will store the data on database and generate the pdf of the same. Here what I want to do is:
Download PDF file;
Save the PDF in a folder.
Downloading the PDF is working perfectly, but it is not being saved in a folder.
public function get_pdf() {
$count = 1;
for ($i = 0; $i < count($_POST['description']); $i++) {
$table_data[] = array(
'serial' => $count,
'description' => $_POST['description'][$i],
'unit' => $_POST['unit'][$i],
'quantity' => $_POST['quantity'][$i],
'rate' => $_POST['rate'][$i],
'amount' => $_POST['amount'][$i]
);
$count++;
}
if (!empty($table_data)) {
// loading pdf library //
$this->load->library('cezpdf');
// field names //
$table_data_field = array(
'serial' => 'S.No.',
'description' => 'Work Description',
'unit' => 'Unit',
'quantity' => 'Quantity',
'rate' => 'Rate',
'amount' => 'Amount'
);
$this->cezpdf->ezTable($table_data, $table_data_field, 'Quotation', array('width' => 500, 'justification' => 'center'));
ob_start();
$this->cezpdf->ezStream();
$data = ob_get_contents();
ob_end_clean();
// save the quotation file on client folder //
move_uploaded_file('Quotation', FCPATH . '/quotation/' . $data);
// force to download the file //
$this->load->helper('download');
force_download('Quotation.pdf', $data);
}
}
Please help me on this. I use CodeIgniter.
Firstly, I don't think you ought to be using move_uploaded_file, and secondly, the name of your file contains the contents of the PDF, not a filename.