Reduza o tamanho do arquivo com cabeçalhos e rodapés de imagem Base64

This article was translated from English: Does it need improvement?
Translated
View the article in English

Adicionar uma imagem Base64 a um cabeçalho ou rodapé em um PDF grande de múltiplas páginas pode aumentar drasticamente o tamanho do arquivo de saída. A solução é incorporar a imagem uma vez, em vez de em cada página, enquanto ainda permite que o texto por página, como {page}, seja renderizado normalmente.

O inchaço acontece por causa de como o renderizador manipula um fragmento combinado. Quando um único fragmento contém tanto a imagem quanto o conteúdo dinâmico, como {page}, o motor trata todo o HTML como dinâmico e reincorpora a imagem Base64 em todas as páginas. Dividir o trabalho em duas passagens mantém a imagem estática e a camada de número de página pequena.

Solução

1. Divida o cabeçalho ou rodapé em dois fragmentos

Separe o conteúdo em um fragmento estático e um dinâmico. Coloque a imagem e qualquer texto que nunca muda no fragmento estático. Coloque o conteúdo por página, como {page}, no fragmento dinâmico. Dê aos dois fragmentos o mesmo layout de tabela e larguras de célula para que o texto dinâmico se encaixe corretamente sobre a camada estática.

2. Adicione o fragmento estático primeiro

Chame AddHtmlHeadersAndFooters apenas com o fragmento estático. A imagem Base64 é renderizada e incorporada uma única vez.

3. Adicione o fragmento dinâmico em uma segunda passagem

Chame AddHtmlHeadersAndFooters novamente apenas com o fragmento dinâmico. Como esta passagem não carrega imagem, o conteúdo por página permanece pequeno.

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");
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");
Imports IronPdf

Dim pdf = PdfDocument.FromFile("input.pdf")

' Static layer: holds the Base64 image. The page-number cell is left empty.
Dim staticFooter As String = "
<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.
Dim dynamicFooter As String = $"
<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 With {
    .HtmlFooter = New HtmlHeaderFooter With {.HtmlFragment = staticFooter, .MaxHeight = 40}
})

' Pass 2: add the dynamic page-number footer (no image, stays small).
pdf.AddHtmlHeadersAndFooters(New ChromePdfRenderOptions With {
    .HtmlFooter = New HtmlHeaderFooter With {.HtmlFragment = dynamicFooter, .MaxHeight = 40}
})

pdf.SaveAs("output.pdf")
$vbLabelText   $csharpLabel

Os dois fragmentos table-layout:fixed compartilham larguras de célula idênticas, então o número da página na segunda passagem fica exatamente onde a célula vazia estava na primeira. A mesma técnica se aplica aos cabeçalhos: mantenha a imagem na passagem estática e coloque qualquer texto de cabeçalho dinâmico na segunda passagem.

AvisoSe os dois fragmentos não compartilharem a mesma estrutura de tabela e larguras de célula, o texto dinâmico, como o número da página, não vai se alinhar sobre a camada estática.

Opção: Referenciar uma imagem externa ou SVG

Se você não precisa da imagem embutida como Base64, apontar o <img> para um arquivo externo ou usar um SVG pode reduzir ainda mais o tamanho do arquivo de saída do que uma string Base64.

Curtis Chau
Redator Técnico

Curtis Chau é bacharel em Ciência da Computação (Universidade Carleton) e se especializa em desenvolvimento front-end, com experiência em Node.js, TypeScript, JavaScript e React. Apaixonado por criar interfaces de usuário intuitivas e esteticamente agradáveis, Curtis gosta de trabalhar com frameworks modernos e criar manuais ...

Leia mais
Pronto para começar?
Nuget Downloads 20,296,129 | Versão: 2026.7 recém-lançado
Still Scrolling Icon

Ainda está rolando a tela?

Quer provas rápidas? PM > Install-Package IronPdf
executar um exemplo Veja seu HTML se transformar em um PDF.