You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

基于PHP重构移动端失效的守门员绩效调研PDF生成方案

桌面端正常的PDF表单适配PHP服务端方案(解决iOS移动端失效问题)

我有一个在桌面端可正常使用的PDF表单,但在iOS设备上无法运行。曾编写脚本尝试适配iOS,仅桌面端有效,移动端仍无法工作。现需改造为PHP服务端方案,但对PHP不熟悉,请问如何将现有可运行的代码适配为Web服务端方案?


原前端代码(桌面端有效)

HTML文件

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Goalie Performance Survey</title>
    <style>
        .survey-table {
            width: 100%;
            max-width: 600px;
            border-collapse: collapse;
        }
        .survey-table th, .survey-table td {
            padding: 8px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .survey-table th {
            background-color: #f2f2f2;
        }
    </style>

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/2.4.0/jspdf.umd.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf-autotable/3.5.16/jspdf.plugin.autotable.min.js"></script>
</head>
<body>
    <h1>Rate the Goalie Performance (1-4, NR)</h1>
    <form id="surveyForm">
        <table class="survey-table">
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Rating</th>
                </tr>
            </thead>
            <tbody id="questions">
                <!-- Questions will be inserted here by the script -->
            </tbody>
        </table>
        <button type="button" onclick="calculateAndGeneratePDF()">Submit & Print</button>
    </form>

    <script>
        const goaliePerformanceItems = [
            "Stick Saves", "Glove Saves", "Body Saves", "Blocker Saves",
            "Post Integrations", "Rush Management", "Screens/Traffic",
            "Breakaways", "Puck Tracking", "Patience"
        ];

        document.addEventListener('DOMContentLoaded', function() {
            const questionsTableBody = document.getElementById('questions');
            goaliePerformanceItems.forEach((item, index) => {
                const rowHTML = `
                    <tr>
                        <td>${item}</td>
                        <td>
                            <select name="item${index}" id="item${index}">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="NR">NR</option>
                            </select>
                        </td>
                    </tr>
                `;
                questionsTableBody.innerHTML += rowHTML;
            });
        });

        function calculateAndGeneratePDF() {
            let totalScore = 0;
            let count = 0;
            let itemsAndScores = [];
            goaliePerformanceItems.forEach((item, index) => {
                const answer = document.getElementById(`item${index}`).value;
                if (answer !== "NR") {
                    totalScore += parseInt(answer, 10);
                    count++;
                }
                itemsAndScores.push({ item: item, score: answer });
            });
            const averageScore = count > 0 ? (totalScore / count).toFixed(2) : "N/A";
            itemsAndScores.push({ item: "Average Score", score: averageScore });
            generatePDF(itemsAndScores);
        }

        function generatePDF(itemsAndScores) {
            const { jsPDF } = window.jspdf;
            const doc = new jsPDF();
            
            doc.autoTable({
                head: [['Item', 'Rating']],
                body: itemsAndScores.map(is => [is.item, is.score]),
                theme: 'striped',
                startY: 10
            });

            doc.save('goalie-performance-results.pdf');
        }
    </script>
</body>
</html>

PHP服务端改造方案

1. 修改前端表单

把前端改成提交到PHP后端,去掉客户端生成PDF的逻辑,只保留表单渲染代码(优化了移动端适配):

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Goalie Performance Survey</title>
    <style>
        .survey-table {
            width: 100%;
            max-width: 600px;
            border-collapse: collapse;
            margin: 0 auto;
        }
        .survey-table th, .survey-table td {
            padding: 10px;
            border: 1px solid #ddd;
            text-align: left;
        }
        .survey-table th {
            background-color: #f2f2f2;
        }
        button {
            margin-top: 20px;
            padding: 10px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            cursor: pointer;
        }
        button:hover {
            background-color: #45a049;
        }
        .center {
            text-align: center;
        }
    </style>
</head>
<body>
    <h1 class="center">Rate the Goalie Performance (1-4, NR)</h1>
    <form id="surveyForm" action="generate-pdf.php" method="POST">
        <table class="survey-table">
            <thead>
                <tr>
                    <th>Item</th>
                    <th>Rating</th>
                </tr>
            </thead>
            <tbody id="questions">
                <!-- Questions will be inserted here by the script -->
            </tbody>
        </table>
        <div class="center">
            <button type="submit">Submit & Generate PDF</button>
        </div>
    </form>

    <script>
        const goaliePerformanceItems = [
            "Stick Saves", "Glove Saves", "Body Saves", "Blocker Saves",
            "Post Integrations", "Rush Management", "Screens/Traffic",
            "Breakaways", "Puck Tracking", "Patience"
        ];

        document.addEventListener('DOMContentLoaded', function() {
            const questionsTableBody = document.getElementById('questions');
            goaliePerformanceItems.forEach((item, index) => {
                const rowHTML = `
                    <tr>
                        <td>${item}</td>
                        <td>
                            <select name="item${index}" id="item${index}" style="width:100%;padding:5px;">
                                <option value="1">1</option>
                                <option value="2">2</option>
                                <option value="3">3</option>
                                <option value="4">4</option>
                                <option value="NR">NR</option>
                            </select>
                        </td>
                    </tr>
                `;
                questionsTableBody.innerHTML += rowHTML;
            });
        });
    </script>
</body>
</html>

2. 编写PHP后端文件(generate-pdf.php)

用TCPDF生成PDF,这是PHP生态里成熟的PDF生成库,兼容所有设备:

第一步:安装TCPDF

  • 用Composer安装:执行命令 composer require tecnickcom/tcpdf
  • 手动安装:从TCPDF官网下载压缩包,解压后把tcpdf文件夹放到项目根目录

第二步:编写PHP代码

<?php
// 引入TCPDF(根据安装方式调整路径)
// Composer安装用这句
require_once 'vendor/autoload.php';
// 手动安装用这句:require_once 'tcpdf/tcpdf.php';

// 定义评分项,和前端保持一致
$goalieItems = [
    "Stick Saves", "Glove Saves", "Body Saves", "Blocker Saves",
    "Post Integrations", "Rush Management", "Screens/Traffic",
    "Breakaways", "Puck Tracking", "Patience"
];

// 收集表单数据并计算分数
$total = 0;
$validCount = 0;
$results = [];

foreach ($goalieItems as $idx => $item) {
    $score = $_POST["item$idx"] ?? 'NR';
    $results[] = [$item, $score];
    
    if ($score !== 'NR') {
        $total += (int)$score;
        $validCount++;
    }
}

// 计算平均分
$average = $validCount > 0 ? number_format($total / $validCount, 2) : 'N/A';
$results[] = ['Average Score', $average];

// 初始化PDF
$pdf = new TCPDF('P', 'mm', 'A4', true, 'UTF-8', false);
$pdf->SetCreator('Goalie Performance Survey');
$pdf->SetTitle('Goalie Performance Results');
$pdf->SetHeaderData('', 0, 'Goalie Performance Survey', 'Results');
$pdf->setHeaderFont(Array('helvetica', '', 10));
$pdf->setFooterFont(Array('helvetica', '', 8));
$pdf->SetMargins(15, 27, 15);
$pdf->SetHeaderMargin(10);
$pdf->SetFooterMargin(10);
$pdf->SetAutoPageBreak(TRUE, 25);
$pdf->SetFont('helvetica', '', 12);

// 添加页面
$pdf->AddPage();

// 生成表格
// 表头
$pdf->SetFillColor(242, 242, 242);
$pdf->Cell(90, 10, 'Performance Item', 1, 0, 'L', true);
$pdf->Cell(40, 10, 'Rating', 1, 1, 'L', true);

// 表内容
foreach ($results as $row) {
    $pdf->Cell(90, 10, $row[0], 1, 0, 'L');
    $pdf->Cell(40, 10, $row[1], 1, 1, 'L');
}

// 输出PDF,强制下载
$pdf->Output('goalie-performance-results.pdf', 'D');
exit;
?>

3. 部署说明

  • 把修改后的HTML文件和PHP文件放到支持PHP的服务器上(如Apache、Nginx)
  • 确保服务器有临时文件写入权限(TCPDF生成PDF需要)
  • iOS设备访问页面提交表单后,会直接触发PDF下载,解决移动端失效问题

内容的提问来源于stack exchange,提问作者Marc Dastous

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 08:15:54