0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

WeasyPrintで自動改ページされるページがあると出力が途中で止まる現象

Posted at

現象

A4サイズで印字することを想定したPDFをWeasyPrintで生成しようとしたところ改行できず処理が途中で止まってしまった。

  • PDF化するHTMLを作成
test.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PDF Sample</title>
    <style>
        body {
            /* A4用紙を意識したサイズ指定 */
            width: 172mm;
            height: 251mm;
            page-break-after: always;
        }
    </style>
</head>
<body>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
</body>
</html>

  • HTML出力結果(一番下までスクロールした結果)
    image.png

    • 最後まで出力できている
  • このHTMLをWeasyPrintでPDF化してみる

code.py

from weasyprint import HTML

html_content = open("./test.html","r",encoding="utf-8")

# HTMLからPDFを生成して保存
HTML(string=html_content.read()).write_pdf("./output.pdf")

  • PDF出力結果
    image.png
    • 改ページされるタイミングあたりで尻切れになって出力されてしまった

解決

  • bodyのCSSからheightの指定を無効化してみると想定通りのPDFが出力された
test.html
<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8">
    <title>PDF Sample</title>
    <style>
        body {
            /* A4用紙を意識したサイズ指定 */
            width: 172mm;
            /* height: 251mm; ここをコメントアウト!! */
            page-break-after: always;
        }
    </style>
</head>
<body>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
    <h1></h1>
</body>
</html>

  • PDF出力結果
    image.png
    • ちゃんと出た。

あとがき

  • ここでは書かなかったが現象が発生したPDFでは複数のHTMLを組み合わせてその繋ぎ目で明示的な改ページを行なっておりそちらは正常に改ページできていた。
  • そこから推測するにおそらくPDFとして出力する基準がbodyの範囲になっており、そこの範囲外に出力対象があると処理が途中で止まってしまうっぽい
  • HTMLの方も本来はPDFと同じ出力結果になるけどブラウザが気を効かせてはみ出した部分も出力してくれていたものと思われる
  • ロジック要因っぽい現象だったためまさかCSSが絡んでいると思わず原因の特定にかなり時間を食った
    • WeasyPrintのバグを疑った・・・ごめんなさい・・・
0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?