AccessViolationException After InsertPdf with HTML Headers/Footers
An AccessViolationException is thrown when calling AddHtmlHeaders on a PdfDocument after InsertPdf was used to merge pages from another document. The exception does not occur in Debug builds or when a debugger is attached.
System.AccessViolationException: Attempted to read or write protected memory. This is often an indication that other memory is corrupt.
at IronPdf.PdfDocument.AddHtmlHeaders(...)
In Release builds, the .NET JIT optimizer allows the garbage collector to reclaim managed objects before their lexical scope ends, when it can prove those objects will not be referenced again by managed code. A PdfDocument passed to InsertPdf can be collected while IronPDF's native Chrome layer is still reading it. The subsequent AddHtmlHeaders call then accesses freed memory, producing the access violation.
Solutions
Option 1: Apply headers and footers before InsertPdf (Recommended)
Reorder operations so headers and footers are written to the base document before any pages are inserted:
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:right; font-size:10px'>Page {page} of {total-pages}</div>"
};
var basePdf = renderer.RenderHtmlAsPdf(baseHtml);
basePdf.AddHtmlHeaders(renderer.RenderingOptions.HtmlHeader);
var supplementPdf = PdfDocument.FromFile("supplement.pdf");
basePdf.InsertPdf(supplementPdf, 0);
basePdf.SaveAs("output.pdf");
Option 2: Use GC.KeepAlive to prevent early collection
If the operation order cannot change, extend the managed lifetime of the source PdfDocument past the AddHtmlHeaders call:
var renderer = new ChromePdfRenderer();
renderer.RenderingOptions.HtmlHeader = new HtmlHeaderFooter
{
HtmlFragment = "<div style='text-align:right; font-size:10px'>Page {page} of {total-pages}</div>"
};
var basePdf = renderer.RenderHtmlAsPdf(baseHtml);
var supplementPdf = PdfDocument.FromFile("supplement.pdf");
basePdf.InsertPdf(supplementPdf, 0);
basePdf.AddHtmlHeaders(renderer.RenderingOptions.HtmlHeader);
GC.KeepAlive(supplementPdf);
basePdf.SaveAs("output.pdf");
GC.KeepAlive(supplementPdf) placed after AddHtmlHeaders prevents the JIT from scheduling collection of supplementPdf before the native merge is complete.

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.