itextpdf背景仅设置为可用文本

时间:2017-10-23 09:08:48

标签: java itext pdf-generation

以下是我使用itext

从Java生成PDF的代码
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();
    }

}

以下是生成的PDF,有人可以帮助我设置背景的宽度而不考虑文字宽度吗?

1 个答案:

答案 0 :(得分:2)

我要做的是将Chunk包含在100%宽度的PdfTable中,如下所示:

    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();

输出:

enter image description here