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');
}
...
Related
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.
I have an API to save images and files
this is the code to save the image request from the API
$file = $request->file('gambar');
$fileName = $file->getClientOriginalName();
$file->storeAs('images/berita', $fileName);
$berita = new Berita;
$berita->judul = $request->judul;
$berita->kategori_id = $request->kategori_id;
$berita->isi = $request->isi;
$berita->gambar = $fileName;
$berita->tgl = $request->tgl;
$berita->user_id = $request->user_id;
$berita->save();
return response()->json([
'message' => 'Data berita Added Successfully!',
'Added berita' => $berita
], Response::HTTP_OK);
I already try the API in postman, and everything went well, image sucessfully uploaded.
Then on the client side, I'm using HTTP Client from Laravel to POST the data to the API. And here's the code.
$Berita = Http::withToken('xxx')
->attach('attachment', file_get_contents($request->file('gambar')))
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'gambar' => file_get_contents($request->file('gambar')),
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
return $Berita;
All the data send successfully, except the gambar which contains the image that i sent. It says that in my API validation.
The gambar must be a file of type: jpeg, jpg, png.
It thought that means the image that i send is sent as a string, so it didn't receive it as a file.
By the way, here's the Laravel documentation about HTTP Client: https://laravel.com/docs/9.x/http-client#multi-part-requests
Does anyone knows how to correctly using it? I think i've misused it.
I think there is problem with attachment.
return Http::withToken('xxx')
->attach('gambar', file_get_contents($request->file('gambar')), , 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
or
return Http::withToken('xxx')
->attach('gambar', $request->file('gambar'), 'gambar.png')
->post('https://api.xxx.my.id/xxx', [
'judul' => $request->judul,
'kategori_id' => $request->kategori_id,
'isi' => $request->isi,
'tgl' => $request->tgl,
'user_id' => $request->user_id
]);
This is because the server cannot read your data.
You should send the data using the application/x-www-form-urlencoded content type, you can achieve this as Laravel documentation says:
$response = Http::asForm()->post('http://example.com/users', [
'name' => 'Sara',
'role' => 'Privacy Consultant',
]);
I use Onesignal notifications for the app.
I don't have a problem sending the notifications but wanted to send these notifications using API help and this library.
php-onesignal library
The notifications I sent must be opened on the relevant page in the application. For this reason, I do not know how to write the URL in the code section below.
require_once(dirname(__FILE__).'/vendor/autoload.php');
use CWG\OneSignal\OneSignal;
$appID = '92b9c6bb-89d2-4cbc-8862-a80e4e81a251';
$authorizationRestApiKey = 'MWRjMTg2MjEtNTBmYS00ODA4LWE1M2EtM2YyZjU5ZmRkNGQ5';
$deviceID = '69aeecc1-7b58-44d1-8000-7767de437adf';
$api = new OneSignal($appID, $authorizationRestApiKey);
$retorno = $api->notification->setBody('Ola')
->setTitle('Titulo')
->addDevice($deviceID)
->send();
I entered the addTag section as in the Onesignal panel, but I could not run it.
$retorno = $api->notification->setBody('Ola')
->setTitle('Titulo')
->addTag('url', 'http://www.example.com/news/testtitle')
->send();
print_r($retorno);
How can I use it here in the Url section of the "ADDITIONAL DATA" field?
Can I solve this problem with addTag?
The following will send a notification with the $data['data'] as additional, as you want.
$data = [
'headings' => ['en' => 'Case 123'],
'contents' => ['en' => 'Case assigned ' . date('d-m-Y H:i')],
'data' => [
'type' => 'new',
'user_id' => 123,
'url' => 'http://www.example.com/news/testtitle'
],
];
OneSignal::sendNotificationCustom([
'app_id' => 1234,
'api_key' => abcd,
'included_segments' => ['All'],
'headings' => $data['headings'],
'contents' => $data['contents'],
'data' => $data['data'],
]);
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!
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.