Page margins when converting HTML to PDF

Hey!

We’ve been using GroupDocs.Conversion for converting templates written in HTML into printable A4 size PDF documents.

I’ve been searching and looking around this forum, but I can’t find anything about customizing page margins for the resulting PDF, except for this thread Options for Conversion in which it’s mentioned that the named feature is not supported.

The linked thread seems to be from 2015, though, so I was wondering whether such a thing has been implemented yet, as having specific margin sizes is important for our client.

Right now, it seems there is no way to keep the document looking correct while having custom margin sizes.

Our input HTML looks more or less like this:

<html>
    <head>
    <style id="styles">
            :root {
                counter-set: pages 0;
            }

        @page {
            counter-increment: pages;
        }

    @page {
        size: A4;
        margin-left: 20mm;
        margin-right: 10mm;

        @bottom-right-corner {
            content: counter(page) "/" counter(pages);
            font-size: 8.5pt;
        }
    }

    body {
        font-size: 10.5pt;
    }
</style>
</head>
<body>
Lorem ipsum dolor sit amet, consectetur adipiscing elit. Nulla sed egestas magna. Aenean mollis mi nec ligula condimentum, a ultricies purus volutpat. Vivamus felis est, viverra sit amet pellentesque eu, consequat non dui. Suspendisse gravida placerat est vitae luctus. Nullam ullamcorper, risus quis ultricies condimentum, diam mauris ultricies velit, vitae pellentesque arcu nisi vitae risus. Proin massa risus, aliquam nec posuere nec, commodo et odio. Ut eros sem, finibus eget congue eu, commodo id nunc. Maecenas accumsan nulla faucibus lacinia lobortis. Vivamus in malesuada est. Phasellus ullamcorper condimentum sagittis. Sed nulla mi, pharetra ac aliquet sit amet, porta id quam. Aenean ante leo, pharetra non fermentum id, semper a turpis. Curabitur sit amet arcu iaculis, hendrerit justo nec, volutpat ipsum. Etiam mollis enim a tortor semper, eu auctor lectus dapibus. Nullam sagittis, urna viverra consequat accumsan, enim metus luctus enim, ut tempor velit metus nec tellus. Ut dapibus luctus velit a venenatis.
</body>
</html>

And the code to convert from HTML to PDF:

var htmlString = "THE ABOVE HTML";
var outputPath = "path/to/output.pdf";
// ConvertStringToStream creates a MemoryStream containing the HTML
using (var converter = new Converter(() => ConvertStringToStream(htmlString)))
{
                converter.Convert(outputPath, new PdfConvertOptions()
                {
                    PageOrientation = PageOrientation.Portrait,
                    Format = PdfFileType.Pdf,
                    PageSize = PageSize.A4,
                    Dpi = 300,
                    Width = 2480,
                    Height = 3508,
                    MarginLeft = 0,
                    MarginRight = 0,
                });
}

Is there any chance you could tell me how to achieve such margins that I’ve specified in the CSS which could be smaller than what the converter adds as default (around 3.5cm on the left and right)?

PS. We do also have a license for GroupDocs.Viewer if that might help solve this issue.

Thank you in advance!

1 Like

@civask

Thanks for reaching us out. The MarginLeft and MarginRight properties in the code you provided are indeed used for specifying custom margins. These values are in pixels and can be adjusted to achieve the desired left and right margins.
Could you please share more details on this scenario? Did you try to change these margins other than 0?

  • If you want to achieve margins smaller than the default 3.5cm (approximately 99 pixels at 300 DPI) on the left and right, you should modify the MarginLeft and MarginRight values.
  • You can experiment with different pixel values for these properties until you achieve the exact margins specified in your CSS.

Otherwise, are you looking for a way to obtain exact pixel values (programmatically by the API at the Conversion time) that correspond to the CSS margins specified in your HTML when converting it to a PDF?

Hey, thank you for the quick answer!

I am aware that the margin values are in pixels (the properties have summaries, fortunately). The problem is that it seems the default value for these margin properties is 0 since when I set them as 0, nothing changed.

Increasing these values only made the margins bigger (which is the opposite of what I want), while going into negative values was counterintuitive and seemed to mess with the width of the pages (resulting in not being A4 anymore).

I’m trying to understand whether it’s possible to generate a PDF document that has no margins at all, for example. If this was possible for HTML to PDF, then what I actually need should be as well.
All the while retaining the A4 dimensions as these PDF documents should look as close to what will be printed out eventually.

Right now it seems the converter has an opinion what the minimum margins should be (the ~3.5cm I mentioned earlier).

I will try experimenting a little more, but it would be a huge timesaver if you could tell me whether I’m approaching this wrong or if it’s even possible.

Thanks again!

1 Like

@civask
Thanks for the details.

We have opened the following new ticket(s) in our internal issue tracking system and will deliver their fixes according to the terms mentioned in Free Support Policies.

Issue ID(s): CONVERSIONNET-6332

You can obtain Paid Support Services if you need support on a priority basis, along with the direct access to our Paid Support management team.

1 Like

@civask

When we test this scenario with Conversion API version 23.9, without setting any margin using the following code. Hence, we get no margins in the output - result.pdf (90.4 KB).

// Initialize the HTML to PDF converter with the input HTML file, "test.html"
using (var converter = new Converter("test.html"))
{
    // Define the conversion options
    var pdfOptions = new PdfConvertOptions()
    {
        PageOrientation = PageOrientation.Portrait,  // Set the page orientation to Portrait
        Format = PdfFileType.Pdf,                    // Define the output file format as PDF
        PageSize = PageSize.A4                       // Set the page size to A4
    };

    // Convert the HTML to PDF using the defined options and save it as "result.pdf"
    converter.Convert("result.pdf", pdfOptions);
}

Could you please try this at your end? Let us know in case of any issue.

1 Like

Hey,

I upgraded Conversion from 23.5.0 to 23.9.0 and it seems the issue has indeed been resolved in one of these later versions.

For some reason the CSS at-rules (@page, @bottom-right-corner) we use for the page numbering do not work in the latest version, though, which makes this kind of a win-lose situation.

It’s also a bit unclear why now, when I don’t set margins in Conversion options and set them in CSS, the pages of the resulting PDF are also in different sizes with the first few pages being A4 and the following being smaller.

Not yet sure whether these things are happening due to some mistake on my part or some update in the package, but I’m going to try and fix it. But if you have any tips regarding that in the meanwhile, then I’d really appreciate hearing those out.

Thanks for looking into it either way!

EDIT: @page seems to work with background-color, so I figure the problem could be on my side

@civask

Please note that the API is UI-agnostic and good to know that issue is fixed.