iText 7 can not set margin

Petr Gavrilov picture Petr Gavrilov · Nov 24, 2017 · Viewed 7.2k times · Source

I have an HTML string, i need to convert it to pdf, but pdf that i need must have specific size and margin. I did as the example show, now i have pdf with width and height that i set, BUT i can`t change or delete the margin, so pls help me.

 using (FileStream fs = new FileStream(somePDFFile, FileMode.OpenOrCreate, FileAccess.Write))
            {

                iText.Kernel.Pdf.PdfWriter pdfWriter = new iText.Kernel.Pdf.PdfWriter(fs);

                iText.Kernel.Pdf.PdfDocument pdfDoc = new iText.Kernel.Pdf.PdfDocument(pdfWriter);

                var v = pdfDoc.GetDefaultPageSize().ApplyMargins<iText.Kernel.Geom.Rectangle>(1, 1, 1, 1, true);
                pdfDoc.GetDefaultPageSize().SetWidth(250f);
                pdfDoc.GetDefaultPageSize().SetHeight(200f);
                pdfDoc.GetCatalog().SetLang(new iText.Kernel.Pdf.PdfString("en-US"));
                //Set the document to be tagged
                pdfDoc.SetTagged();



                iText.Html2pdf.ConverterProperties props = new iText.Html2pdf.ConverterProperties();

                iText.Html2pdf.HtmlConverter.ConvertToPdf(htmlString, pdfDoc, props);

                pdfDoc.Close();



            }

Answer

Bruno Lowagie picture Bruno Lowagie · Nov 24, 2017

I searched for an answer, but I could only find this approach:

public void createPdf(String src, String dest) throws IOException {
    ConverterProperties properties = new ConverterProperties();
    properties.setBaseUri(new File(src).getParent());
    List<IElement> elements =
            HtmlConverter.convertToElements(new FileInputStream(src), properties);
    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    pdf.setTagged();
    Document document = new Document(pdf);
    document.setMargins(100, 50, 50, 100);
    for (IElement element : elements) {
        document.add((IBlockElement)element);
    }
    document.close();
}

In other words: I convert the HTML to a list of elements, and I then add those elements to a Document for which I define a margin.

My preferred solution would have been to define the margin at the level of the <body> tag as done in How to margin the body of the page (html)? Unfortunately, I noticed that this isn't supported yet (and I made a ticket for the iText development team to fix this).

I also tried the convertToDocument() method, but I wasn't able to set immediateFlush to false. I also asked the team to look into this.

Maybe there's also a property that could be introduced, although I'm not all that sure if this should be a ConverterProperties property, a PdfDocument property, or a PdfWriter property.

Update:

You could use the @page rule in CSS to define the margins. For instance:

<style>
    @page {
        margin-top: 200pt;
    }
</style>

This creates a PDF with a top margin of 200pt.