IText 5 Pdf表列宽度不起作用

时间:2018-11-18 19:34:08

标签: java pdf itext

我正在尝试创建一个格式为Avery名称标签5395的PDF文件,该标签在8 1/2 x 11的纸上具有8个标签。我用实际工作表中的测量值设置了一个PdfPTable,并将其写出。问题是列宽和表的整体宽度不正确。而不是3.5“的列,它们大约是2.8”。我的代码如下。我想念什么?

public class TryNameLabelPdf {
public static void main(String[] args) {
PdfPTable theTable;
Document theDoc;
    try {
        // Avery 5395 Name Badges
        theDoc = new Document();
        Rectangle pageSize = new Rectangle(612f,792f); // 8.5*72 = 612, 11*72= 792
        theDoc.setPageSize(pageSize);
        theDoc.setMargins(49.5f, 49.5f,41.06f, 41.06f);  // left, right, top, bottom
        theTable = new PdfPTable(2);
        float[] columnWidths = {252f, 252f}; // 3.5*72 = 252
        theTable.setWidths(columnWidths);        
        theTable.setTotalWidth(504f); // 2*252 = 504
        PdfWriter.getInstance(theDoc, new FileOutputStream("MyTestTable.pdf"));
        theDoc.open();
        PdfPCell cell1 = new PdfPCell(new Paragraph("Cell 1.1"));
        cell1.setFixedHeight(174);
        PdfPCell cell2 = new PdfPCell(new Paragraph("Cell 1.2"));
        cell2.setFixedHeight(174);
        PdfPCell cell3 = new PdfPCell(new Paragraph("Cell 2.1"));
        cell3.setFixedHeight(174);
        PdfPCell cell4 = new PdfPCell(new Paragraph("Cell 2.2"));
        cell4.setFixedHeight(174);
        PdfPCell cell5 = new PdfPCell(new Paragraph("Cell 3.1"));
        cell5.setFixedHeight(174);
        PdfPCell cell6 = new PdfPCell(new Paragraph("Cell 3.2"));
        cell6.setFixedHeight(174);
        PdfPCell cell7 = new PdfPCell(new Paragraph("Cell 4.1"));
        cell7.setFixedHeight(174);
        PdfPCell cell8 = new PdfPCell(new Paragraph("Cell 4.2"));
        cell8.setFixedHeight(174);
        theTable.addCell(cell1);
        theTable.addCell(cell2);
        theTable.addCell(cell3);
        theTable.addCell(cell4);
        theTable.addCell(cell5);
        theTable.addCell(cell6);
        theTable.addCell(cell7);
        theTable.addCell(cell8);
        theDoc.add(theTable);
        theDoc.close();
    } catch (DocumentException ex) {
        Logger.getLogger(TryNameLabelPdf.class.getName()).log(Level.SEVERE, null, ex);
    } catch (FileNotFoundException ex) {
        Logger.getLogger(TryNameLabelPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
}

}

1 个答案:

答案 0 :(得分:0)

发现了问题!事实证明,设置后需要锁定列宽:

            theTable.setLockedWidth(true); // Without this the table width won't stick!