### Run server with custom options Source: https://waka.github.io/sghtmltopdf/en/getting-started/docker.html Starts the server with custom options: --listen, --workers, and --max-body-size. The command must start with 'server' to override the default CMD. ```bash docker run --rm -p 8080:8080 ghcr.io/waka/sghtmltopdf \ server --listen 0.0.0.0:8080 --workers 4 --max-body-size 52428800 ``` -------------------------------- ### sghtmltopdf with HTML header and footer files Source: https://waka.github.io/sghtmltopdf/en/usage/cli/reference.html Command-line example showing how to use separate HTML files for the header and footer. Placeholders are substituted as text; JavaScript is not executed, external resources are not fetched, and @font-face is not loaded. ```bash sghtmltopdf report.html --header-html header.html --footer-html footer.html ``` -------------------------------- ### GET /version Source: https://waka.github.io/sghtmltopdf/en/usage/server.html Returns the version of the software. ```APIDOC ## GET /version ### Description Returns the version of the software, in the format `sghtmltopdf `. ### Method GET ### Endpoint /version ### Response Success response example: `sghtmltopdf 1.0.0` ``` -------------------------------- ### Start sghtmltopdf server with --listen and font Source: https://waka.github.io/sghtmltopdf/en/usage/server.html Runs the sghtmltopdf server in resident mode, listening on the given address (default 127.0.0.1:8080) with a specified font (required for Japanese text). The binary prints 'listening on 127.0.0.1:8080' to standard output when ready. ```bash sghtmltopdf server --listen 127.0.0.1:8080 --font NotoSansJP-Regular.ttf ``` -------------------------------- ### Run sghtmltopdf as an HTTP server Source: https://waka.github.io/sghtmltopdf/en/getting-started/docker.html Starts the server mode with default settings, listening on 0.0.0.0:8080 inside the container. The image's CMD sets --listen 0.0.0.0:8080 because the default is 127.0.0.1, which is unreachable from outside the container. ```bash docker run --rm -p 8080:8080 ghcr.io/waka/sghtmltopdf ``` -------------------------------- ### sghtmltopdf with header and footer text options Source: https://waka.github.io/sghtmltopdf/en/usage/cli/reference.html Command-line example showing how to generate a PDF with a centered header, right-aligned footer with page numbers, and a header line. Uses --header-center, --footer-right, and --header-line. ```bash sghtmltopdf report.html \ --header-center "Quarterly report" \ --footer-right "[page] / [topage]" \ --header-line ``` -------------------------------- ### Server-only startup options list Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Options that can only be set when the server starts. Passing any of these to the client raises UsageError. In a Rails app, the Railtie's base_url and allow_path defaults are dropped automatically when server_url is set. ```plaintext font, font-index, gothic-font, gothic-font-index, serif-font, serif-font-index, mono-font, mono-font-index, output, cover, header-html, footer-html, user-style-sheet, base-url, allow, enable-local-file-access, disable-local-file-access, allow-remote-assets, log-level, quiet ``` -------------------------------- ### Basic sghtmltopdf usage examples Source: https://waka.github.io/sghtmltopdf/en/usage/cli/reference.html Shows the simplest form using system fonts, writing to a specified output file. Without an output path, the input name is used with the extension changed to .pdf. Reading from standard input and writing to standard output is also demonstrated. ```bash # The simplest form; the system fonts are used sghtmltopdf invoice.html -o invoice.pdf # Without an output path, the input name with the extension changed to .pdf sghtmltopdf invoice.html # Read from standard input and write to standard output cat invoice.html | sghtmltopdf - -o - > invoice.pdf ``` -------------------------------- ### sghtmltopdf CLI usage Source: https://waka.github.io/sghtmltopdf/en/usage/cli/reference.html Shows the two command-line forms of sghtmltopdf: one for converting a file and one for running the HTTP server. The first form takes an input HTML file, while the second starts the server. ```text sghtmltopdf [OPTIONS] sghtmltopdf server [OPTIONS] ``` -------------------------------- ### Install the sghtmltopdf gem Source: https://waka.github.io/sghtmltopdf/en/getting-started/install.html Adds the sghtmltopdf gem to a Gemfile. Precompiled gems are available for x86_64-linux, aarch64-linux, and arm64-darwin (glibc) on Ruby 3.2 or later, so no Rust toolchain is required. Conversion runs in-process as a native extension; the GVL is released during heavy work. ```ruby # Gemfile gem "sghtmltopdf" ``` -------------------------------- ### Start new page for each chapter Source: https://waka.github.io/sghtmltopdf/en/supports/pagination.html Starts a new page for each chapter by forcing a page break before every section.chapter that follows another section.chapter. Note: in streaming mode, selectors that look backwards (like :last-child) never match, but the adjacent sibling combinator (+) used here does work. ```css section.chapter + section.chapter { break-before: page; } ``` -------------------------------- ### Page break with break-before Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html HTML with a CSS class using break-before: page to start a new page before the element. Also mentions break-after and break-inside: avoid. ```html

