Dir*_*ber 7 php pdf nginx wkhtmltopdf
我使用KnpSnappyBundle 1.6.0和wkhtmltopdf 0.12.5从 PHP 中的 HTML 生成 PDF,如下所示:
$html = $this->renderView(
'pdf/template.html.twig',
[ 'entity' => $entity, ]
);
return new PdfResponse($snappy->getOutputFromHtml($html,
['encoding' => 'UTF-8', 'images' => true]), 'file'.$entity->getUniqueNumber().'.pdf'
);
Run Code Online (Sandbox Code Playgroud)
我的问题:在我的生产服务器上,当我引用与我的代码托管在同一台服务器上的资产(图像或 css)时,生成 PDF 大约需要 40-50 秒。即使我只使用托管在同一台服务器上的小图像也需要 40 秒。我可以使用托管在另一台服务器上的更大的图像,并且会立即生成 PDF。
我的服务器在提供资产或文件方面的速度并不慢。如果我只是将 HTML 呈现为一个页面,它会立即发生(有或没有资产)。当我在本地(在我的笔记本电脑上)从我的生产服务器请求资产以生成 PDF 时,它也会立即发生。
我在 HTML 中需要的需要呈现为 PDF 的资产都具有绝对 URL,这是 wkhtmltopdf 工作所必需的。例如:<img src="https://www.example.com/images/logo.png">困难的是,一切正常,只是非常缓慢。没有指出会导致超时的不存在的资产。
我一开始以为可能与 wkhtmltopdf 有关,所以我尝试了不同的版本和不同的设置,但这并没有改变任何东西。我还尝试指向同一台服务器上的另一个域,问题仍然存在。我尝试不使用 KnpSnappyBundle,但问题仍然存在。
所以我现在猜测是服务器问题(或与 wkhtmltopdf 的组合)。我正在运行Nginx-1.16.1并通过 SSL 提供所有内容。我安装了OpenSSL 1.1.1d 2019 年 9 月 10 日(库:OpenSSL 1.1.1g 2020 年 4 月 21 日),我的操作系统是Ubuntu 18.04.3 LTS。其他一切都在此服务器上按预期工作。
当我查看 Nginx 访问日志时,我可以看到在使用来自同一服务器的资产时,我自己的 IP 地址发出了一个 get 请求。我不明白为什么这需要这么长时间,而且我已经没有下一步要尝试的想法。任何想法表示赞赏!
我将为我的域添加我的 Nginx 配置(以防它可能有帮助):
server {
root /var/www/dev.example.com/public;
index index.php index.html index.htm index.nginx-debian.html;
server_name dev.example.com www.dev.example.com;
location / {
# try to serve file directly, fallback to index.php
try_files $uri /index.php$is_args$args;
}
location ~ ^/index\.php(/|$) {
fastcgi_pass unix:/var/run/php/php7.3-fpm.sock;
fastcgi_split_path_info ^(.+\.php)(/.*)$;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME $realpath_root$fastcgi_script_name;
fastcgi_param DOCUMENT_ROOT $realpath_root;
internal;
}
location ~ \.(?:jpg|jpeg|gif|png|ico|woff2|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|js|css)$ {
gzip_static on;
# Set rules only if the file actually exists.
if (-f $request_filename) {
expires max;
access_log off;
add_header Cache-Control "public";
}
try_files $uri /index.php$is_args$args;
}
error_log /var/log/nginx/dev_example_com_error.log;
access_log /var/log/nginx/dev_example_com_access.log;
listen 443 ssl; # managed by Certbot
ssl_certificate /etc/letsencrypt/live/dev.example.com/fullchain.pem; # managed by Certbot
ssl_certificate_key /etc/letsencrypt/live/dev.example.com/privkey.pem; # managed by Certbot
include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot
ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot
}
server {
if ($host = dev.example.com) {
return 301 https://$host$request_uri;
} # managed by Certbot
server_name dev.example.com www.dev.example.com;
listen 80;
return 404; # managed by Certbot
}
Run Code Online (Sandbox Code Playgroud)
Udate 2020 年 8 月 5 日:我尝试了wkhtmltopdf 0.12.6,但这给了我完全相同的问题。几个月前我发布的作为对我的问题的回答的“解决方案”远非完美,这就是我寻找新建议的原因。任何帮助表示赞赏。
对我来说这听起来像是 DNS 问题。我会尝试添加一个条目,/etc/hosts例如:
127.0.0.1 example.com
127.0.0.1 www.example.com
Run Code Online (Sandbox Code Playgroud)
并将您的图像指向使用该域