2017-09-17 60 views
0

我正在研究java中的小项目,我想从数据库中获取内容并将它们写入PDF文件。使用iText库根据给定格式创建PDF

我试着用Google搜索并想出了iText Library

任何人都可以引导建立一个PDF,看起来像封闭的图像computer generated invoice

PS:我是很新,JAVA.and这是我的第一个Java项目。

+1

这个问题对于堆栈溢出来说太宽泛了。首先阅读[文档](https://developers.itextpdf.com/content/itext-7-converting-html-pdf-pdfhtml/chapter-4-creating-reports-using-pdfhtml)(如果向下滚动,你会看到一个发票的例子)。开始编码,并在出现*特定技术问题*时返回到堆栈溢出。堆栈溢出不是“为我工作”的平台,也不是一个学习平台。 –

+1

当然,还有一本专门用iText制作发票的书:https://developers.itextpdf.com/content/zugferd-future-invoicing –

+0

@BrunoLowagie感谢您的反馈:)我只是寻找初学者参考.. –

回答

2

我已经完成了大部分用例的快速实现。

以下是代码:
首先我们定义一个小类,作为发票中的单个记录。

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; 
    } 
} 

然后,我为发票中的每个大块创建了一个方法。
的标题开始:

public static void addTitle(Document layoutDocument) 
{ 
    layoutDocument.add(new Paragraph("RETAIL INVOICE").setBold().setUnderline().setTextAlignment(TextAlignment.CENTER)); 
} 

然后添加文本的小段落的标题下:

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)); 
} 

,然后添加一个表:

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); 
} 

主要方法,然后看起来像这样:

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(); 
}