I am creating labels (as in Avery labels) using iText 5 tables. Positioning of label elements requires some very tight tolerances in order to fit everything on the label. My problem is that I have various zones on the label as PdfPCells. I need to fit text into these zones with 0 wasted space. But I always seem to have extra space at the top of the cell. This is best illustrated by using .setVerticalAlignment(Element.ALIGN_TOP); which does not bring the text to the top of my cell.
I'd show image but apparently I'm not allowed.
How do I get rid of this space?
package actions.test;
import java.io.FileOutputStream;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
public class PdfCellTest
{
public static void main(String[] args) throws Exception {
System.out.println("Cell Test");
BaseFont bf = BaseFont.createFont
(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
Font companyFont =new Font(bf);
companyFont.setSize(10.5f);
companyFont.setColor(BaseColor.BLUE);
companyFont.setStyle(Font.BOLD);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("c:\\temp\\celltest.pdf"));
document.open();
PdfPTable main = new PdfPTable(1);
main.setWidthPercentage(30);
Phrase companyPhrase = new Phrase("My Company Name, LLC",companyFont);
PdfPCell companyCell = new PdfPCell(companyPhrase);
companyCell.setHorizontalAlignment(Element.ALIGN_CENTER);
companyCell.setVerticalAlignment(Element.ALIGN_TOP);
companyCell.setBorder(Rectangle.BOX);
companyCell.setBorderColor(BaseColor.RED);
companyCell.setPadding(0);
companyCell.setFixedHeight(10.5f);
companyCell.setBackgroundColor(BaseColor.WHITE);
main.addCell(companyCell);
document.add(main);
document.close();
}
}
Run Code Online (Sandbox Code Playgroud)
您非常接近解决方案。您设置的所有属性都正常,现在尝试添加:
companyCell.setUseAscender(true);
companyCell.setUseDescender(true);
Run Code Online (Sandbox Code Playgroud)
这些方法有什么作用?它们考虑了存储在正在使用的字体中的度量。您谈论的是顶部填充,但您会注意到“下降器”也会对底部填充产生很好的影响。
顶部的“填充”并不是真正的填充。是“领头羊”。您使用的是默认字体,即 Helvetica 12pt。默认行距是字体大小的 1.5 倍。那是18pt。您正在文本模式下工作,这意味着您可以在单元格级别定义行距(与在元素级别定义行距的复合模式相反)。例如:您可以像这样从顶部的“填充”中删除 4pt:
companyCell.setLeading(14);
Run Code Online (Sandbox Code Playgroud)
重要提示:这也将减少不同行之间的间距。如果这不是一个选项,您可能需要切换到复合模式。