Search code examples
c#pdf-generationabcpdf

ABCpdf, render an HTML within a "template": How to add margin?


I'm trying to render an HTML within a predefined PDF-template (e.g. within a frame.) The template/frame should reach the edges. But the HTML shouldn't do that. So I need some kind of margin for the HTML only. Here is my code so far:

var doc = new Doc();
doc.MediaBox.String = "A4";
doc.Rect.String = doc.MediaBox.String;

var id = doc.AddImageUrl(url.ToString());

doc.AddImageDoc("template.pdf", 1, doc.MediaBox);

while (doc.Chainable(id))
{
    doc.Page = doc.AddPage();

    id = doc.AddImageToChain(id);

    doc.AddImageDoc("template.pdf", 1, doc.MediaBox);
}

for (var i = 1; i <= doc.PageCount; i++)
{
    doc.PageNumber = i;
    doc.Flatten();
}

I see, that there is a possibility to pass a Rect to #AddImageDoc. But I don't have this option for #AddImageUrl.


Solution

  • Here is how I could solve the problem:

    First, I set the position and margins of the doc.Rect:

    doc.Rect.Position(15, 15);
    doc.Rect.Width = pageWidth - 2*15;
    doc.Rect.Height = pageHeight - 2*15;
    

    Then I filled the doc with the images from the parsed URL:

    var id = doc.AddImageUrl(url.ToString());
    
    while (doc.Chainable(id))
    {
        doc.Page = doc.AddPage();
        id = doc.AddImageToChain(id);
    }
    

    After this, I reset the doc.Rect to the size of the actual paper (in ma case: A4):

    doc.Rect.String = "A4";
    

    Now I can loop over all pages and add the template to them:

    for (var i = 1; i <= doc.PageCount; i++)
    {
        doc.PageNumber = i;
        doc.AddImageDoc(template, 1, doc.Rect);
        doc.Flatten();
    }