Skip to content
Advertisement

Add multiple attachments in a pdf using itext pdf stamper

I want to add multiple attachments to a pdf file. When I go into the loop it only attaches the last attachment.

sample code

PdfReader reader = new PdfReader(FILE);

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(realPath+"/Temp/"+sosValues.getCmaId()+".pdf"));

for(SOSCustomerOrderFile cmaOrder:orderList)
{
    PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(stamper.getWriter(), null, cmaOrder.getFileName(), cmaOrder.getFileData());
    /*  stamper.getWriter(), null, "test.txt", "Some test".getBytes());*/
    stamper.addFileAttachment("Attachment", fs);
}
stamper.close();

Advertisement

Answer

You have adapted the existing example AddEmbeddedFile to add more than one attachment, and you claim that only one attachment is added.

I can not reproduce this. I have also adapted the existing example by creating a new example: AddEmbeddedFiles

public static final String[] ATTACHMENTS = {
    "hello", "world", "what", "is", "up"
};
public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    for (String s : ATTACHMENTS) {
        PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
            stamper.getWriter(), null, String.format("%%s.txt", s),
            String.format("Some test: %%s", s).getBytes());
        stamper.addFileAttachment(String.format("Content: %%s", s), fs);
    }
    stamper.close();
}

The result contains all the expected attachments:

enter image description here

The only difference that I see, is that you give every embedded file the same name, but even if I do that, I can still see all the attachments correctly.

Another difference, is that I use an array of String values, but that shouldn’t really matter, assuming that cmaOrder.getFileName() indeed returns a file name (e.g. “order1.doc”, “order2.xls”,…) and that cmaOrder.getFileData() returns a byte[] with the actual bytes of that file. By not telling us what the SOSCustomerOrderFile class is about, you are forcing us to make that assumption.

If you have the file on disk, you could also do something like this:

PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
    stamper.getWriter(), cmaOrder.getFilePath(), cmaOrder.getFileName(), null);

That is: if the SOSCustomerOrderFile class has a getFilePath() method that returns the path to the file. We don’t know that, we don’t have access (nor do we want access) to your complete code base. We can only create an SSCCE in order to try to reproduce the problem, and our SSCCE tells us that your allegation is wrong. You can prove that you’re right by adapting our SSCCE in such a way that we can run it on our machines and reproduce the problem.

User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement