Ash*_*coN 3 java pdf itext file-management
我正在研究java中的小项目,在那里我想从数据库中获取内容并将它们写入PDF文件.
我试图谷歌搜索并提出了iText库.
PS:我对JAVA很新.这是我的第一个java项目.
我已经完成了大部分用例的快速实现.
这是代码:
首先,我们定义一个小类,作为发票中的单个记录.
static class Article{
int SNO;
String description;
int quantity;
double unitPrice;
public Article(int SNO, String description, int quantity, double unitPrice)
{
this.SNO = SNO;
this.description = description;
this.quantity = quantity;
this.unitPrice = unitPrice;
}
}
Run Code Online (Sandbox Code Playgroud)
然后我为发票中的每个大块创建了一个方法.
从标题开始:
public static void addTitle(Document layoutDocument)
{
layoutDocument.add(new Paragraph("RETAIL INVOICE").setBold().setUnderline().setTextAlignment(TextAlignment.CENTER));
}
Run Code Online (Sandbox Code Playgroud)
然后添加标题下方的一小段文字:
public static void addCustomerReference(Document layoutDocument)
{
layoutDocument.add(new Paragraph("M/s Indian Convent School").setTextAlignment(TextAlignment.LEFT).setMultipliedLeading(0.2f));
layoutDocument.add(new Paragraph("y Pocket-3, Sector-24, Rohini Delhi-110085").setMultipliedLeading(.2f));
layoutDocument.add(new Paragraph("b 011-64660271").setMultipliedLeading(.2f));
}
Run Code Online (Sandbox Code Playgroud)
然后添加一个表:
public void addTable(Document layoutDocument, List<Article> articleList)
{
Table table = new Table(UnitValue.createPointArray(new float[]{60f, 180f, 50f, 80f, 110f}));
// headers
table.addCell(new Paragraph("S.N.O.").setBold());
table.addCell(new Paragraph("PARTICULARS").setBold());
table.addCell(new Paragraph("QTY").setBold());
table.addCell(new Paragraph("RATE").setBold());
table.addCell(new Paragraph("AMOUNT IN RS.").setBold());
// items
for(Article a : articleList)
{
table.addCell(new Paragraph(a.SNO+""));
table.addCell(new Paragraph(a.description));
table.addCell(new Paragraph(a.quantity+""));
table.addCell(new Paragraph(a.unitPrice+""));
table.addCell(new Paragraph((a.quantity * a.unitPrice)+""));
}
layoutDocument.add(table);
}
Run Code Online (Sandbox Code Playgroud)
然后主要方法如下所示:
public static void main(String[] args) throws FileNotFoundException {
PdfDocument pdfDocument = new PdfDocument(new PdfWriter("MyFirstInvoice.pdf"));
Document layoutDocument = new Document(pdfDocument);
// title
addTitle(layoutDocument);
// customer reference information
addCustomerReference(layoutDocument);
addTable(layoutDocument, Arrays.asList(
new Article(1, "Envelopes",2000, 1.70),
new Article(2, "Voucher Book", 50, 41)));
// articles
layoutDocument.close();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4907 次 |
| 最近记录: |