How to get Blade template view as a raw HTML string? - php

I need the HTML of my Blade template as a string.
I'm going to use that HTML string to generate a PDF from it.
At the moment I have Blade streaming as a response back to browsers.
return view('users.edit', compact('user'));
How can I get the raw HTML string from the blade template?

You can call render() on the view.
$html = view('users.edit', compact('user'))->render();
See the View source code for more information.

This is the perfect solution of download/converting a blade file to HTML.
$view = view('welcome')->render();
header("Content-type: text/html");
header("Content-Disposition: attachment; filename=view.html");
return $view;

<!-- View stored in resources/views/greeting.blade.php -->
<html>
<body>
<h1>Hello, {{ $name }}</h1>
</body>
</html>
<!-- In your php controller -->
return view('greeting', ['name' => 'James']);
edited
<!-- In your PHP controller You can add html variable , and then use it for example to print PDF -->
$html=view('greeting', ['name' => 'James']);
$pdf = \App::make('snappy.pdf.wrapper');
$output = $pdf->loadHTML($html)->output();
$headers = [
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'inline; filename="' . $filename . '"',
];
\Storage::put("pdfs/$filename", $output);
return response()->download(storage_path("app\\pdfs\\$filename"), $filename . '.pdf', $headers);
<!-- or return \Response::make($output, 200, $headers); -->
to use snappy you need to follow the instructions :
https://github.com/barryvdh/laravel-snappy
1. Download wkhtmltopdf from here https://wkhtmltopdf.org/downloads.html
2. Package Installation: composer require barryvdh/laravel-snappy
3. In (app.php) providers array add Barryvdh\Snappy\ServiceProvider::class,
4. In (app.php) aliases array add 'PDF' => Barryvdh\Snappy\Facades\SnappyPdf::class, 'SnappyImage' => Barryvdh\Snappy\Facades\SnappyImage::class,
5. Run php artisan vendor:publish --provider="Barryvdh\Snappy\ServiceProvider"
6. In (snappy.php) edit the binary path based on your installation path for wkhtmltopdf For me it is the following :
return array(
'pdf' => array(
'enabled' => true,
// base_path('vendor\wemersonjanuario\wkhtmltopdf-windows\bin\64bit\wkhtmltopdf'),
'binary' =>'"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
'timeout' => false,
'options' => array(),
'env' => array(),
),
'image' => array(
'enabled' => true,
'binary' =>'"C:\Program Files\wkhtmltopdf\bin\wkhtmltopdf"',
'timeout' => false,
'options' => array(),
'env' => array(),
),
);

Will return as sting
$myViewData = View::make('test.view',compact('data'))->render();
Good luck!

Related

Telegram sendPhoto with multipart/form-data not working?

Hi I am trying to send an image. The documentation states that I can send a file using multipart/form-data.
Here is my code:
// I checked it, there really is a file.
$file = File::get(Storage::disk('local')->path('test.jpeg')) // it's the same as file_get_contents();
// Here I use the longman/telegram-bot library.
$serverResponse = Request::sendPhoto([
'chat_id' => $this->tg_user_chat_id,
'photo' => $file
]);
// Here I use Guzzle because I thought that there might be an
// error due to the longman/telegram-bot library.
$client = new Client();
$response = $client->post("https://api.telegram.org/$telegram->botToken/sendPhoto", [
'multipart' => [
[
'name' => 'photo',
'contents' => $file
],
[
'name' => 'chat_id',
'contents' => $this->tg_user_chat_id
]
]
]);
Log::info('_response', ['_' => $response->getBody()]);
Log::info(env('APP_URL') . "/storage/$url");
Log::info('response:', ['_' => $serverResponse->getResult()]);
Log::info('ok:', ['_' => $serverResponse->getOk()]);
Log::info('error_code:', ['_' => $serverResponse->getErrorCode()]);
Log::info('raw_data:', ['_' => $serverResponse->getRawData()]);
In both cases, I get this response:
{\"ok\":false,\"error_code\":400,\"description\":\"Bad Request: invalid file HTTP URL specified: Wrong URL host\"}
Other download methods (by ID and by link) work. Can anyone please point me in the right direction?
Using the php-telegram-bot
library, sendPhoto can be used like so:
<?php
require __DIR__ . '/vendor/autoload.php';
use Longman\TelegramBot\Telegram;
use Longman\TelegramBot\Request;
// File
$file = Request::encodeFile('/tmp/image.jpeg');
// Bot
$key = '859163076:something';
$telegram = new Telegram($key);
// sendPhoto
$chatId = 000001;
$serverResponse = Request::sendPhoto([
'chat_id' => $chatId,
'photo' => $file
]);
The trick is to use Request::encodeFile to read the local image.

Yii2 send pdf to mail not working?

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');
}
...