Invoice

This is page 1.

Line items

This is page 2.

``` -------------------------------- ### hello.html - Basic invoice HTML Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html A minimal HTML document used as the input for the sghtmltopdf examples. It includes inline CSS for font family, heading border, and a right-aligned total. ```html

Invoice

Thank you for your continued business. Please find the charges below.

Total 12,000 JPY

``` -------------------------------- ### Configure gothic_font in Sghtmltopdf Source: https://waka.github.io/sghtmltopdf/en/migration/wicked-pdf.html Sets a custom gothic font for Japanese output, avoiding reliance on system fonts. Use this in an initializer or setup block. ```ruby Sghtmltopdf.configure do |c| c.gothic_font = Rails.root.join("vendor/fonts/NotoSansJP-Regular.ttf") end ``` -------------------------------- ### GET /healthz Source: https://waka.github.io/sghtmltopdf/en/usage/server.html Returns the health status of the service. ```APIDOC ## GET /healthz ### Description Returns the health status of the service. ### Method GET ### Endpoint /healthz ### Response Success response: `ok` ``` -------------------------------- ### Stream PDF with ActionController::Live Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Combine the render pdf: renderer with ActionController::Live to send pages as they are finalized. The renderer assembles the whole PDF and returns it with send_data, but this example streams chunks to the response. If it fails after part of the file has been written, the client receives a broken PDF because the headers have already gone out and the status can no longer be changed. ```ruby class InvoicesController < ApplicationController include ActionController::Live def show response.headers["Content-Type"] = "application/pdf" html = render_to_string(template: "invoices/show", layout: "pdf") Sghtmltopdf.render(html) { |bytes| response.stream.write(bytes) } ensure response.stream.close end end ``` -------------------------------- ### Render PDF with a block for chunked output Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Pass a block to Sghtmltopdf.render to receive each chunk of the PDF as it is finalized, instead of the whole PDF being assembled and returned. The return value is nil. This is the hook for writing into Rack's response.stream or feeding an S3 multipart upload. Writing can start before the whole PDF has been assembled; locally the chunks arrive page by page as each is finalized. ```ruby Sghtmltopdf.render(html) { |bytes| response.stream.write(bytes) } ``` -------------------------------- ### Define @page size, margins, and margin box content Source: https://waka.github.io/sghtmltopdf/en/supports/pagination.html CSS @page rule that sets paper size, page margins, and margin box text such as a header, page numbers, and a first-page footer. @page overrides CLI page setup options; size accepts keywords like A4 or Letter, lengths, and orientation; counter(page) and counter(pages) provide page numbers. Note size and margin cannot vary between pages, and counter(pages) is unavailable in streaming mode. ```css @page { size: A4; margin: 20mm; @top-center { content: "Invoice"; } @bottom-center { content: counter(page) " / " counter(pages); } } @page :first { @bottom-center { content: "Cover"; } } ``` -------------------------------- ### Set orphans and widows to control paragraph breaks Source: https://waka.github.io/sghtmltopdf/en/supports/pagination.html CSS example using orphans and widows to control how many lines of a paragraph must remain at the bottom/top of a page. Both accept an integer of 1 or more and default to 2; if the requirement can't be met, the whole paragraph moves to the next page. ```css __ p { orphans: 3; /* leave at least three lines at the bottom of the page */ widows: 3; /* carry at least three lines to the top of the next page */ } ``` -------------------------------- ### Run sghtmltopdf as a CLI Source: https://waka.github.io/sghtmltopdf/en/getting-started/docker.html Runs the binary as a CLI, converting invoice.html to invoice.pdf. The container runs as UID 10001, so use --user to match the host owner when writing to a mounted directory. ```bash docker run --rm -v "$PWD:/work" -w /work --user "$(id -u):$(id -g)" \ ghcr.io/waka/sghtmltopdf invoice.html -o invoice.pdf ``` -------------------------------- ### Build the CLI binary from source Source: https://waka.github.io/sghtmltopdf/en/getting-started/install.html Clones the repository and builds the CLI binary in release mode. Requires the stable Rust toolchain; no C libraries or system packages are needed. The binary is written to target/release/sghtmltopdf. ```bash git clone https://github.com/waka/sghtmltopdf.git cd sghtmltopdf cargo build --release ``` -------------------------------- ### Check the built binary version Source: https://waka.github.io/sghtmltopdf/en/getting-started/install.html Verifies the built binary by printing its version. Run from the repository root after building. ```bash ./target/release/sghtmltopdf --version ``` -------------------------------- ### Run the HTTP server with Docker Source: https://waka.github.io/sghtmltopdf/en/getting-started/install.html Pulls the Docker image and runs the HTTP server on port 8080. The image bundles Japanese fonts (BIZ UDPGothic and BIZ UDPMincho), so Japanese PDFs render without supplying a font. ```bash docker pull ghcr.io/waka/sghtmltopdf:latest docker run --rm -p 8080:8080 ghcr.io/waka/sghtmltopdf ``` -------------------------------- ### Convert via standard input/output Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html Pipes hello.html into sghtmltopdf and writes the PDF to standard output. Use - for both input and output to read from stdin and write to stdout. ```bash cat hello.html | sghtmltopdf - -o - > hello.pdf ``` -------------------------------- ### Streaming conversion via server mode query Source: https://waka.github.io/sghtmltopdf/en/usage/cli/streaming.html Use the `?stream=1&streaming` query parameters in server mode to make the response body chunked and enable streaming input, rendering, and output. ```shell curl --data-binary @big.html 'http://127.0.0.1:8080/pdf?stream=1&streaming' -o out.pdf ``` -------------------------------- ### Render HTML to PDF using Sghtmltopdf.render and render_to_file Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Convert HTML strings to PDF bytes with `Sghtmltopdf.render` and write to a file with `render_to_file`. The returned string is ASCII-8BIT. Input HTML is passed as bytes; encoding is detected from BOM, `encoding:`, ``, or UTF-8. `render_to_file` writes atomically, and the GVL is released during heavy work. ```ruby pdf = Sghtmltopdf.render("

