AnySmallEmpsilon
AnySmallEmpsilon

Reputation: 31

Itext 7 PdfException - "com.itextpdf.kernel.PdfException: Pdf indirect object belongs to other PDF document. Copy object to current pdf document."

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.

Upvotes: 0

Views: 1827

Answers (1)

AnySmallEmpsilon
AnySmallEmpsilon

Reputation: 31

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

Upvotes: 3

Related Questions