所以,本日我要和人人分享一个怎样运用DomPDF库使HTML规划生成PDF文件的例子。
在这个例子中,我将主要做三件事,以下:
1)设置dompdf库
2)建立index . php文件
3)建立pdf_generate.php文件
步骤1:装置和设置
在第一步,我们必需下载一个库和两个依靠的dompdf。
1) Dompdf:我们能够从GitHub下载Dompdf库,下载链接:https://github.com/dompdf/dompdf。下载后将其解压缩到根文件夹并将其重定名为“dompdf”。
2) php-font-lib:现在从GitHub下载php-font-lib,下载链接:https://github.com/PhenX/php-font-lib。下载后解压到“dompdf/lib/”文件夹,并将其重定名为“php-font-lib”。
3) php-svg-lib:末了从GitHub下载php-svg-lib,下载链接:https://github.com/PhenX/php-svg-lib。下载后解压到“dompdf/lib/”文件夹,并将其重定名为“php-svg-lib”。
步骤2:建立index.php文件
在这个步骤中,我将在根目录中建立index.php文件,在这个文件中,我运用bootstrap建立了一个简朴的表单。
代码以下:
index . php
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>PHP运用Dompdf库将HTML文件转换为PDF</title> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> </head> <body> <div class="container"> <h2>生成PDF的信息表单</h2> <form action="pdf_generate.php" method="POST"> <div class="form-group"> <label>称号:</label> <input type="text" name="name" class="form-control" placeholder="输入称号" required> </div> <div class="form-group"> <label>Email:</label> <input type="email" name="email" class="form-control" placeholder="输入Email" required> </div> <div class="form-group"> <label>网址:</label> <input type="url" name="url" class="form-control" placeholder="输入URL" required> </div> <div class="form-group"> <label>内容:</label> <textarea name="say" class="form-control" placeholder="输入内容"></textarea> </div> <div class="form-group"> <button class="btn btn-success">生成PDF</button> </div> </form> </div> </body> </html>
效果图以下:
这里我们将猎取宣布的数据并生成pdf文件下载。
代码以下:
pdf_generate.php
<?php require_once 'dompdf/autoload.inc.php'; /* 援用Dompdf定名空间*/ use Dompdf\Dompdf; /* 实例化并运用dompdf类 */ $dompdf = new Dompdf(); $html = '<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <h1>迎接来到ki4网</h1> <table class="table table-bordered"> <tr> <th colspan="2">信息表</th> </tr> <tr> <th>称号</th> <td>'.$_POST['name'].'</td> </tr> <tr> <th>Email</th> <td>'.$_POST['email'].'</td> </tr> <tr> <th>网址</th> <td>'.$_POST['url'].'</td> </tr> <tr> <th>内容</th> <td>'.nl2br($_POST['say']).'</td> </tr> </table>'; $dompdf->loadHtml($html); /* 将HTML呈现为PDF*/ $dompdf->render(); /*将生成的PDF输出到浏览器 */ $dompdf->stream();
相干引荐:《PHP教程》
OK,PHP运用Dompdf库将HTML文件转换为PDF的要领就引见到这里!须要的朋侪,能够直接下载本篇中的代码到当地举行测试,愿望对人人有所协助!
以上就是PHP怎样运用Dompdf库将HTML转换为PDF?的细致内容,更多请关注ki4网别的相干文章!