How to save generated PDF with JasperReports into server Yii

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;
}

Symfony 2 kpn snappy generate pdf with output meets security area

I`m using Symfony2 kpn snappy bundle to generate pdfs. I want to generate PDF from an html page with css. I found a solution, but it has a problem with :
$pageUrl = $this->generateUrl('accounts_management_generate_pdf_markup',
array('invoice' => $invoiceData), true); // use absolute path!
return new \Symfony\Component\HttpFoundation\Response(
$this->get('knp_snappy.pdf')->getOutput($pageUrl), 200, array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);
The problem is that the pageUrl accounts_management_generate_pdf_markup is behind a security area and cannot be accessed without authentication. The generated file is just the login page, to which this path accounts_management_generate_pdf_markup redirects if not logged.
My questions are:
Is there any way to pass to snappy authentication credentials?
Is there another way using snappy bundle to generate the pdf using styles(css)
You can add the session cookie as an argument to the getOutput function:
$pageUrl = $this->generateUrl('route', array('id' => $id), true);
$session = $this->get('session');
$session->save();
session_write_close();
return new Response(
$this->get('knp_snappy.pdf')->getOutput($pageUrl, array('cookie' => array($session->getName() => $session->getId()))),
200,
array(
'Content-Type' => 'application/pdf',
'Content-Disposition' => 'attachment; filename="file.pdf"'
)
);

print screen > ckeditor > CakePHP CakeEmail

I have a CKEditor 3.6.5 (revision 7647) field (on a CakePHP 2.2.1 site) where users paste print screen images (only works on Firefox). The html generated by the paste (button paste from word) is something like this:
<img alt="" src="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==" />
At a certain point I have to send by Email the html on these fields which should include the images.
Reading [base64-encoded-images-in-email-signatures][1] and [how-to-embed-images-in-email][2] I figured that the Email should have an attachment with the image.
My question is how can I transform the src of the image on a file? This way I intend to transform the HTML before send.
I have tried with success to attach a file with:
$data = base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAUA AAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO 9TXL0Y4OHwAAAABJRU5ErkJggg==');//file_get_contents('http://' . env('HTTP_HOST') . $fileInfo['url'] . '/disable-auth-key:' . Configure::read('Security.salt') . '.' . $fileInfo['ext']);
$handle = fopen(TMP . 'print_screen.png', 'w+');
fwrite($handle, $data);
fclose($handle);
$email = new CakeEmail(array(
'log' => true,
'config' => 'smtp',
'returnPath' => 'return#mydomain.pt',
'from' => array('app#mydomain.pt' => 'APP'),
'to' => array('name#domain.pt' => 'Name'),
'emailFormat' => 'html',
'subject' => 'image test',
'domain' => '#uab.pt',
'attachments' => array(
'print_screen.png' => array(
'file' => TMP . 'print_screen.png',
'mimetype' => 'image/png',
'contentId' => 'Print-Screen-01'
)
)
));
$email->send('test|<img src="cid:print_screen.png#Print-Screen-01">|');
On GMail I have access to the attachment file but on the body no image. Where is the source
<div id=":85x">test|<img>|</div>
On Outlook, no attachments and the source is
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">test|<img src="cid:print_screen.png#Print-Screen-01">
I'm also open to other solutions that achieve the same result.
on the src attribute of the image tag the cid value should be I was using #.
The correct line of code
$email->send('test|<img src="cid:Print-Screen-01">|');

Categories