Skip to content
Advertisement

iText: how to add a String to a cell

Hi guys I am an absolute beginner so go easy on me, why is this not working for me, I really do not understand why this is not working, but I am a beginner so if someone could correct this for me, I would really appreciate it. I am surprised that it does not work


import com.itextpdf.kernel.geom.PageSize;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.layout.Document;
import com.itextpdf.layout.element.Cell;

import com.itextpdf.layout.element.Table;

import java.io.IOException;

public class Main {

    public static void main(String[] args) throws IOException {
        String path = "C:\Users\KevinOneDrive\Desktop\Generated PDFs\Table.pdf";
        String logosrc = "C:\Users\Kevin\OneDrive\Desktop\Generated PDFs\Images\mainlogo.png";


        PdfWriter pdfWriter = new PdfWriter(path);
        PdfDocument pdfDocument = new PdfDocument(pdfWriter);
        Document document = new Document(pdfDocument);
        pdfDocument.setDefaultPageSize(PageSize.A4);

        float col = 280f;
        float columnWidth[] = {col, col};
        Table table = new Table(columnWidth);

        table.addCell(new Cell().add("INVOICE"));

My Error messege:

java: no suitable method found for add(java.lang.String)
    method com.itextpdf.layout.element.Cell.add(com.itextpdf.layout.element.IBlockElement) is not applicable
      (argument mismatch; java.lang.String cannot be converted to com.itextpdf.layout.element.IBlockElement)
    method com.itextpdf.layout.element.Cell.add(com.itextpdf.layout.element.Image) is not applicable
      (argument mismatch; java.lang.String cannot be converted to com.itextpdf.layout.element.Image)

Answer

iText 7.0 had a method add(String) for Cell.

For iText 7.1, as documented in the API, a Cell takes only a block element or an image for its add() method. Block elements in iText are things like paragraphs, lists and divs.

You can wrap your String in a Paragraph:

table.addCell(new Cell().add(new Paragraph("INVOICE")));

For further differences between 7.0 and 7.1, it may be useful to take a look at the 7.1 migration guide, which also include this change:

com.itextpdf.layout.element.Cell#add(java.lang.String) has been removed, use a BlockElement such as Paragraph instead.

Advertisement