iText生成PDF
Posted yang21
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了iText生成PDF相关的知识,希望对你有一定的参考价值。
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 ", 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的主要内容,如果未能解决你的问题,请参考以下文章