首页 > 解决方案 > 如何在 Laravel 中导出 PDF 文件

问题描述

我有两种看法。一种是显示过滤视图(视图 1)。另一种是从过滤视图中获取数据,然后导出为 PDF 文件(视图 2)。这意味着当点击“打印”时,将导出 PDF 文件,视图 2 将是带有视图 1 数据的 PDF 文件的视图。

现在我不知道如何从视图 1 中获取数据并显示到视图 2 中。

这是我的代码:

视图1:

<form method="get">
    <select name="type" onchange="this.form.submit()">
        <option value="">All types</option>
        @foreach ($types as $item)
            <option value="{{ $item->id }}" @if ($request->type == $item->id) selected @endif>{{ $item->name }}</option>
        @endforeach
    </select>
</form>
<br>
<a href="pdf">Print</a>
<br><br>
    <table border="1">
        <tr>
            <th>ID</th>
            <th>Content</th>
            <th>Type</th>
        </tr>
        @foreach ($data as $q)
            <?php $typeName = App\Type::find($q->type_id);?>
            <tr>
                <td>{{ $q->id }}</td>
                <td>{{ $q->content }}</td>
                <td>{{ $typeName->name }}</td>
            </tr>
        @endforeach
    </table>

View2:此视图将显示在 PDF 文件中,但我不知道如何从 View1 中获取价值

<table border="1">
    <tr>
        <th>ID</th>
        <th>Content</th>
        <th>Type</th>
    </tr>
</table>

过滤控制器:

public function getFilter(Request $request){
        $types = Type::all();
        $model = Question::where('id', '>', 0)->with('types');

        if (isset($request->type))
            $model = $model->where('type_id', $request->type);
        $data = $model->paginate(15)->appends(request()->query());

        return view('View1', compact( 'data', 'request', 'types'));
    }

打印控制器:

public function getValueFromView2(){
//I've to write something to get value from View1
}
public function getPDF(){
        $pdf = PDF::loadView('View2');
        return $pdf->download('test.pdf');
}

具有过滤功能的 View1 工作正常。我想要的是在过滤后导出带有 View1 数据的 PDF 文件

标签: mysqllaravel

解决方案


如果您可以更改尝试执行 atm 的方式,这真的非常简单。

更改您的方法 getPDF 以接受 get param names type

public function getPDF(){
    $type = $this->input('type');

    // get your data here in this call using the parameter(s)
    $model = $model->where('type_id', $type);
    $data = $model->get();

    $view2 = \View::make('view2', ['data', $data]);
    $view2Str = $view1->render();

    // Check the PDF documentation how to pass html and print pdf.
   // I'm assuming this is how the library loads view, as I haven't used this myself.
    $pdf = PDF::loadView( $view2Str );
    return $pdf->download('test.pdf');
}

在打印链接上,将参数type作为查询字符串传递给 getPDF 方法;


推荐阅读