2016-08-08 2 views
2

Я хочу создать PDF-файл с тремя столбцами динамическими данными. Я попытался с моим этим кодом,Как заполнить динамические данные каждым столбцом по строке Использование iText в Java

public class Clazz { 

public static final String RESULT = "result.pdf"; 
private String[] data = {"1","2","3","4","5","6","7","8"}; 

private void go() throws Exception { 

    Document doc = new Document(); 
    PdfWriter.getInstance(doc, new FileOutputStream(RESULT)); 
    doc.open(); 

    PdfPTable mainTable = new PdfPTable(3); 
    PdfPCell cell; 

    for (int i = 0; i < data.length; i+=2) { 
     cell = new PdfPCell(new Phrase(data[i])); 
     PdfPTable table = new PdfPTable(1); 
     table.addCell(cell); 
     if (i+1 <= data.length -1) { 
      cell = new PdfPCell(new Phrase(data[i + 1])); 
      table.addCell(cell); 
     } else { 
      cell = new PdfPCell(new Phrase("")); 
      table.addCell(cell); 
     } 
     mainTable.addCell(table); 
    } 

    doc.add(mainTable); 
    doc.close(); 

} 
} 

Я хочу напечатать, как это в моем PDF:

На первой странице будет печататься 1 2 3, а затем на следующей странице он будет печатать 4 5 6, а затем на следующей странице будет напечатано 7 8 и пустая ячейка.

+0

возможно дубликат: HTTP: // StackOverflow .com/questions/37526223/fill-the-dynamic-data-with-each-row-columns-by-column-use-itext-in-java – LychmanIT

+0

Можете ли вы прояснить, что вы пытаетесь сделать и что вы пробовал? – EJoshuaS

+0

Я хочу напечатать вот так в моем pdf: На первой странице он напечатает 1 2 3, а затем на следующей странице он напечатает 4 5 6, а затем на следующей странице напечатает 7 8 и пустую ячейку. –

ответ

0

Для того, чтобы перейти на следующую страницу, вы должны использовать NEWPAGE() метод из документа класса. Вы можете увидеть пример newPage here.

Это возможное решение. Это, безусловно, может быть улучшено, это просто то, что вы делаете:

private static void go() throws Exception { 
    Document doc = new Document(); 
    PdfWriter.getInstance(doc, new FileOutputStream(RESULT)); 
    doc.open(); 

    PdfPTable mainTable = new PdfPTable(3); 
    PdfPCell cell; 

    //went to <= data.length to cover the case of empty cell after 7,8 
    //a better approach could be more suitable here 
    for (int i = 0; i <= data.length; i++) { 
     PdfPTable table = new PdfPTable(1); 
     if (i < data.length) { 
      cell = new PdfPCell(new Phrase(data[i])); 
      table.addCell(cell); 
     } else { 
      cell = new PdfPCell(new Phrase("")); 
      table.addCell(cell); 
     } 

     //go to next page after completing each row 
     if(i != 0 && i%3 == 0) 
     { 
      doc.add(mainTable); 
      doc.newPage(); 
      mainTable = new PdfPTable(3); 
     } 

     mainTable.addCell(table); 
    } 

    doc.add(mainTable); 
    doc.close(); 
} 
0

С чисто академической точки зрения, вот код. Оптимизирован ли он, нет. Я только что 3 вещи а) Нужна таблица с 3 столбцами б) Нуждается разрыв страницы после каждой строки с) Пустые ячейки должны быть заполнены «»

import java.io.FileOutputStream; 
import java.io.IOException; 

import com.itextpdf.text.Document; 
import com.itextpdf.text.DocumentException; 
import com.itextpdf.text.Phrase; 
import com.itextpdf.text.pdf.PdfPCell; 
import com.itextpdf.text.pdf.PdfPTable; 
import com.itextpdf.text.pdf.PdfWriter; 

public class CreateTable { 

    /** The resulting PDF file. */ 
    public static final String RESULT = "first_table.pdf"; 

    /** 
    * Main method. 
    * 
    * @param args 
    *   no arguments needed 
    * @throws DocumentException 
    * @throws IOException 
    */ 
    public static void main(String[] args) throws IOException, DocumentException { 
     new CreateTable().createPdf(RESULT); 
    } 

    /** 
    * Creates a PDF with information about the movies 
    * 
    * @param filename 
    *   the name of the PDF file that will be created. 
    * @throws DocumentException 
    * @throws IOException 
    */ 
    public void createPdf(String filename) throws IOException, DocumentException { 
     // step 1 
     Document document = new Document(); 
     // step 2 
     PdfWriter.getInstance(document, new FileOutputStream(filename)); 
     // step 3 
     document.open(); 
     // step 4 
     createCustomTables(document); 
     // step 5 
     document.close(); 
    } 

    public static void createCustomTables(Document document) throws DocumentException { 
     String[] data = { "1", "2", "3", "4", "5", "6", "7", "8" }; 
     PdfPTable table = null; 
     int arrayLength = data.length; 
     int mod3 = data.length % 3; 
     int iterCounter = (mod3 == 0) ? arrayLength : arrayLength + (3 - mod3); 

     System.out.println(iterCounter); 

     for (int i = 0; i <= iterCounter; i++) { 
      String string = (arrayLength > i) ? data[i] : ""; 
      if (i % 3 == 0) { 
       table = new PdfPTable(3); 
       document.newPage(); 
      } 
      PdfPCell cell = new PdfPCell(new Phrase(string)); 
      table.addCell(cell); 
      document.add(table); 
     } 
     return; 
    } 
} 
Смежные вопросы