2

I'm trying to add a dynamically created table to a dynamically created existing PDF. I want to "append" the table to a specific position on the last page of the existing PDF.

My current code is based on the answer given by Uladzimir Asipchuk on this thread, it goes like this:

public byte[] completePDF(byte[] originalPDF){

    ByteArrayInputStream is = new ByteArrayInputStream(originalPDF);
    ByteArrayOutputStream os = new ByteArrayOutputStream();

    PdfDocument pdfDoc;
    try {
        pdfDoc = new PdfDocument(new PdfReader(is), new PdfWriter(os));
        final Document doc = new Document(pdfDoc);
         //FAKE TABLE TO TEST
        Table table = new Table(UnitValue.createPercentArray(new float[] {10f,90f}));

        for (int i = 0; i<150; i++){

            table.addCell(new String(new Integer(i).toString()));
            table.addCell("FAKE DATA");
        }

        doc.setRenderer(new DocumentRenderer(doc) {
            @Override
            protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {

                int lastPage = doc.getPdfDocument().getNumberOfPages();

                LayoutArea area = super.updateCurrentArea(overflowResult);

                if (area.getPageNumber() == lastPage) {
                    PdfDocumentContentParser parser = new PdfDocumentContentParser(doc.getPdfDocument());
                    TextMarginFinder finder = parser.processContent(lastPage, new TextMarginFinder());
                    area.getBBox().decreaseHeight(finder.getTextRectangle().getHeight() + 30);
                }
                return area;
            }
        });

        doc.add(table);

        doc.close();
    } catch (Exception e) {
        return null;
    }

    return os.toByteArray();

}

This code does almost what I want, (new pages are added based on the table size, and the table position on the last page starts after the text of that page), but I don't know of to force the table to start getting drawn on the last page.

Is is possible? Any help would be greatly appreciated.

Thanks!

CarlosG
  • 51
  • 9
  • Please move the solution from your question into an actual answer which you can eventually accept. This causes your question to appear as answered. – mkl May 04 '18 at 16:00

1 Answers1

3

Found the solution by myself, I was really close to it. I'll post it just in case someone has the same problem:

if (area.getPageNumber() == lastPage) {
    PdfDocumentContentParser parser = new PdfDocumentContentParser(doc.getPdfDocument());
    TextMarginFinder finder = parser.processContent(lastPage, new TextMarginFinder());
    area.getBBox().decreaseHeight(finder.getTextRectangle().getHeight() + 30);
} else if (area.getPageNumber() < lastPage){
    area.getBBox().decreaseHeight(doc.getPdfDocument().getDefaultPageSize().getHeight());
}
return area;

This way the table gets "appended" just after the end of the text of the last page of the PDF.

CarlosG
  • 51
  • 9