使用Base64圖像表頭和表尾減少檔案大小
在大型多頁PDF中新增Base64圖像到表頭或表尾可能會顯著增加輸出檔案的大小。 解決方法是嵌入圖像一次而不是每頁,仍然允許像{page}這樣的每頁文字正常渲染。
膨脹發生是因為渲染器如何處理合併的片段。 當一個片段同時包含圖像和動態內容如{page}時,引擎將所有的HTML視為動態,並在每頁重新嵌入Base64圖像。 將工作分成兩個步驟,保持圖像靜態和頁號層小。
解決方案
1. 將表頭或表尾分成兩個片段
將內容分成靜態片段和動態片段。 將從未更改過的圖像和任何文字放置在靜態片段中。 將每頁內容如{page}放置在動態片段中。 為兩個片段提供相同的表格佈局和單元格寬度,以便動態文字正確落在靜態層之上。
2. 先新增靜態片段
僅使用靜態片段調用AddHtmlHeadersAndFooters。 Base64圖像將被渲染並嵌入一次。
3. 在第二步中新增動態片段
再次僅使用動態片段調用AddHtmlHeadersAndFooters。 由於此步驟不包含圖像,每頁內容保持小。
using IronPdf;
var pdf = PdfDocument.FromFile("input.pdf");
// Static layer: holds the Base64 image. The page-number cell is left empty.
string staticFooter = @"
<table style='width:100%; table-layout:fixed;'>
<tr>
<td style='width:20%;'>
<img src='data:image/png;base64,iVBORw0KGg...' style='width:150px;' />
</td>
<td style='width:80%; text-align:right;'></td>
</tr>
</table>";
// Dynamic layer: holds only {page}. Same layout, but no image.
string dynamicFooter = $@"
<table style='width:100%; table-layout:fixed;'>
<tr>
<td style='width:20%;'></td>
<td style='width:80%; text-align:right; font-size:10px;'>Page {{page}} of {pdf.PageCount}</td>
</tr>
</table>";
// Pass 1: add the static image footer (image embedded once).
pdf.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
{
HtmlFooter = new HtmlHeaderFooter { HtmlFragment = staticFooter, MaxHeight = 40 }
});
// Pass 2: add the dynamic page-number footer (no image, stays small).
pdf.AddHtmlHeadersAndFooters(new ChromePdfRenderOptions
{
HtmlFooter = new HtmlHeaderFooter { HtmlFragment = dynamicFooter, MaxHeight = 40 }
});
pdf.SaveAs("output.pdf");
兩個table-layout:fixed片段共享相同的單元格寬度,因此第二步中的頁碼正好位於第一步中的空單元格位置。相同技術適用於表頭:在靜態步驟中保留圖像,並在第二步中放置任何動態表頭文字。
選項:參考外部圖像或SVG
如果您不需要將圖像內嵌為Base64,將<img>指向外部檔案或使用SVG可以進一步縮小輸出大小比Base64字串更有效。

Curtis Chau holds a Bachelor’s degree in Computer Science (Carleton University) and specializes in front-end development with expertise in Node.js, TypeScript, JavaScript, and React. Passionate about crafting intuitive and aesthetically pleasing user interfaces, Curtis enjoys working with modern frameworks and creating well-structured, visually appealing manuals.