medilies/ctrl-p

将 HTML 转换为 PDF 的任务委托给浏览器

v0.1.0-beta 2023-12-28 21:32 UTC

This package is auto-updated.

Last update: 2024-09-30 02:13:11 UTC


README

Latest Version on Packagist Pest Action Pint action Total Downloads

设置

composer require medilies/ctrl-p

要求

  • PHP 8.1

使用方法

设置 HTML

  • 使用 CtrlP::html('foo')$ctrlP->setHtml('foo') 来设置 HTML。
  • 使用 CtrlP::template('<?php echo "foo";', [])$ctrlP->template('<?php echo "foo";', []) 来从 PHP 模板设置 HTML。

设置页面大小和方向

  • 使用 format($paperFormat) 来设置标准纸张格式。
  • 使用 landscape()portrait() 来指定所选的纸张格式。
  • 使用 paperSize($width, $height) 来设置显式的大小。

页边距

使用 margins($margins) 来设置页边距。

截至 2023 年 12 月,页眉和页脚的页边距内容无法编辑,因为没有浏览器支持(查看

控制

  • 使用 printButton($bool) 来添加/移除打印按钮。
  • 使用 backUrl($url) 来添加/移除一个链接到您选择页面的按钮。
  • 使用 autoPrint() 在渲染页面后自动打印页面。

覆盖

  • 使用 title($title) 来覆盖标题。
  • 使用 urlPath($url) 来覆盖 URL 路径。

示例

<?php

// php -S 0.0.0.0:8080 .\this_file.php
// Visit http://127.0.0.1:8080/

use Medilies\CtrlP\CtrlP;

require_once __DIR__.'/../vendor/autoload.php';

echo CtrlP::html('
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Flex and Grid HTML Page</title>
  <style>
    body {
      font-family: Arial, sans-serif;
      margin: 0;
      padding: 0;
    }

    .container {
      display: flex;
      height: 100vh;
    }

    .sidebar {
      background-color: #f2f2f2;
      width: 250px;
      padding: 20px;
    }

    .main-content {
      flex: 1;
      display: grid;
      grid-template-columns: 1fr 1fr 1fr;
      gap: 20px;
      padding: 20px;
      background-color: #e0e0e0;
    }

    .box {
      background-color: #fff;
      padding: 20px;
      border-radius: 5px;
      box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
      text-align: center;
    }
  </style>
</head>
<body>

  <div class="container">
    <div class="sidebar">
      <h2>Sidebar</h2>
      <p>Some sidebar content goes here.</p>
    </div>

    <div class="main-content">
      <div class="box">Box 1</div>
      <div class="box">Box 2</div>
      <div class="box">Box 3</div>
      <div class="box">Box 4</div>
      <div class="box">Box 5</div>
      <div class="box">Box 6</div>
    </div>
  </div>

</body>
</html>
    ')
    ->margins('1cm')
    // ->paperSize('130mm', '130mm')
    ->format('A4')
    ->landscape()
    ->title('Chad PDF')
    ->urlPath('/drip-url')
    ->autoPrint()
    ->printButton()
    ->backUrl('/some-path')
    ->get();

screenshot