Search code examples
.net-coreitext7c#-6.0

How can itext7 remove the space between paragraph text and paragraph top?


Using itext7, I created a pdf with two paragraphs.

string cardPdf = "card.pdf"; float cardWidth = 266.5f; float cardHeight = 164.4f;
using (PdfDocument cardDoc = new PdfDocument(new PdfWriter(cardPdf)))
using (Document doc = new Document(cardDoc))
{
    PdfPage page = cardDoc.AddNewPage(new iText.Kernel.Geom.PageSize(cardWidth, cardHeight));
    Paragraph pg1 = new Paragraph("WriteParagraph 1").SetFontSize(10f);
    pg1.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
    doc.Add(pg1);
    Paragraph pg2 = new Paragraph("WriteParagraph 2").SetFontSize(20f);
    pg2.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
    doc.Add(pg2);
}

I found that there are gaps at the top of the paragraph text and the background rectangle, and different font sizes cause different gaps. How can I remove the spacing.


Solution

  • You can use either of those methods to reduce space around to document.

    Document Level

    SetMargins(float topMargin, float rightMargin, float bottomMargin, float leftMargin);
    
    SetTopMargin(float topMargin);
    SetRightMargin(float rightMargin);
    SetBottomMargin(float bottomMargin);
    SetLeftMargin(float leftMargin);
    

    Paragraph Level

    SetMargins(float topMargin, float rightMargin, float bottomMargin, float leftMargin);
    
    SetMarginTop(float topMargin);
    SetMarginRight(float rightMargin);
    SetMarginBottom(float bottomMargin);
    SetMarginLeft(float leftMargin);
    

    To control line spacing/leading for the paragraph.

    SetMultipliedLeading(float leadingValue);
    

    If need to control leading on overall document level.

    SetProperty(int property, object value);
    
    SetProperty(Property.LEADING, new Leading(Leading.MULTIPLIED, float leading Value);
    

    Try this:

    string cardPdf = "card.pdf"; float cardWidth = 266.5f; float cardHeight = 164.4f;
    using (PdfDocument cardDoc = new PdfDocument(new PdfWriter(cardPdf)))
    using (Document doc = new Document(cardDoc))
    {
        doc.SetMargins(15f, 20f, 15f, 20f);
        PdfPage page = cardDoc.AddNewPage(new iText.Kernel.Geom.PageSize(cardWidth, cardHeight));
        Paragraph pg1 = new Paragraph("WriteParagraph 1").SetFontSize(10f);
        pg1.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
        pg1.SetMultipliedLeading(0.8f);
        doc.Add(pg1);
        Paragraph pg2 = new Paragraph("WriteParagraph 2").SetFontSize(20f);
        pg2.SetMultipliedLeading(0.8f);
        pg2.SetMarginTop(0f);
        pg2.SetBackgroundColor(iText.Kernel.Colors.ColorConstants.YELLOW);
        doc.Add(pg2);
    }