我正在尝试将csv
文件解析为pdf
。我到目前为止所附的内容如下。
我的问题是这个代码在pdf中结束的文件切断了csv文件的第一行,我无法弄清楚原因。 [附带的例子]基本上我想要一个没有被操纵的cfv文件的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
答案 0 :(得分:1)
在CSVReader.java中将DEFAULT_SKIP_LINES设置为0
答案 1 :(得分:0)
这是@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();
}