0

I have an existing pdf file, and I want to add a new content to it in top of the same existing pdf page. The problem with the following code is I get a pdf file where the new content is over the old content (old content doesn't move it keeps its position & they got mixed) and the generated file is not readable. Please any idea how can I make this possible

public byte[] pdfCreation(Port port, byte[] oldPdf) throws IOException {

        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ByteArrayInputStream bais = new ByteArrayInputStream(oldPdf);
        PdfReader reader = new PdfReader(bais);
        PdfWriter writer = new PdfWriter(baos);
        PdfDocument pdfDoc = new PdfDocument(reader, writer);
        Document document = new Document(pdfDoc);


        float[] columnWidth = { 200f, 200f, 200f, 200f };
        Table table = new Table(columnWidth).setCaption(new Div().add(new Paragraph("My caption").setBold()));
        table.addCell(new Cell().add(new Paragraph("id")));
        table.addCell(new Cell().add(new Paragraph("description")));

        table.addCell(new Cell().add(new Paragraph(new StringBuilder().append(port.getId()).toString())));
        table.addCell(new Cell().add(new Paragraph(port.getDescription())));

        document.add(table);
        document.close();

        byte[] pdf = baos.toByteArray();

        return pdf;
    }
hakima maarouf
  • 1,010
  • 1
  • 9
  • 26
  • @KJ I really appreciate your help. I am a beginner with iText and java so Please have you any exemple how to implement one of those methods? I searched on the internet but I did not find something helpful – hakima maarouf Mar 24 '22 at 09:26
  • Does your original PDF have headers / backgrounds / etc. that should _not_ move while making place for your new content? – mkl Mar 24 '22 at 10:31
  • @mkl no, the whole content should move down to make space for new content (old content is not long so one page is enough for both new & old content) – hakima maarouf Mar 24 '22 at 10:41
  • 1
    Indeed, the hints from the answer @KJ linked give rise to the easiest and most faithful approach. hkmaarouf, do the hints suffice or do you need more details? – mkl Mar 25 '22 at 11:00
  • mkl finally it seems to be working .. I used page.setCropBox! Thank you so much mkl & KJ – hakima maarouf Mar 26 '22 at 18:48
  • Great. Thus, I closed your question as duplicate of that other question. – mkl Mar 27 '22 at 12:40

0 Answers0