csv to pdf file in java
Solution 1
This is the solution @anand came up with (anand had edited it into the question for lack of understanding how SO works).
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();
}
Solution 2
set DEFAULT_SKIP_LINES to 0 in CSVReader.java
anand
Updated on June 04, 2022Comments
-
anand almost 2 years
I am trying to get a
csv
file parsed into apdf
. What I have so far is attached below.My problem is with this code the file that ends up in the pdf cuts off at the first line of the csv file and I cant figure out why. [examples attached] Essentially I would like a pdf version of the csv file nothing manipulated. I am sure its an issue with how i am adding data to the itext pdf but I cant really find another way of forwarding an array to the pdf file. Any ideas on fixing the code or something simpler?
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 file: http://dl.dropbox.com/u/11365830/data1.csv
PDF file: http://dl.dropbox.com/u/11365830/Test.pdf