1. 程式人生 > >iText生成PDF

iText生成PDF

div ddc \n before 年齡 iter file except output

Document document = null;
PdfWriter writer = null;
try{
    // A4橫向
    document = new Document(new Rectangle(842.0F, 595.0F), 20F, 20F, 50F, 50F);
    writer = PdfWriter.getInstance(document, new FileOutputStream(...));
    document.open();
    
    // 解決不支持中文的問題
    BaseFont baseFont = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    
    
// 字體 // 標題:粗體、黑色、大小21 Font titleFont = new Font(baseFont, 21F, Font.BOLD, BaseColor.BLACK); // 正文字體 Font contentFont = new Font(baseFont, 16F); // 字體:下劃線 Font titleFont = new Font(baseFont, 16F, Font.UNDERLINE); // 短句,document.add(..)不換行 Phrase phrase; // 段落:document.add(..)換行
Paragraph paragraph; // 標題 paragraph = new Paragraph("YangNing", titleFont); paragraph.setLeading(30F); paragraph.setsetAlignment(Element.ALIGN_CENTER); document.add(paragraph); // 第一段 phrase = new Phrase("文字A", contentFont); phrase .setLeading(30F); document.add(phrase); phrase
= new Phrase("文字B\r\n", contentFont); phrase .setLeading(30F); document.add(phrase); // 第二段 paragraph = new Paragraph("xxxx", contentFont); paragraph.setLeading(30F); document.add(paragraph); // 增加表格 document.add(createTable(baseFont)); } catch (Exception e){ // handle exception } finally { if(document != null){ document.close; } if(writer != null){ writer.close; } }
private PdfPTable createTable(BaseFont baseFont){
    Font tableFont = new Font(baseFont, 9F);
    // 兩列
    PdfPTable table = new PdfPTable(2)
    table.setWidthPercentage(100F);
    table.setSpacingBefore(10F);
    table.setSpacingAfter(10F);
    table.serWidths(new float[]{4F, 5F});

    PdfPCell child;

    child = new PdfPCell(new Phrase("姓名", tableFont));
    child.setMinimunHeight(30F)
    child.setHorizontalAlignment(Element.ALIGN_CERTER);
    child.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(child);

    child = new PdfPCell(new Phrase("年齡", tableFont));
    child.setMinimunHeight(30F)
    child.setHorizontalAlignment(Element.ALIGN_CERTER);
    child.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(child);

    child = new PdfPCell(new Phrase("yangxuyue", tableFont));
    child.setMinimunHeight(30F)
    child.setHorizontalAlignment(Element.ALIGN_CERTER);
    child.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(child);

    child = new PdfPCell(new Phrase("24", tableFont));
    child.setMinimunHeight(30F)
    child.setHorizontalAlignment(Element.ALIGN_CERTER);
    child.setVerticalAlignment(Element.ALIGN_MIDDLE);
    table.addCell(child);

    return table;
}

iText生成PDF