0
votes

I'm getting the exception described in the title when I'm trying to print a few documents continuously.

The first one was printed but for second process doc.close() thrown exception.

1.print methods.

private void print1(Cell header, Table table, Cell footer, int size) throws Exception {
    byte[] bytes = somePrintService.getByteArray(header, table, footer, size);
    somePrintService.printbytes(bytes);
}

private void print2(Cell header, Table table, Cell footer, int size) throws Exception {
    byte[] bytes = somePrintService.getByteArray(header, table, footer, size);
    somePrintService.printbytes(bytes);
}

2.getByteArray method in somePrintService

public byte[] getByteArray(Cell header, Table table, Cell footer, int height) {


    ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

    PdfWriter writer = new PdfWriter(outputStream);

    PdfDocument pdf = new PdfDocument(writer);
    Rectangle rectangle = new Rectangle(135f, height);
    PageSize pageSize = new PageSize(rectangle);
    pdf.setDefaultPageSize(pageSize);

    Document doc = new Document(pdf);
    doc.setMargins(0, 0, 0, 0);


    doc.add(header);
    doc.add(table);
    doc.add(footer);


    doc.close(); ------- Exception thrown here!!!

    return outputStream.toByteArray();
}

3.Itext kernel code which thrown exception

private void write(PdfIndirectReference indirectReference) {
    if (document != null && !indirectReference.getDocument().equals(document)) {
        throw new PdfException(PdfException.PdfIndirectObjectBelongsToOtherPdfDocument);
    }
    ...
}

PS1. I am using Spring services for creating tables, fonts e.t.c.

PS2. Itext version - 7.1.10

Thank you.

1
Actually the error message says it all, you add the same iText document content objects to different pdf documents (each getByteArray creates a new document). This can cause issues, so it is forbidden. Generate separate sets of iText document content objects for different target documents. That been said, you directly add cells to a document. This probably will cause issues as cells are meant to be added to tables. - mkl
...you add the same iText document content objects to different pdf documents - do you mean table, header and footer? Tables are different for each method, footer and header are the same. - AnySmallEmpsilon
@mkl Thank you, problem is solved. - AnySmallEmpsilon

1 Answers

2
votes

The problem is solved. For each document must be generated separate sets of iText objects (Cell, Paragraph, Table ... ).