ruby wkhtmltopdf错误时生成的PDF与大量的网页与页眉/页脚

ohfgkhjo  于 2023-08-04  发布在  Ruby
关注(0)|答案(4)|浏览(142)

我使用pdfkit(它在后台使用wkhtmltopdf)在我的rails应用程序中生成PDF。根据指南here,我已经得到了它主要用于PDF的基本情况。我现在遇到了一个问题,当试图生成一个PDF与大量的网页,也有页眉/页脚。当试图生成PDF时,我在控制台中的wkhtmltopdf中看到的错误是:

QEventDispatcherUNIXPrivate(): Unable to create thread pipe: Too many open files
QEventDispatcherUNIXPrivate(): Can not continue without a thread pipe

字符串
可以用来重新创建错误的html的最小示例:

<!-- content of pdf_header_url is the character "h" -->
<meta content="<%= pdf_header_url %>" name="pdfkit-header-html"/>
<!-- content of pdf_footer_url is the character "f" -->
<meta content="<%= pdf_footer_url %>" name="pdfkit-footer_html"/>
<% [*1..3].each do |j|%>
  <h1><%= j %></h1>
  <ul>
    <% [*1..1000].each do |i|%>
      <li><%= i %></li>
    <% end %>
  </ul>
<% end %>


请注意,删除页眉/页脚标签可以使PDF呈现良好。
生成PDF的实际ruby代码是:

def view_report
  html = render_to_string(:template => 'pdf/pdf_body.html', :layout => false)
  kit = PDFKit.new(html)
  pdf = kit.to_pdf
  send_data pdf, :type => 'application/pdf', :disposition => 'inline', :filename => 'foo.pdf'
end


访问此控制器路由将生成PDF。最后,我还有一个页眉/页脚的控制器,因为这些“部分”需要通过url获取:

class PdfController < ApplicationController

  def header
    render :layout => false
  end

  def footer
    render :layout => false
  end

end


pdf_header_url和pdf_footer_url的值实际上只是“h”和“f”,这是为了最小化可重复的示例。
有没有熟悉wkhtmltopdf的人对进一步的调试步骤有什么建议来解决这个问题?

lymgl2op

lymgl2op1#

我今天收到了同样的错误信息,我用一个非常简单的解决方案解决了这个问题。问题是,我的页眉和页脚需要完整的html文档的html,头和身体标签。另外,看看你是否可以得到你的页眉和页脚的生成的html输出,并验证它们。

pkwftd7m

pkwftd7m2#

打开文件限制。

我确保了我的页眉和页脚文件是完整的HTML文档,就像Tom Hirschfeld建议的那样,但我仍然得到了这个打开文件太多的错误。
在搜索了互联网之后,我发现你需要提高你的文件数量限制,一个单一的进程可以打开。在我的例子中,我正在生成数百到数千页的PDF。它在没有页眉和页脚的情况下工作得很好,但是当合并页眉和页脚时,它似乎达到了打开文件的上限。
根据您运行的系统,有不同的方法来调整此设置,但以下是我在Ubuntu服务器上的工作:
在**/etc/security/limits.conf**末尾添加以下内容:

# Sets the open file maximum here.
# Generating large PDFs hits the default ceiling (1024) quickly. 
*    hard nofile 65535
*    soft nofile 65535
root hard nofile 65535 # Need these two lines because the wildcards
root soft nofile 65535 # (the * above) are not applied to the root user.

字符串
ulimit命令的一个很好的参考可以在这里找到。
我希望这能让一些人走上正确的道路。

x9ybnkn6

x9ybnkn63#

wkhtmltopdf每页使用2个文件描述符(页眉和页脚各一个),这是生成每页自定义变量所必需的。您必须编辑/etc/security/limits.conf以设置nofile(即打开文件的最大数量)到适当的高数量--可能需要一些实验来找到适合您的值。

dz6r00yl

dz6r00yl4#

以下是Mac的解决方案:https://github.com/uncss/uncss/issues/106#issuecomment-64768667
对我很有效。

相关问题