Module: Sghtmltopdf

Defined in:
lib/sghtmltopdf.rb,
lib/sghtmltopdf/options.rb,
lib/sghtmltopdf/railtie.rb,
lib/sghtmltopdf/version.rb,
lib/sghtmltopdf/renderer.rb,
lib/sghtmltopdf/view_helpers.rb,
lib/sghtmltopdf/configuration.rb,
lib/sghtmltopdf/server_client.rb

Defined Under Namespace

Modules: Options, ViewHelpers Classes: Configuration, Railtie, Renderer, ServerClient, ServerError

Constant Summary collapse

DEFAULT_CHUNK_SIZE =

ブロック付きrenderで1回に渡すバイト数の目安(ローカル変換のみ)。 ページ確定ごとにブロックを呼ぶとGVLの取り直しが増えるため、ここまで 溜めてから渡す。

64 * 1024
VERSION =
"0.1.0"

Class Method Summary collapse

Class Method Details

.configObject



76
77
78
# File 'lib/sghtmltopdf.rb', line 76

def config
  @config ||= Configuration.new
end

.configure {|config| ... } ⇒ Object

グローバルな既定オプション。

Yields:



71
72
73
74
# File 'lib/sghtmltopdf.rb', line 71

def configure
  yield config
  config
end

.render(html, **options, &block) ⇒ Object

HTMLを変換してPDFのバイト列(ASCII-8BITのString)を返す。

ブロックを渡すと、PDF全体を組み立ててから返す代わりにチャンクごとに ブロックを呼ぶ(返り値はnil)。Rackのresponse.streamへ流したり、S3の マルチパートアップロードへ繋いだりするための口(エンジン側は出力先(sink) を意識しない設計に対応する)。

Sghtmltopdf.render(html) { |bytes| response.stream.write(bytes) }

ローカル・サーバ委譲のどちらでも、PDF全体が組み上がるのを待たずに 書き出せる(ローカルは確定したページから順に、サーバは?stream=1の chunked transfer encodingをそのまま渡す)。

ただし逐次になるのはPDFの書き出しだけで、HTMLのパースとレイアウトは 文書全体に対して先に行う。最初のチャンクが届くのは変換の終盤で、 ピークメモリもブロック無しの場合と変わらない。HTMLを読みながら ページを確定させたい場合はstreaming: trueと併せて使う (制約と引き換えにメモリが大きく減る)。

1回に渡すバイト数の目安はchunk_size:で変えられる(既定64KiB。 ローカル変換のみ。小さくするとGVLの取り直しが増える)。



49
50
51
52
53
54
55
56
# File 'lib/sghtmltopdf.rb', line 49

def render(html, **options, &block)
  client = server_client(options)
  return client.render(html.to_s, server_options(options), &block) if client
  return Native.render(html.to_s, argv_for(options)) if block.nil?

  Native.render_each(html.to_s, argv_for(options), block, chunk_size(options))
  nil
end

.render_to_file(html, path, **options) ⇒ Object

HTMLを変換してpathへ書き出す。

一時ファイルへ書いて成功時だけrenameするため、途中で失敗しても 壊れたPDFが出力先に残らない(サーバへ委譲する場合も同じ)。



62
63
64
65
66
67
68
# File 'lib/sghtmltopdf.rb', line 62

def render_to_file(html, path, **options)
  client = server_client(options)
  return client.render_to_file(html.to_s, server_options(options), path.to_s) if client

  Native.render_to_file(html.to_s, argv_for(options), path.to_s)
  nil
end

.reset_config!Object

主にテスト用。設定を空に戻す。



81
82
83
# File 'lib/sghtmltopdf.rb', line 81

def reset_config!
  @config = Configuration.new
end