I have PDF stored in a folder, now i want to view it via link on my form page. How will i do it using Yii framework.
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/Tutorial.pdf') ,
array('class'=>'button','target'=>'_blank'));
The error i am receiving mentioned below, i have also tried by including uploads in allow of controller.
Error
Error 404
Unable to resolve the request "uploads/Tutorial.pdf".
I am using mPDF to generate PDF but i don't know how to view an already generated PDF using Yii.
You need several more things to make this work. You may have already done some of this and not pasted it but here goes...
I'm assuming you've set up your site to use clean URLs with .htaccess by following this tutorial. Now you can add:
in config/main.php, urlMananger section you need a route to a controller class and action method. This tells Yii which controller to use when you go to the URL /uploads/Tutorial.pdf
'urlManager'=>array(
'urlFormat'=>'path',
'showScriptName'=>false,
'rules'=>array(
'uploads/<filename:[a-zA-Z]+\.pdf>' => 'upload/viewPdf', // actionViewPdf Method in UploadController class
// ... all your other rules
),
),
And a controller class, and a method with the same name as in your route above (prepended with action):
class UploadController extends Controller
{
// Put the usual Yii access control stuff here or whatever...
public function actionViewPdf()
{
$filename = $_GET['filename'] . '.pdf';
$filepath = '/path/to/your/pdfs/' . $filename;
if(file_exists($filepath))
{
// Set up PDF headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filepath));
header('Accept-Ranges: bytes');
// Render the file
readfile($filepath);
}
else
{
// PDF doesn't exist so throw an error or something
}
}
}
Then you should be able to use
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/viewPdf', array('filename' => 'Tutorial')) ,
array('class'=>'button','target'=>'_blank'));
Hope that's helpful.
Well.... are you sure that the uploads folder is available on the server and it is in a location that is link friendly? Yii does not pass everything through it's index.php file, if a file already exists then it just used it like it is. That is why you can access the files in your images or css folder without having a controller for it.
If you are using the normal Yii structure then you should have your "uploads" folder next to your protected folder.
If your uploads folder is not in a web accessible location, use what JamesG told you to. The only change I would to is to the pattern, it only matches letters, you might have other chars in the name too.
Do not add ".pdf" to your link:
Yii::app()->createUrl('/uploads/Tutorial')
in PHP you can print your pdf like this (must be in the actionTutorial):
$mPDF = Yii::app()->ePdf->mpdf();
$mPDF->WriteHTML($this->render('tutorial', array(), true));
$mPDF->Output();
The tutorial is a simply html page that should be rendered into your pdf.
Here you can find the doku to the mpdf Yii extension
Related
I want to load my application at http://localhost:52856/CRUD/Products/List so then i can start working on the List.cshtml file instead of loading Index.cshtml at http://localhost:52856 .
Look i know i can just put a button at the index file so then it can redirect to path or use the navbar, but personally i don't want to do that every single time.Just load the application at the file.cshtml i want. But How can i do it?
If you don't like my comment you could do the following in Index.cshtml.cs
public IActionResult OnGet()
{
return new RedirectToPageResult("/CRUD/Product/List");
}
1. Include MVC as a service into our app.
we can optionally use another method called AddRazorPagesOptions() like so:
services.AddMvc().AddRazorPagesOptions(options =>
{
options.Conventions.AddPageRoute("/Customer/Index", "");
});
Within that AddRazorPagesOptions() method, we can set things like route conventions and the root directory for pages. It turns out that, to set a default route for a page.
2. remove or rename Pages/Index.cshtml
i am new in yii framework. currently i am using yii 1.1.
now i want to create custom components and we can say than create global function which is use anywhere in the application.
According to this url 'http://www.yiiframework.com/wiki/727/updated-how-to-create-call-custom-global-function-in-whole-application/'
i am follow all steps according to above url
but i have occur a error
Alias "ext.components.MyClass" is invalid. Make sure it points to an existing PHP file and the file is readable.
MyClass.php in the components folder
class MyClass extends CApplicationComponent {
public function get_my_info() {
$value = '1';
return $value;
}
}
Declare in the config folder
'components'=>array(
'user'=>array(
// enable cookie-based authentication
'allowAutoLogin'=>true,
),
'myClass' => array(
'class' => 'ext.components.MyClass',
),
And use in the view file
<?php
$myInfo = Yii::app()->myClass->get_my_info();
echo $myInfo;
?>
Have you put the file in correct component directory?. As per your alias the path should be /protected/extensions/components/MyClass.php
Write full path like application.modules.setting.components.*
I have a audit table and audit_report field.Field type is text .I saved pdf files into folder and saved name to database.I tried to display the pdf on view page. but the box with image sign only getting. I could display jpeg and png files nicely.How to display PDF on view page of yii2 framework.
This would work,
return Yii::$app->response->sendFile($completePath, $filename, ['inline'=>true]);
Input the function with third param as array of value 'inline'=>true to open the file within the browser window.
See the documentation here sendFile()
You could add a button that opens the file in a new tab, but make it link to an action in your controller that returns the file instead of the direct path to the file:
In your view:
<?= Html::a('PDF', [
'controller/pdf',
'id' => $model->id,
], [
'class' => 'btn btn-primary',
'target' => '_blank',
]); ?>
In your controller:
public function actionPdf($id) {
$model = ModelClass::findOne($id);
// This will need to be the path relative to the root of your app.
$filePath = '/your/file/path';
// Might need to change '#app' for another alias
$completePath = Yii::getAlias('#app'.$filePath.'/'.$model->fileName);
return Yii::$app->response->sendFile($completePath, $model->fileName);
}
Aliases - Key Concepts - The Definitive Guide to Yii 2.0
Although the question has been answered there is one thing that needs to be addressed if you have the file content/stream instead of the file path, like for instance you are using Dropbox API and you receive a stream from the API and want to display that file instead of forcing the browser to download.
For this case you can use the sendContentAsFile when attempting to display the PDF file in the browser you will need to specify the mimeType option too along with the "inline"=>true because the default mimeType value is set to application/octet-stream which is used to download a file and to display inline in browser you need to change it to application/pdf.
return Yii::$app->response->sendContentAsFile(
$fileContent,
$filename,
['inline' => true, 'mimeType' => 'application/pdf']
);
I have placed a PDF file in folder /protected/uploads. I want to view this file on click of hyperlink. But i am facing the error and the PDF is not being displayed.
Error
Error 404<br/>
Unable to resolve the request "uploads/viewPdf".
Here is what i have done to view the file.
main.php
'urlManager'=>array(
'urlFormat'=>'path',
'rules'=>array(
'uploads/<filename:[a-zA-Z]+\.pdf>' => 'Upload/viewPdf',
'<controller:\w+>/<id:\d+>'=>'<controller>/view',
'<controller:\w+>/<action:\w+>/<id:\d+>'=>'<controller>/<action>',
'<controller:\w+>/<action:\w+>'=>'<controller>/<action>',
),
),
UploadController
class UploadController extends Controller
{
public function actionIndex()
{
$this->render('index');
}
public function actionViewPdf()
{
$filename = $_GET['filename'] . '.pdf';
$filepath = '/uploads/Tutorial' . $filename;
if(file_exists($filepath))
{
// Set up PDF headers
header('Content-type: application/pdf');
header('Content-Disposition: inline; filename="' . $filename . '"');
header('Content-Transfer-Encoding: binary');
header('Content-Length: ' . filesize($filepath));
header('Accept-Ranges: bytes');
// Render the file
readfile($filepath);
}
else
{
// PDF doesn't exist so throw an error or something
}
}
}
and the link in the form. I would like to mention here is that the form belong to other controller not the upload controller
_form
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/viewPdf', array('filename' => 'Tutorial')) ,
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
echo CHtml::link(
'pdf',
Yii::app()->createUrl('/uploads/viewPdf', array('filename' => 'Tutorial')) ,
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
You do NOT have a controller called uploads, you do have one called upload, this is the problem. Also I believe you should not use the first / when using create url. Try using
echo CHtml::link(
'pdf',
Yii::app()->createUrl('upload/viewPdf', array('filename' => 'Tutorial')) ,
array('class'=>'btnPrint btn btn-danger','target'=>'_blank'));
One more thing, I am not sure that the file resolves to the correct path when creating
$filepath = '/uploads/Tutorial' . $filename;
The controller is in a folder, why would /uploads/ go to the correct folder from there? Try using a full path, or detect the path with dirname(FILE) and take it from there.
Just to also make sure. You create a link that will look something like this:
/uploads/Tutorial.pdf this will get resolved to /protected/uploads/TutorialTutorial.pdf, is that the functionality you want?
Most of what Mihai said is true and should be fixed. In addition try changing your controller to include the $filename as a required parameter. This will throw a 404 if $filename is not present in the url.
public function actionViewPdf($filename){
$filename .= '.pdf';
...
}
Im a newbie to yii and have been trying to add bootstrap and giiplus extension to yii.However after adding the extracted file to extensions folder and making changes in main.php I cant seem to get error in displaying even the main page.I followed this tutorial..
http://www.cniska.net/yii-bootstrap/setup.html
Download extension from here.
Paste all bootstrap extensions folders what you have download under extensions/bootstrap
config/main.php
Add before starting of array
Yii::setPathOfAlias('bootstrap', dirname(__FILE__).'/../extensions/bootstrap');
Add under return array
'theme'=>'bootstrap',
'modules'=>array(
'gii'=>array(
'generatorPaths'=>array(
'bootstrap.gii',
),
),
),
Add in under components
'bootstrap'=>array(
'class'=>'bootstrap.components.Bootstrap',
),
extensions/boostrap/components/Bootstrap.php
Paste code in class
public function init() {
$this->registerAllCss();
$this->registerJs();
parent::init();
}
protected/views/layout/main.php
Paste the line under head tag
<?php echo Yii::app()->bootstrap->init();?>
Follow this link for documentation
http://www.cniska.net/yii-bootstrap/