简体   繁体   中英

iText merge a stamped pdf with a pdf created at runtime

I want to merge 2 pdf documents using iText in java, one of the pdfs is created at runtime while the other is an existing pdf that I read in and using the PdfStamper function stamp an image onto it. I want to then merge these two pdfs and display them using a servlet.

I want to know if this is possible and how to do it.

I have no problem creating or stamping them separately but I just can't seem to figure out how to merge them.

Thanks

I suppose this code can help you. You would have to import IText.Jar for this

    public static void doMerge(List<InputStream> list,
                           OutputStream outputStream) throws DocumentException,
                                                             IOException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    float k = 0;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            //                document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
            System.out.println(page.getHeight());
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

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