2012-07-25 124 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(); 
}