如何使用Docraptor库将HTML转换为PDF

381 阅读3分钟

使用Docraptor库将HTML转换为PDF

便携文档格式(PDF)是一种标准的文档呈现格式。现在所有的东西都是以PDF形式给出的,包括付款请求、收据和拨款报告。

然而,生成许多自定义PDF的时间会很漫长,特别是如果你想生成许多PDF文件。

简介

DocRaptor是一个HTML-to-PDF的API,它大大增强了HTML到PDF的转换。此外,该API有一个PHP框架,便于与PHP项目集成。本文将指导读者使用DocRaptor将HTML文档转换为PDF。

安装

为了开始使用DocRaptor,我们需要在我们的本地机器上安装它。安装可以通过两种方式进行。第一种方式是使用composer依赖管理器,而第二种方式是下载库的压缩文件,并将其解压到特定的项目文件夹中。

使用 composer 进行下载

Composers是一个PHP依赖性管理器。它可以下载、安装和更新你的项目依赖性。

composer require docraptor/docraptor

使用压缩文件进行安装

通过这个链接导航,下载压缩文件。

下载该文件,然后将其解压到你的工作区。创建一个新文件,命名为docraptor.php ,并在其中包含autoload.php 。在docraptor.php 文件中,添加下面的代码片段。

//docraptor.php
require_once('./path/to/docraptor-php/autoload.php');

API认证

每个使用API的项目都需要一个API密钥。这个密钥可以识别对特定资源的请求来自哪台机器。因此,我们需要添加一个API密钥来验证我们请求的来源。

要开始使用,你可以使用free to use API密钥,"YOUR_API_KEY_HERE "来开始。然而,这个密钥只允许我们使用有水印的文件,并将文件的下载数量限制在5个。

$configuration=DocRaptor\configuration::getDefaultconfiguration();  //requests for API key 
$configuration->setUsername('KEY_YOUR_API_HERE');   //works for test document

添加HTML内容或一个URL

这一部分是大部分工作完成的地方,因为我们在这里添加要转换的HTML内容。我们需要转换的任何HTML必须存在于我们正在处理的单个文档中。将下面的代码片段添加到名为docaptor.php 的文件中。

