Kishirada
Kishirada

Reputation: 152

Using iText how do I change the distance between new lines?

I'm messing around with itext, and I was changing the fontsize and as a result I end up with some weirdly spaced text in my pdf:

enter image description here

Which I'd like to turn into something like this: (Excuse the poor image editing)

enter image description here

This is the code I use to enter the text:

private fun setBaseInfo(info: ArrayList<String>): PdfPCell
{
    val cell = PdfPCell()

    val glue = Chunk(VerticalPositionMark())
    val p = Paragraph()
    p.font.size = 8.0f

    for (str in info)
    {
        p.add(glue)
        p.add(str)
        p.add("\n")
    }

    cell.border = Rectangle.NO_BORDER
    cell.addElement(p)

    return cell
}

And this is the info I feed it:

private fun foo(): ArrayList<String>
{
    val array = ArrayList<String>()
    array.add("Hi")
    array.add("StackOverflow")
    array.add("I'd Like")
    array.add("This")
    array.add("text")
    array.add("to be closer")
    array.add("together!")
    return array
} 

When removing p.add("\n") this is the output: enter image description here

Upvotes: 0

Views: 451

Answers (1)

Joris Schellekens
Joris Schellekens

Reputation: 9012

Full disclosure: former iText employee here

This is how I would do it:

public static void main(String[] args) throws IOException {

    // create a temp file to hold the output
    File outputFile = File.createTempFile("stackoverflow",".pdf");

    PdfDocument pdfDocument =  new PdfDocument(new PdfWriter(outputFile));
    Document layoutDocument = new Document(pdfDocument);

    String[] lines = {"Hi","StackOverflow","I'd like","this","text","to","be","closer","together!"};
    for(String line : lines){
        layoutDocument.add(new Paragraph(line)
                .setMultipliedLeading(0.5f));   // this is where the magic happens
    }

    layoutDocument.close();
    pdfDocument.close();

    // display the temp file with the default PDF viewer
    Desktop.getDesktop().open(outputFile);
}

I changed a couple of things:

  • Use the latest version of iText whenever possible. You want to benefit from several years of bugfixes and a newer architecture.
  • Do not use tables to solve layout issues.
  • Use leading (either MultipliedLeading or FixedLeading) on Paragraph objects to fix your issue.

Upvotes: 4

Related Questions