使用 DOMpdf 在 Laravel 中生成包含图表的 PDF

问题描述 投票:0回答:1

我已成功创建图表,但我不知道如何以 pdf 格式呈现此图表。我已经尝试了很多东西,但它不起作用。我使用“Laravel 图表”库创建了图表,并使用“DOMpdf”库生成 pdf。另外,我尝试将画布转换为图像,但它不起作用。请帮我。我是新来的 拉拉维尔。

谢谢您的协助

chart.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8">
                <canvas id="myChart" height="100px"></canvas>
            </div>
            <button id="convertButton">pdf</button>
        </div>
    </div>
    
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.1/Chart.min.js" charset="utf-8"></script>    

    <script type="text/javascript">
  
        var labels =  {{ Js::from($labels) }};
        var users =  {{ Js::from($data) }};
      
        const data = {
            labels: labels,
            datasets: [{
                label: 'My First dataset',
                backgroundColor: 'rgb(255, 99, 132)',
                borderColor: 'rgb(255, 99, 132)',
                data: users,
            }]
        };
      
        const config = {
            type: 'line',
            data: data,
            options: {}
        };
      
        const myChart = new Chart(
            document.getElementById('myChart'),
            config
        );
      
    </script>
    <script>
        const canvas = document.getElementById('myChart');
        const convertButton = document.getElementById('convertButton');
        convertButton.addEventListener('click', () => {
            const canvasData = canvas.toDataURL(); // Convert canvas content to data URL
            
            // Send the canvas data to the server using fetch
            fetch('/pdf', {
                method: 'POST',
                headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
                body: `imageData=${encodeURIComponent(canvasData)}`
            })
            .then(response => response.json())
            .then(result => {
                console.log(result.message);
            });
        });
    </script>
</body>
</html>

/pdf(路线)功能:

public function generatePDF(Request $request)
    {
        
        $users = User::select(DB::raw("COUNT(*) as count"), DB::raw("MONTHNAME(created_at) as month_name"))
                    ->whereYear('created_at', date('Y'))
                    ->groupBy(DB::raw("month_name"))
                    ->orderBy('id','ASC')
                    ->pluck('count', 'month_name');
 
        $labels = $users->keys();
        $data = $users->values();

        $imageData = $request->input('imageData');

        // Remove the data URL prefix to get the actual base64-encoded image data
        $imageData = str_replace('data:image/png;base64,', '', $imageData);

        $decodedImageData = base64_decode($imageData);

        echo "<pre>";
        print_r($decodedImageData);echo "<br>";

        // Generate a unique filename for the image
        $filename = 'canvas.png';

        $filepath = public_path($filename);

        // Save the image in the storage directory
        Storage::disk('public')->put($filename, $decodedImageData);


            $chartHtml = view('pdf', compact('filepath'))->render();

            $pdf = PDF::loadHTML($chartHtml);

            return $pdf->stream('chart.pdf');

    }

pdf.blade.php

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    <div class="container">
        <div class="row">
            <div class="col-md-8">                
                <img src="{{$filepath}}" alt="charts">
            </div>
        </div>
    </div>
</body>
</html>
php jquery laravel dompdf laravel-charts
1个回答
0
投票

对于您的情况,您应该使用 spatie/browsershot 包

© www.soinside.com 2019 - 2024. All rights reserved.