$docraptor = newDocRaptor\DocAPI();
$doc = new DocRaptor\doc(); //identifies the type of file required
$doc = setDocumentContent("<!DOCTYPE html>
<html lang="en">
  <head> 
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    <meta name="csrf-token" content="m8GCXCxn8DS2r8zNl1wmhb4O0n79avTSc9puuaqd">
    <title>Home</title>
    <!-- Bootstrap CSS --><link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css" integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">
</head>
<body>
    <div class="container" style="margin-top: 8%; margin-left: 30%; border-color: #1dcf06 ;">
      <table style="border-collapse: separate; border-spacing: 0; color: #4a4a4d;  font: 14px/1.4 "Helvetica Neue", Helvetica, Arial, sans-serif;">
        <thead style="background: #395870; background: linear-gradient(#49708f, #293f50); color: #fff; font-size: 11px; text-transform: uppercase;">
          <tr>
            <th scope="col" colspan="2" style="padding: 10px 15px; vertical-align: middle;">Item</th>
            <th scope="col" style="padding: 10px 15px; vertical-align: middle;">Qty</th>
            <th scope="col" style="padding: 10px 15px;  vertical-align: middle;">Price</th>
          </tr>
        </thead>
        <tbody style="background: #f0f0f2;">
          <tr>
            <td style="padding: 10px 15px; vertical-align: middle;">
              <strong class="book-title">Programming pearls</strong>
               <span class="text-offset" style="color: #807c80;  font-size: 12px">Jon Bentley</span>
            </td>
            <td class="item-stock" style="text-align: center">In Stock</td>
            <td class="item-qty" style="text-align: center">1</td>
            <td class="item-price" style="text-align: right">$30.02</td>
          </tr>
          <tr>
            <td style="padding: 10px 15px; vertical-align: middle;">
              <strong class="book-title" style="color: #395870;  display: block;">Introduction to Algorithms</strong>
                <span class="text-offset" style="color: #807c80;  font-size: 12px">by Thomas H. Cormen, Charles E. Leiserson, Ronald L. Rivest, Clifford Stein</span>
            </td>
            <td class="item-stock" style="text-align: center;">In Stock</td>
            <td class="item-qty" style="text-align: center;">2</td>
            <td class="item-price" style="text-align: right;">$52.94</td>
          </tr>
          <tr>
            <td style="padding: 10px 15px; vertical-align: middle;">
              <strong class="book-title" style="color: #395870;  display: block;">Introducing JAVA</strong>
              <span class="text-offset" style="color: #807c80;  font-size: 12px">by Bruce Lawson &#38; Remy Sharp</span>
            </td>
            <td class="item-stock" style="text-align: center;">Out of Stock</td>
            <td class="item-qty" style="text-align: center;">1</td>
            <td class="item-price" style="text-align: right;">$22.23</td>
          </tr>
          <tr>
            <td style="padding: 10px 15px; vertical-align: middle;">
              <strong class="book-title" style="color: #395870;  display: block;">Working effectively with Legacy Code</strong>
               <span class="text-offset" style="color: #807c80;  font-size: 12px">by Michael Feathers</span>
            </td>
            <td class="item-stock" style="text-align: center;">In Stock</td>
            <td class="item-qty" style="text-align: center;">1</td>
            <td class="item-price" style="text-align: right;">$30.17</td>
          </tr>
        </tbody>
        <tfoot style="text-align: right;">
          <tr class="text-offset" style="color: #807c80;  font-size: 12px">
            <td colspan="3"style="padding: 10px 15px; vertical-align: middle;">Subtotal</td>
            <td>$135.36</td>
          </tr>
          <tr class="text-offset" style="color: #807c80;  font-size: 12px">
            <td colspan="3" style="padding: 10px 15px; vertical-align: middle;">Tax</td>
            <td>$13.54</td>
          </tr>
          <tr>
            <td colspan="3" style="padding: 10px 15px; vertical-align: middle;">Total</td>
            <td>$148.90</td>
          </tr>
        </tfoot>
      </table>
    </div>
</body>
</html>");    //supply content directly 

请注意,有时我们可能想转换一个只存在于互联网空间的文件,而不是将其存储在我们的机器上。因此,我们需要提供我们计划在这种情况下使用的文件的链接。

这个过程可以按以下方式进行。

$docraptor = newDocRaptor\DocApi();
$doc = newDocRaptor\doc();
$doc = setDocumentUrl("http: //DocRaptor.com/returns/sales.html");  //or use a url

无论你在报告中使用HTML还是URL,你引用的所有资源都应该可以通过互联网访问,这样DocRaptor才能工作。所以我们需要有一个互联网连接。

API文档选项

鉴于DocRaptor也可能将文档转换为其他文件,例如将HTML转换为Excel,我们必须确保创建正确的文档。因此,将文档类型设置为PDF

$doc->setDocumentType("pdf");   //pdf or xls or xlsx //helps you find the document later

此外,我们应该创建一个测试文档,因为我们使用的是免费的API密钥。当测试设置为true ,我们必须注意,生成的PDF文档将有水印,限制5次下载,并在5天后失效。

$doc->setTest(true);    //test document are free but watermarked

另一个必须注意的是,默认情况下,JavaScript是关闭的,但你需要启用它以提高文档创建过程中的速度。

$doc->setJavaScript('true');    //enable JavaScript processing 

文档生成

在配置好你的API之后,运行这段代码来生成你的文件。文件创建是一个单行代码。它还包括一个错误处理机制,在出错的情况下巩固管理结构的错误。

try{
    $creat-response=$DocRaptor->creatDoc($doc); //generate the document
} catch (DocRaptor\ApiException $Error){
    echo $error ."\n";  //shows the error
    echo $error->getMessage() ."\n";    //returns the error message
    echo $error->getCode() ."\n";       //shows the line of code with the error
    echo $error->getResponseBody() ."\n";
}

在你的文件中添加以下代码片段,使文件能够保存在服务器上。

//saving to server
$fie = fopen("/tmp/DocRaptor-php.pdf" , "wb");
$fwrite($file , $create_response);
$fclose($file);

下面的代码片断将使用户能够下载文件。

//instructs php to return a file download 
$header('Content-Description: file Transfer');
$header('Content-Type: Application/pdf');
$header('Content-Deposition: attachment; filename=sales.pdf');
$header('Content-Transfer-Encoding: binary');
$header('Expires: 0');
$header('Content-Description: file Transfer');
$header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
$header('Pragma: public');
$header('Content-Length: ' .strlen($creat-response));
ob_clean();
flush();
echo($creat_response);
exit;

generated pdf

结论

长期以来,DocRaptor将HTML文档转换为PDF格式。它的策略与其他策略不同,因为它更详细,更紧凑,更直接。当我们需要将多份报告转换为PDF格式时,可以考虑它。

这篇文章涵盖了使用DocRaptor API将HTML文档转换为PDF。这篇文章对所使用的各种技术很有益处,并以适当的文档组织。