Java中将CSV文件转换为PDF文件

4
我正在尝试将一个csv文件解析成pdf格式。我目前的代码如下所示。
我的问题是在这个代码中生成的pdf文件只包含csv文件的第一行,我无法找出原因。我希望能够得到一个与csv文件相同的pdf版本。我确定问题出在如何向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


如果你只使用第一列,你其实不需要 CSV... 这是你的标准用例吗? - Franz Ebner
1
我猜解析器是工作的,虽然我不知道它是如何工作的。但是肯定有问题的是你的迭代(while ((nextLine = reader.readNext()) != null)),这不对。重新思考你的整个代码... 你确定每一行都需要一个“new Document();”吗? - Franz Ebner
天啊,我简直不敢相信我没看到那个问题。是的,我不需要为每个迭代创建一个新文档……谢谢。而解析器确实存在,因为我不知道导入csv文件的其他方法。如果您知道更简单的方法,我会非常乐意听取!本质上,我想创建一个csv转pdf的转换器,这是我能想到的最好方式。 - anand
谢谢,这很有帮助!我最终使用了类似的代码(作为解决方案发布在上面)。 - anand
@anand 顺便说一句,如果你回来了并且想要收集你回答的潜在声望,请告诉我,我会删除我的帖子。我只是想清楚地向任何经过的人提供答案。 - djeikyb
显示剩余5条评论
2个回答

1
这是@anand想出的解决方案(由于不了解SO的工作方式,@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();
} 

1
将CSVReader.java中的DEFAULT_SKIP_LINES设置为0。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接