PDF with several paragraphs from Java Itext

I have an array of strings as follows: -

String[] data = {"Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"}.

Now I want to write these data lines to a pdf file under another, for example: -

  1. Sunday
  2. Monday
  3. Tuesday
  4. Wednesday
  5. Thursday
  6. Friday
  7. Saturday.

I use itext to achieve this. Below is the code snippet that I am using

for(int i= 0; i< data.length;i++)

{

Document document=new Document();
PdfWriter.getInstance(document, new FileOutputStream(directory));
document.open();
document.add(new Paragraph(data[i]));
document.add(Chunk.NEWLINE);
document.close();
}

Problem: -

The pdf file I get has only: -

  1. saturday.

Please, help.

+4
source share
2 answers

The problem is that you are creating a document in a loop. Try the following:

Document document=new Document();
PdfWriter.getInstance(document, new FileOutputStream(directory));
document.open();
for(int i= 0; i< data.length;i++)
{
  document.add(new Paragraph(data[i]));
  document.add(Chunk.NEWLINE);
}
document.close();

You might want to handle closing a thread in case something happens. With Java 7 or higher, you can achieve this:

Document document=new Document();
try (FileOutputStream fos = new FileOutputStream(directory)) {
  PdfWriter.getInstance(document, fos);
  document.open();
  for(int i= 0; i< data.length;i++)
  {
    document.add(new Paragraph(data[i]));
    document.add(Chunk.NEWLINE);
  }
  //EDIT start
  document.close();
  //EDIT end
}
+4
source

You create a document in a loop, and also close it.

, .

try
{
   Document document=new Document();
   PdfWriter.getInstance(document, new FileOutputStream(directory));
   document.open();
   for(int i= 0; i< data.length;i++)
   {
      document.add(new Paragraph(data[i]));
      document.add(Chunk.NEWLINE);    
   }
 }
finally{

document.close();
}
0

Source: https://habr.com/ru/post/1569227/


All Articles