Invoice

") # → the PDF as a byte String Sghtmltopdf.render_to_file(html, "invoice.pdf") # → writes to a file and returns nil ``` -------------------------------- ### Initializer: configure sghtmltopdf globally Source: https://waka.github.io/sghtmltopdf/en/migration/wicked-pdf.html Global configuration for sghtmltopdf, the counterpart of wicked_pdf's WickedPdf.config. The global config is merged first, and arguments to render take precedence. ```ruby # config/initializers/sghtmltopdf.rb Sghtmltopdf.configure do |c| c.page_size = "A4" c.margin_top = "20mm" c.gothic_font = Rails.root.join("vendor/fonts/NotoSansJP-Regular.ttf") end ``` -------------------------------- ### Set page size and margins via CLI Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html sghtmltopdf command with --page-size A4 and --margin-top/--margin-bottom set to 20mm. Accepted units are mm, cm, in, pt, and px; a bare number means mm. ```bash sghtmltopdf hello.html -o hello.pdf \ --page-size A4 --margin-top 20mm --margin-bottom 20mm ``` -------------------------------- ### Convert large HTML file using --streaming Source: https://waka.github.io/sghtmltopdf/en/usage/cli/streaming.html Run sghtmltopdf with the `--streaming` flag to read the HTML in chunks and release memory page by page. Best for HTML with tens of thousands of elements. ```shell sghtmltopdf big.html -o big.pdf --streaming ``` -------------------------------- ### Convert hello.html to hello.pdf Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html Basic sghtmltopdf command that converts hello.html to hello.pdf. Without -o, the output file is the input name with the extension changed to .pdf. ```bash sghtmltopdf hello.html -o hello.pdf ``` -------------------------------- ### Configure Sghtmltopdf with page size and gothic font in Rails initializer Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Sets global configuration for Sghtmltopdf, specifying A4 page size and a gothic font path. Global configuration is merged first, and call-site arguments take precedence. Use Sghtmltopdf.reset_config! to clear configuration, mainly for tests. ```ruby # for example config/initializers/sghtmltopdf.rb Sghtmltopdf.configure do |c| c.page_size = "A4" c.gothic_font = Rails.root.join("vendor/fonts/NotoSansJP-Regular.ttf") end ``` -------------------------------- ### Convert HTML to PDF via HTTP request Source: https://waka.github.io/sghtmltopdf/en/getting-started/docker.html Sends an HTML file to the server's /pdf endpoint with a page-size parameter and saves the response as a PDF. Requires the server to be running. ```bash curl --data-binary @invoice.html \ 'http://127.0.0.1:8080/pdf?page-size=A4' \ -o invoice.pdf ``` -------------------------------- ### wkhtmltopdf vs sghtmltopdf cover and toc syntax Source: https://waka.github.io/sghtmltopdf/en/migration/wkhtmltopdf-options.html Shows the positional-argument syntax of wkhtmltopdf for cover and table of contents versus the equivalent sghtmltopdf options. sghtmltopdf takes a single HTML file as input and uses --cover and --toc instead; merging several HTML files is not supported. ```shell wkhtmltopdf cover cover.html toc page.html out.pdf # wkhtmltopdf sghtmltopdf --cover cover.html --toc page.html -o out.pdf # sghtmltopdf ``` -------------------------------- ### Configure sghtmltopdf server_url Source: https://waka.github.io/sghtmltopdf/en/migration/wicked-pdf.html Configure the sghtmltopdf gem to delegate PDF generation to a separate server process. Only one URL is accepted; load balancing is expected to be handled externally (e.g., nginx or Kubernetes Service). If the server is unreachable, a Sghtmltopdf::ServerError is raised and no fallback to local conversion occurs. ```ruby Sghtmltopdf.configure { |c| c.server_url = "http://pdf.internal:8080" } ``` -------------------------------- ### Add header and footer with placeholders Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html sghtmltopdf command that adds a centered header and a footer with page numbers. [page] is replaced with the current page number and [topage] with the total page count. JavaScript is never executed, so these placeholders take its place. ```bash sghtmltopdf hello.html -o hello.pdf \ --header-center "Invoice" \ --footer-right "[page] / [topage]" \ --header-line ``` -------------------------------- ### Pass CLI options to Sghtmltopdf.render Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Pass CLI options using hash keys: long options become keys with underscores. Values are parsed exactly as on the CLI. Unknown keys cause a UsageError. Nested hashes (like wicked_pdf) are not accepted; write them flattened. ```ruby Sghtmltopdf.render(html, page_size: "A4", margin_top: "20mm", toc: true) # --page-size A4 --margin-top 20mm --toc ``` -------------------------------- ### Build CLI without HTTP server feature Source: https://waka.github.io/sghtmltopdf/en/getting-started/install.html Builds a smaller binary by disabling the HTTP server feature. Use this if you do not need the server mode. ```bash cargo build --release --no-default-features --features cli ``` -------------------------------- ### Enable remote assets with --allow-remote-assets Source: https://waka.github.io/sghtmltopdf/en/supports/images.html Use this command to allow sghtmltopdf to load remote assets (e.g., images, CSS) when converting HTML. This is off by default. Even when enabled, requests to non-global destinations (loopback, private, link-local, etc.) are always blocked. ```bash sghtmltopdf report.html --allow-remote-assets ``` -------------------------------- ### Convert HTML to PDF with streaming output Source: https://waka.github.io/sghtmltopdf/en/usage/server.html Sends a large HTML file to the PDF conversion endpoint with streaming output enabled. The response is saved to out.pdf. ```bash curl --data-binary @big.html 'http://127.0.0.1:8080/pdf?stream=1' -o out.pdf ``` -------------------------------- ### Use custom fonts with --font and --gothic-font Source: https://waka.github.io/sghtmltopdf/en/getting-started/docker.html Mounts a directory with custom fonts and passes them via --font and --gothic-font. These take precedence over the bundled fonts. ```bash docker run --rm -v "$PWD:/work" -w /work --user "$(id -u):$(id -g)" \ ghcr.io/waka/sghtmltopdf invoice.html -o invoice.pdf \ --font fonts/YourFont-Regular.ttf --gothic-font fonts/YourFont-Regular.ttf ``` -------------------------------- ### sghtmltopdf --no-images Source: https://waka.github.io/sghtmltopdf/en/supports/images.html Command to convert invoice.html to PDF without loading images. ```bash sghtmltopdf invoice.html --no-images ``` -------------------------------- ### Controller: render PDF with sghtmltopdf Source: https://waka.github.io/sghtmltopdf/en/migration/wicked-pdf.html A controller action that renders a PDF with sghtmltopdf. The render call uses the same options as wicked_pdf, so existing controllers keep working without changes. ```ruby def show respond_to do |format| format.pdf { render pdf: "invoice", template: "invoices/show", layout: "pdf" } end end ``` -------------------------------- ### Handle local file access with --allow-path Source: https://waka.github.io/sghtmltopdf/en/usage/cli/reference.html Shows the error when a local reference escapes the base directory and the corrected command using --allow-path. The check is lexical, so symlinks under the base directory are followed; --allow-path resolves real paths. ```bash $ sghtmltopdf pages/index.html -o out.pdf エラー: ../images/logo.png: 基準ディレクトリ(pages)の外を参照しています。 外部のファイルを読む場合は --allow-path でディレクトリを明示してください $ sghtmltopdf pages/index.html --allow-path . -o out.pdf ``` -------------------------------- ### Gemfile: swap wicked_pdf for sghtmltopdf Source: https://waka.github.io/sghtmltopdf/en/migration/wicked-pdf.html Replace the wicked_pdf and wkhtmltopdf-binary gems with sghtmltopdf in the Gemfile. The diff shows removing the old gems and adding the new one. ```ruby # Gemfile - gem "wicked_pdf" - gem "wkhtmltopdf-binary" + gem "sghtmltopdf" ``` -------------------------------- ### Upload PDF to S3 with multipart upload Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Upload the rendered PDF to S3 using a multipart upload, buffering chunks because every part except the last must be at least 5MB. The gem has no S3 support of its own, to avoid the dependency and because the code is short anyway. On error, the multipart upload is aborted and the exception is re-raised. ```ruby s3 = Aws::S3::Client.new upload = s3.create_multipart_upload(bucket: bucket, key: key, content_type: "application/pdf") parts, buffer = [], +"".b flush = lambda do part = s3.upload_part(bucket: bucket, key: key, upload_id: upload.upload_id, part_number: parts.size + 1, body: buffer) parts << {part_number: parts.size + 1, etag: part.etag} buffer.clear end begin Sghtmltopdf.render(html, server_url: server_url) do |bytes| buffer << bytes flush.call if buffer.bytesize >= 5 * 1024 * 1024 end flush.call unless buffer.empty? s3.complete_multipart_upload(bucket: bucket, key: key, upload_id: upload.upload_id, multipart_upload: {parts: parts}) rescue StandardError s3.abort_multipart_upload(bucket: bucket, key: key, upload_id: upload.upload_id) raise end ``` -------------------------------- ### Set page size and margins via CSS @page Source: https://waka.github.io/sghtmltopdf/en/getting-started/first-pdf.html CSS @page rule that sets size to A4 and margin to 20mm. If both CSS and CLI options are present, CSS wins; CLI options are treated as initial values. ```css @page { size: A4; margin: 20mm; } ``` -------------------------------- ### POST /pdf Source: https://waka.github.io/sghtmltopdf/en/usage/server.html Converts the HTML content in the request body to PDF and returns it as application/pdf. ```APIDOC ## POST /pdf ### Description Converts the HTML in the request body to PDF and returns it as application/pdf. ### Method POST ### Endpoint /pdf ### Parameters #### Query Parameters - **stream** (boolean) - Optional - If set to 1, the PDF is sent with chunked transfer encoding as each page becomes final. - **page-size** (string) - Optional - Page size for the PDF, e.g., A4. - **margin-top** (string) - Optional - Top margin size, e.g., 20mm. - **toc** (boolean) - Optional - Generate a table of contents when set to true. - **grayscale** (boolean) - Optional - Enable grayscale when set to 1 or true. Set to 0 or false to disable. Values may be percent encoded, with %XX and +. ### Request Body The request body must contain the HTML content to be converted. ### Response #### Success Response (200) The response is a PDF file with content type application/pdf. #### Error Response (400) Returns 400 if any query parameter is not on the allowlist. ``` -------------------------------- ### Reference assets in a PDF view with sghtmltopdf helpers Source: https://waka.github.io/sghtmltopdf/en/usage/ruby_rails.html Use these helpers in a Rails view to reference assets that the PDF engine can read. `sghtmltopdf_stylesheet_link_tag` expands the stylesheet into a `