image.png
import java.io.FileOutputStream;
import com.lowagie.text.*;
import com.lowagie.text.pdf.PdfPCell;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
import com.rh.soc.assetmanage.model.pdf.PdfParagraph;
/**
* @author GQ
*/
public class ITextPdfUtil {
private static float lineHeight = (float)25.0;
private static PdfPTable tables =new PdfPTable(3);
public static void main(String[] args) {
String tmpPath ="C:\\Users\\53601\\Downloads\\test1.pdf";
try{
Rectangle rectangle1 = new Rectangle(1684.0F, 842.0F);
Document pdfDoc =new Document(rectangle1, 50, 50, 50, 50);
PdfWriter.getInstance(pdfDoc, new FileOutputStream(tmpPath));
pdfDoc.open();
//当前页放满换行,避免出现空白行
tables.setSplitLate(false);
tables.setWidthPercentage(60);
//handler
writeHandler();
//body
for (int i = 0; i < 2; i++) {
writeBody();
}
pdfDoc.add(tables);
pdfDoc.close();
} catch(Exception e) {
e.printStackTrace();
}
}
private static void writeHandler(){
PdfPCell cell;
cell =new PdfPCell(new PdfParagraph("设备编号", 22, true));
setCell(cell, lineHeight);
//fill cell
cell =new PdfPCell(new PdfParagraph("设备名称", 22, true));
setCell(cell, lineHeight);
//create a table to fill cell
PdfPTable iTable =new PdfPTable(2);
PdfPCell iCell =new PdfPCell(new PdfParagraph("指标值", 18, true));
iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
iCell.setFixedHeight(lineHeight);
//merge column
iCell.setColspan(2);
iTable.addCell(iCell);
mergeColumn(iTable, "指标",true);
mergeColumn(iTable, "是否正常",true);
cell =new PdfPCell(iTable);
cell.setPadding(0);
tables.addCell(cell);
}
private static void writeBody() {
PdfPCell cell;
//fill cell
cell =new PdfPCell(new PdfParagraph("A", 18, false));
setCell(cell, lineHeight);
//fill cell
cell =new PdfPCell(new PdfParagraph("B", 18, false));
setCell(cell, lineHeight);
//create a table to fill cell
PdfPTable iTable =new PdfPTable(2);
for (int i = 0; i < 10; i++) {
//merge column
mergeColumn(iTable, "C"+i,false);
mergeColumn(iTable, "D"+i,false);
}
cell =new PdfPCell(iTable);
cell.setPadding(0);
tables.addCell(cell);
}
private static void mergeColumn(PdfPTable iTable, String c,boolean isBold) {
PdfPCell iCell;
iCell = new PdfPCell(new PdfParagraph(c, 16, isBold));
iCell.setHorizontalAlignment(Element.ALIGN_CENTER);
iCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
iCell.setFixedHeight(lineHeight);
iTable.addCell(iCell);
}
private static void setCell(PdfPCell cell, float height) {
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
cell.setVerticalAlignment(Element.ALIGN_MIDDLE);
cell.setPadding(0);
cell.setFixedHeight(height);
tables.addCell(cell);
}
}