snugcomponents / pdf-generator
SnugComponents 组件,用于生成 PDF 文件。
v2.0.4
2023-05-07 18:38 UTC
Requires
- php: >=8.1
- ext-curl: *
- nette/application: ^3.1
- nette/di: ^3.1
- snugcomponents/utils: ^1.0
Requires (Dev)
- mockery/mockery: ^1.5
- phpunit/phpunit: ^9.5
README
使用我们的 API 生成 PDF 文件的库。
简介
这个库是 Nette 扩展,用于向我们的微服务发送请求,可以从 HTML 代码生成 PDF 或屏幕截图。如果您想使用此扩展,您需要拥有自己的微服务。
安装
下载
安装 snugcomponents/pdf-generator
的最佳方式是使用 Composer
$ composer require snugcomponents/pdf-generator
注册
库已准备好 Nette,因此您可以在配置中注册它
extensions:
PdfGenerator: Snugcomponents\PdfGenerator\DI\PdfGeneratorExtension
注入
注册后,有两个服务您可能感兴趣。您可以将这两个服务简单地注入到其他服务中
public function __construct(
private \Snugcomponents\PdfGenerator\PdfFactory $pdfFactory,
private \Snugcomponents\PdfGenerator\ScreenshotFactory $screenshotFactory,
) {
parent::__construct();
...
}
设置
所有设置都是必需的!!!
库 需要 进行配置。您可以通过将以下代码插入您的私有配置来实现
PdfGenerator:
url: 'https://pdfserver.com/' # URL of your microservice for generating PDFs
tempDir: '%tempDir%' # temp dir, where will be saved result from microservice
username: 'username' # username for Basic authentication
password: 'password' # password for Basic authentication
用法
用法非常简单
PdfFactory
$pdfFilename = $pdfFactory->create('<p>This is HTML to print</p>'); # send directly HTML which you need to print to PDF
$pdfFilename = $pdfFactory->create('https://htmlurl.com/'); # or send URL address of web page, which you need to be printed into PDF
在 $pdfFilename
中,您将获得生成的 PDF 的路径。它将保存在您通过配置提供的临时目录中。强烈建议将文件移动到另一个位置。
ScreenshotFactory
$imgFilename = $screenshotFactory->create(
'<p>This is HTML to print</p>', # HTML or URL
1024, # width of printing screen - OPTIONAL
768, # height of printing screen - OPTIONAL
);
在 $imgFilename
中,您将获得生成的 jpg 图像的路径。它将保存在您通过配置提供的临时目录中。强烈建议将文件移动到另一个位置。
立即文件下载
如果您需要下载生成的文件而无需查看它,您可以通过另一个名为 FileResponse
的服务来实现。
小示例:(仅适用于演示者)
#[Inject] public PdfFactory $pdfFactory;
#[Inject] public \Snugcomponents\PdfGenerator\Responses\FileResponseFactory $fileResponseFactory;
public function actionGenerate(): void
{
$filePath = $this->pdfFactory->create('<p>This is HTML to print</p>');
$response = $this->fileResponseFactory->create(
file: $filePath, # path to file to download
name: 'document.pdf' # name for downloaded file - OPTIONAL
contentType: 'application/pdf' # Content-Type of file - OPTIONAL
forceDownload: true, # force download? - OPTIONAL (default true)
deleteFileWhenFinished: true, # delete file after download? - OPTIONAL (default false)
);
$this->sendResponse($response);
}
设置打印到 PDF
如果您需要强制自己的打印到 PDF 设置,例如移除边框、隐藏图像等,那么您只需将经典的 @media print
CSS 属性添加到您的样式表中即可。
结论
此扩展需要 PHP8.1、Nette3.1,并且属于 SnugDesign © 2023