Spring, iText - создайте PDF из множества объектов - PullRequest
0 голосов
/ 07 мая 2019

У меня 9 разных сущностей с разным количеством полей Я пытаюсь создать PDF-файл из всех них. Я нашел это решение для создания PDF:

public class PDFGenerator {

  private static Logger logger = LoggerFactory.getLogger(PDFGenerator.class);

  public static ByteArrayInputStream customerPDFReport(List<Customer> customers) {
    Document document = new Document();
        ByteArrayOutputStream out = new ByteArrayOutputStream();

        try {

          PdfWriter.getInstance(document, out);
            document.open();

            // Add Text to PDF file ->
          Font font = FontFactory.getFont(FontFactory.COURIER, 14, BaseColor.BLACK);
          Paragraph para = new Paragraph( "Customer Table", font);
          para.setAlignment(Element.ALIGN_CENTER);
          document.add(para);
          document.add(Chunk.NEWLINE);

          PdfPTable table = new PdfPTable(3);
          // Add PDF Table Header ->
            Stream.of("ID", "First Name", "Last Name")
              .forEach(headerTitle -> {
                  PdfPCell header = new PdfPCell();
                  Font headFont = FontFactory.getFont(FontFactory.HELVETICA_BOLD);
                  header.setBackgroundColor(BaseColor.LIGHT_GRAY);
                  header.setHorizontalAlignment(Element.ALIGN_CENTER);
                  header.setBorderWidth(2);
                  header.setPhrase(new Phrase(headerTitle, headFont));
                  table.addCell(header);
              });

            for (Customer customer : customers) {
              PdfPCell idCell = new PdfPCell(new Phrase(customer.getId().toString()));
              idCell.setPaddingLeft(4);
              idCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
              idCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(idCell);

                PdfPCell firstNameCell = new PdfPCell(new Phrase(customer.getFirstName()));
                firstNameCell.setPaddingLeft(4);
                firstNameCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                firstNameCell.setHorizontalAlignment(Element.ALIGN_LEFT);
                table.addCell(firstNameCell);

                PdfPCell lastNameCell = new PdfPCell(new Phrase(String.valueOf(customer.getLastName())));
                lastNameCell.setVerticalAlignment(Element.ALIGN_MIDDLE);
                lastNameCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                lastNameCell.setPaddingRight(4);
                table.addCell(lastNameCell);
            }
            document.add(table);

            document.close();
        }catch(DocumentException e) {
          logger.error(e.toString());
        }

    return new ByteArrayInputStream(out.toByteArray());
  }
}

В этом решении используются Stream.of("ID", "First Name", "Last Name") и customer.getId().toString(), но я не знаю, для какой сущности пользователь хочет создать PDF, поэтому я не могу использовать методы get.

Мне нужно что-то вроде AbstractPDFGenerator, который будет создавать PDF для любого числа полей сущностей и заполнять их без получателей.

Какой лучший способ создания PDF для нескольких объектов?

1 Ответ

1 голос
/ 07 мая 2019

Сделайте что-то подобное .... количество столбцов зависит от того, сколько строк в вашем списке.Входные данные представляют собой список, состоящий из множества списков строк.Внешний список содержит каждую строку, внутренний список содержит каждое значение в строке

public static void main( String[] args ) throws IOException {
    List<List<String>> rows = new ArrayList<>();

    List<String> headerRow = Arrays.asList( "ID", "First Name", "Last Name" );
    List<String> firstRow = Arrays.asList( "1", "Jon", "Snow" );
    List<String> secondRow = Arrays.asList( "2", "Mr", "Person" );

    rows.add( headerRow );
    rows.add( firstRow );
    rows.add( secondRow );

    File file = new File( "pathhhh" );
    file.getParentFile().mkdirs();

    ByteArrayInputStream bais = new ByteArrayInputStream( customerPDFReport( rows ) );
    StreamUtils.copy( bais, new FileOutputStream( file ) );
}

public static byte[] customerPDFReport( List<List<String>> rows ) {
    Document document = new Document();
    ByteArrayOutputStream out = new ByteArrayOutputStream();

    try {

        PdfWriter.getInstance( document, out );
        document.open();

        // Add Text to PDF file ->
        Font font = FontFactory.getFont( FontFactory.COURIER, 14, BaseColor.BLACK );
        Paragraph para = new Paragraph( "Customer Table", font );
        para.setAlignment( Element.ALIGN_CENTER );
        document.add( para );
        document.add( Chunk.NEWLINE );

        PdfPTable table = new PdfPTable( rows.get( 0 ).size() );
        List<String> headerRow = rows.remove( 0 ); // remove header

        for ( String value : headerRow ) {

            PdfPCell header = new PdfPCell();
            Font headFont = FontFactory.getFont( FontFactory.HELVETICA_BOLD );
            header.setBackgroundColor( BaseColor.LIGHT_GRAY );
            header.setHorizontalAlignment( Element.ALIGN_CENTER );
            header.setBorderWidth( 2 );
            header.setPhrase( new Phrase( value, headFont ) );
            table.addCell( header );

        }

        for ( List<String> wholeRow : rows ) {
            for ( String value : wholeRow ) {
                PdfPCell idCell = new PdfPCell( new Phrase( value ) );
                idCell.setPaddingLeft( 4 );
                idCell.setVerticalAlignment( Element.ALIGN_MIDDLE );
                idCell.setHorizontalAlignment( Element.ALIGN_CENTER );
                table.addCell( idCell );
            }
        }

        document.add( table );

        document.close();
    } catch ( DocumentException e ) {

    }

    return out.toByteArray();
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...