Search code examples
itextitext7

How to replace text of Paragraph in Itext?


I want to set page number when I merge pdf files. The page number paragraph will defind by someone to custom style what he want. Now I can add text to the paragraph(like doc.add(paragraph.add(text))), but I can not replace it.

    public static byte[] mergePdf(Map<String, PdfDocument> filesToMerge, Paragraph paragraph) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(baos));
        Document doc = new Document(pdfDoc);

        pdfDoc.initializeOutlines();
        PdfPageFormCopier formCopier = new PdfPageFormCopier();

        int page = 1;
        for (Map.Entry<String, PdfDocument> entry : filesToMerge.entrySet()) {
            String title = entry.getKey();
            PdfDocument srcDoc = entry.getValue();
            int numberOfPages = srcDoc.getNumberOfPages();

            for (int i = 1; i <= numberOfPages; i++, page++) {
                Text text = new Text(String.format("page %d", page));
                srcDoc.copyPagesTo(i, i, pdfDoc, formCopier);

                if (i == 1) {
                    text.setDestination("p" + page);

                    PdfOutline rootOutLine = pdfDoc.getOutlines(false);
                    PdfOutline outline = rootOutLine.addOutline(title);
                    outline.addDestination(PdfDestination.makeDestination(new PdfString("p" + page)));
                }

                // I want do like "doc.add(paragraph.set(text))";
                // paragraph already have been set position,font,fontSize and so on. SO I dont want to "new Paragraph(text)"
                doc.add(paragraph.add(text));
            }
        }

        for (PdfDocument srcDoc : filesToMerge.values()) {
            srcDoc.close();
        }
        doc.close();
        return baos.toByteArray();
    }

Solution

  • I am the questioner. At last I resolve the question do like this:

    public class MyParagraph extends Paragraph {
    
        public MyParagraph() {
        }
    
        public void setContent(Text text) {
            List<IElement> children = this.getChildren();
            if (!children.isEmpty()) {
                children.clear();
            }
            children.add(text);
        }
    }