0

Here i am combining 2 pdf documents using the Itext packages. Merging was done successfully using the code below

    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    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);
        }
    }

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

Here the list is an InputStream List. And outputStream is an output stream

The problem i am having is i want to append the PDFdocuments in the list after the 1st PDF is added (i.e 1st PDF has 4 lines...i want the 2nd PDF to continue in the same page after the 4th line). What i am getting is the 2nd PDF is added in the second page. Is there any alternate keyword for document.newPage();

Can anyone help me with it.

Thanks would like to hear any responses:)

Ash Win
  • 115
  • 1
  • 10
  • Add some new lines? /n – anaxin Feb 22 '16 at 07:47
  • I don't want to add a new line. I want to remove the whitespace(blank lines) – Ash Win Feb 22 '16 at 09:02
  • Oh maybe something like string = string.replaceAll("(\r?\n){5,}", "\r\n\r\n\r\n\r\n"); it will replace anything over 5 new lines with 4 new lines. – anaxin Feb 22 '16 at 09:27
  • 1
    You're asking something that is impossible in PDF (in general). You can't do this with iText, nor with any other software I know of. Read ISO 32000 if you want to know *why* it's impossible. Workarounds exist, but it would lead us too far to explain how to go about it. Such a workaround wouldn't work in a majority of PDFs (e.g. if they have a footer). – Bruno Lowagie Feb 22 '16 at 09:32
  • Taking my PDF in form of a string and using the string properties would not be the right way to do it anaxin. – Ash Win Feb 22 '16 at 10:01
  • Oops!!! Thanks for taking your time to respond Bruno. If Itext doesn't work and ISO 32000 also doesn't have any way regarding it. Then i am next to impossible now.:( – Ash Win Feb 22 '16 at 10:05

1 Answers1

0

It depends on the requirements you have. As long as

  • you only are interested in the page contents of the merged PDFs, not in the page annotations and
  • the pages have no content but the text lines you mention, in particular no background graphics, watermarks, or header/footer lines,

you can you use either the

If you are interested in annotations, it should be no problem to extend those classes accordingly. If your PDDFs have background graphics or watermarks, headers or footers, they should be removed beforehand.

Community
  • 1
  • 1
mkl
  • 90,588
  • 15
  • 125
  • 265