如何从活动的View Laravel生成PDF

时间:2016-07-16 21:45:58

标签: php laravel

当用户输入滚动否时,我有一个搜索框,它返回特定的学生结果。我想生成搜索到的数据的PDF,该数据在表中。 enter image description here 主要问题:我想为搜索了他/她的数据的学生的结果生成PDF,以便如何为当前学生结果生成PDF。

打印/ PDF生成器按钮:

 <a href="{!! url('/getPDF') !!}">Print</a>

PDFController:

class PDFController extends Controller
{
    public function getPDF(Request $request){
            // I want some code here to get the current student result so that I can generate pdf for the current student
            $pdf = PDF::loadView('results.single');
            return $pdf->stream('result.pdf');
    }
}

SearchController:

class ResultsSearchController extends Controller
{
    public function search()
    {
        $keyword = Input::get('keyword');
        $row = Student::where('rollno',$keyword)->first();
        $rollno = $row['rollno'];
        if($keyword == $rollno){
            return View::make('results.single')
            ->with('search',Student::where('rollno',$keyword)
            ->get())->with('keyword',$keyword);
        }else{
            return view('errors.404');
        }
    }
}

routes.php文件:

Route::get('/getPDF', 'PDFController@getPDF');

PS:我正在使用https://github.com/barryvdh/laravel-dompdf

2 个答案:

答案 0 :(得分:5)

试试这个

首先将路线改为

Route::get('/getPDF/{id}', 'yourController@getPDF');

将搜索到的学生ID从单个视图传递到PDF视图,如下所示

<a href="{!! url('/getPDF', $student->id) !!}">Print</a>

并在PDF控制器中

 public function getPDF(Request $request,$id){
            $student = Student::findOrFail($id);
            $pdf = PDF::loadView('pdf.result',['student' => $student]);
            return $pdf->stream('result.pdf', array('Attachment'=>0));              
 }

并在您的视图中获取对象

{!! $student->property!!}

答案 1 :(得分:1)

当您致电PDF::loadView()时,我认为您需要包含搜索结果,就像在search()

中一样
$keyword = Input::get('keyword');
$row = Student::where('rollno',$keyword)->first();
$rollno = $row['rollno'];
if($keyword == $rollno){
    $results = Student::where('rollno',$keyword)->get();
    $pdf = PDF::loadView('results.single', [
                'search' => $results, 
                'keyword' => $keyword
                ]);
    return $pdf->stream('result.pdf');
}