2012-07-25 118 views
4

我想獲得一個csv文件解析到pdf。到目前爲止,我已經在下面附上。csv到PDF文件在java

我的問題是,這個代碼中的文件,結束在pdf切斷在csv文件的第一行,我不知道爲什麼。 [附帶的示例]基本上,我希望PDF版本的csv文件不受任何操作。我相信它是如何將數據添加到itext pdf的問題,但我真的找不到將數組轉發到pdf文件的另一種方式。任何關於修復代碼或更簡單的想法?

public static void main(String[] args) throws IOException, DocumentException { 
    @SuppressWarnings("resource") 
    CSVReader reader = new CSVReader(new FileReader("data1.csv") ,'\''); 
    String [] nextLine; 
    while ((nextLine = reader.readNext()) != null) { 
      // nextLine[] is an array of values from the line 
      System.out.println(nextLine[0]); 
      String test; 
      test = nextLine[0]; 

      // step 1 
      Document document = new Document(); 

      // step 2 
      PdfWriter.getInstance(document, new FileOutputStream("Test.pdf")); 

      // step 3 
      document.open(); 

      // step 4 
      PdfPTable arrayTable3 = new PdfPTable(1); 
      arrayTable3.setHorizontalAlignment(Element.ALIGN_LEFT); 

      Phrase phrase1 = new Phrase(nextLine[0]); 
      PdfPCell arrayDetailsCell3 = new PdfPCell(); 

      arrayDetailsCell3.addElement(phrase1); 

      // Add the cell to the table 
      arrayTable3.addCell(arrayDetailsCell3); 

      // Add table to the document 
      document.add(arrayTable3); 

      // step 5 
      document.close(); 
    } 
} 

CSV文件:http://dl.dropbox.com/u/11365830/data1.csv
PDF文件:http://dl.dropbox.com/u/11365830/Test.pdf

+0

如果你只使用你並不真正需要的csv ...第一列 - 是你的STD用例? – 2012-07-25 19:46:46

+0

嗨,弗蘭克,如果我可以從單個coloumns中獲取行,那將會很好,但不幸的是,如果我試圖僅顯示其他列中的數據,csv解析器會一直給我提供錯誤。像例如,如果我有以下代碼:System.out.println(nextLine [0] + nextLine [1]);我會得到一個界限錯誤。我誤解了解析器的功能嗎? csv是轉換器的輸出,我試圖將其轉換爲pdf格式。 – anand 2012-07-25 21:29:48

+1

我猜解析器可以工作,雖然我不知道它。但是,你的迭代肯定是錯誤的(while((nextLine = reader.readNext())!= null))這是不正確的。 「爲每一行? – 2012-07-26 06:07:44

回答

0

這是@anand想出了一個解決方案(阿南德已經剪輯成問題缺乏理解爲什麼會這樣運作)。

public void createPdf(String filename) throws DocumentException, IOException { 
    // step 1 
    Document document = new Document(); 

    // step 2 
    PdfWriter.getInstance(document, new FileOutputStream(filename)); 

    // step 3 
    document.open(); 

    // step 4 
    @SuppressWarnings("resource") 
    CSVReader reader = new CSVReader(new FileReader("testing.csv") ,'\''); 
    List< String[]> myEntries = reader.readAll(); 
    for (int i = 31; i < myEntries.size(); i++) { 
     String[] strings = myEntries.get(i); 
     for (int j = 0; j < strings.length; j++) { 
      document.add(new Paragraph(strings[j] + "\n")); 
     } 
    } 

    // step 5 
    document.close(); 
    reader.close(); 
}