简体   繁体   中英

Stamping the first page of portfolio pdf using itext

I have been working on an module where it requires the first page of all the PDF's be stamped using itext. Although the code is working fine for the normal PDF's when i try the same logic for portfolio pdfs .Below is the code snippet for the same:

    try {

        PdfReader reader = new PdfReader("D:\\Test\\test.pdf");
        System.out.println(reader.getNumberOfPages());

        PdfStamper stamper = new PdfStamper(reader,new FileOutputStream("D:\\Test\\test_stamped.pdf"));



        PdfContentByte canvas = stamper.getOverContent(i);

        PdfDictionary root = reader.getCatalog();

        canvas.beginText();
        BaseFont baseFont = BaseFont.createFont(BaseFont.HELVETICA_BOLD, "ASCII", false);
        canvas.setFontAndSize(baseFont, 14);
        canvas.setRGBColorFill(255, 0, 0);
        canvas.showTextAligned(PdfContentByte.ALIGN_CENTER, "Test Stamping-Pg"+i, 30, 1, 0);
        canvas.endText();

        stamper.setFormFlattening(true);
        stamper.close();
        reader.close();
        System.out.println("Stamping complete..");

    } catch (Throwable t) {

        t.printStackTrace();
    }

It would be very helpful if anyone could help me for it.

According to the PDF specification ISO 32000-1 (in which "portfolios" are called "portable collections"),

When a conforming reader first opens a PDF document containing a collection, it shall display the contents of the initial document, along with a list of the documents present in the EmbeddedFiles name tree. The document list shall include the additional document information specified by the collection schema. The initial document may be the container PDF or one of the embedded documents.

NOTE 2 The page content in the initial document should contain information that helps the user understand what is contained in the collection, such as a title and an introductory paragraph.

Thus, in case the initial document is not the container document but a contained one, you have extract that contained document, manipulate it, and replace its original version with your manipulated version in the collection.

You can check whether the initial document is not the container document but a contained one by inspecting the collection dictionary:

Table 155 – Entries in a collection dictionary

D byte string (Optional) A string that identifies an entry in the EmbeddedFiles name tree, determining the document that shall be initially presented in the user interface. If the D entry is missing or in error, the initial document shall be the one that contains the collection dictionary.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM