DOMPDF を使用して PDF ファイルを作成しています。PDF に抽出する大きなコンテンツがあり、すべてのページにヘッダーが必要です。DOMPDFを使用してすべてのページにヘッダーが表示されるように、PDFにヘッダーとフッターを追加する方法を誰でも教えてください。
4 に答える
0.6.0 コードでは、HTML+CSS を使用してヘッダーとフッターを生成できます。インライン PHP を使用する場合と比較すると、いくつかの制限があります (たとえば、まだ PAGE_COUNT プレースホルダーがないなど)。これが実行可能かどうかは、ニーズによって異なります。
次のコードは、ヘッダーとフッターを含む 2 ページのドキュメントを生成します。
<html>
<head>
<style>
@page { margin: 180px 50px; }
#header { position: fixed; left: 0px; top: -180px; right: 0px; height: 150px; background-color: orange; text-align: center; }
#footer { position: fixed; left: 0px; bottom: -180px; right: 0px; height: 150px; background-color: lightblue; }
#footer .page:after { content: counter(page, upper-roman); }
</style>
<body>
<div id="header">
<h1>Widgets Express</h1>
</div>
<div id="footer">
<p class="page">Page </p>
</div>
<div id="content">
<p>the first page</p>
<p style="page-break-before: always;">the second page</p>
</div>
</body>
</html>
不足している機能の一部にアクセスする必要がある場合は、2 つのスタイルを組み合わせて使用することもできます。メソッドを使用して追加された PDF オブジェクトとテキストpage_text
は、HTML コンテンツの上に表示されます。
DOMPDF wikiに FAQ エントリがあります:ヘッダーとフッターまたはページ番号を追加する方法はありますか? .
したがって、次の「インライン PHP」スニペットを HTML 入力に追加できます (page_text
フッターに同様の -call を追加します)。
<script type="text/php">
if ( isset($pdf) ) {
$font = Font_Metrics::get_font("helvetica", "bold");
$pdf->page_text(72, 18, "Header: {PAGE_NUM} of {PAGE_COUNT}",
$font, 6, array(0,0,0));
}
</script>
これを呼び出し元側で (つまり、PHP コードで直接) 実装したい場合は、DOMPDFS の -method を呼び出す必要があります。このメソッドは、上記の例のようにメソッドget_canvas()
を呼び出すことができる、基礎となる PDF-Renderer を返します。page_text
私が何を意味するかをお見せしましょう:
// your dompdf setup
$dompdf = new DOMPDF();
$dompdf->load_html($html);
$dompdf->render();
// add the header
$canvas = $dompdf->get_canvas();
$font = Font_Metrics::get_font("helvetica", "bold");
// the same call as in my previous example
$canvas->page_text(72, 18, "Header: {PAGE_NUM} of {PAGE_COUNT}",
$font, 6, array(0,0,0));
最終的には後で電話する必要がありますpage_text
(load_html
試してみてください)。
ドキュメントのヘッダー、フッター、コンテンツを次のように定義します。
<html>
<head>
<style>
@page {
margin: 100px 25px;
}
header {
position: fixed;
top: -60px;
height: 50px;
background-color: #752727;
color: white;
text-align: center;
line-height: 35px;
}
footer {
position: fixed;
bottom: -60px;
height: 50px;
background-color: #752727;
color: white;
text-align: center;
line-height: 35px;
}
</style>
</head>
<body>
<header>
Header
</header>
<footer>
Footer
</footer>
<main>
<!-- Your main content -->
</main>
</body>
</html>