2017-09-17 65 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(); 
}