iTextpdf background is set only up to the text available

The following is my code to generate the PDF from Java using iText:

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Font.FontFamily;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
 
 
 
public class ChunkBackground {
 
    public static final String DEST = "C:\test.pdf";
 
    public static void main(String[] args) throws IOException,
            DocumentException {
        File file = new File(DEST);
        file.getParentFile().mkdirs();
        new ChunkBackground().createPdf(DEST);
    }
 
    public void createPdf(String dest) throws IOException, DocumentException {
        Document document = new Document();
        PdfWriter.getInstance(document, new FileOutputStream(dest));
        document.open();
        
        Font f = new Font(FontFamily.HELVETICA, 8.5f, Font.BOLD, BaseColor.WHITE);
        Chunk c = new Chunk("FOR EMPLOYMENT WITH XXXX YYYY XXXXX", f);
        
        c.setBackground(BaseColor.BLACK);
        Paragraph p = new Paragraph();
        p.add(c);
 
        document.add(p);
        document.close();
    }
     
}

Here is the PDF generated:

PDF

How can I set the width of the background irrespective of the text width?

Answer

What I would do is include the Chunk in a PdfTable with 100% width like this:

    Font f = new Font(FontFamily.HELVETICA, 8.5f, Font.BOLD, BaseColor.WHITE);
    Chunk c = new Chunk("FOR EMPLOYMENT WITH XXXX YYYY XXXXX", f);

    PdfPTable table = new PdfPTable(1);
    PdfPCell cell = new PdfPCell(new Phrase(c));

    cell.setBackgroundColor(BaseColor.BLACK);
    table.addCell(cell);
    table.setWidthPercentage(100);

    document.add(table);
    document.close();

Output:

enter image description here

Leave a Reply

Your email address will not be published. Required fields are marked *