Sasan
Sasan

Reputation: 141

Delete pdf pages in java with iTextpdf

I have an existing function to show pdf files that I can't change.

The input of function is an InputStream variable. In the past they used to pass a pdf file to it and it shows it.

But right now they asked me to show only first 30 pages of the pdf. So I am using iTextpdf and I do something like this:

PdfReader reader = new PdfReader (inputStream);
reader.selectPages("1-30");

Now I should send the result as InputStream variable to show method.

How I should do it? Thanks

Upvotes: 0

Views: 386

Answers (2)

Vishwa Ratna
Vishwa Ratna

Reputation: 6420

Get the reader of existing pdf file by

PdfReader pdfReader = new PdfReader("source pdf file path");

Now update the reader by

 reader.selectPages("1-5,15-20");

then get the pdf stamper object to write the changes into a file by

PdfStamper pdfStamper = new PdfStamper(pdfReader,
                new FileOutputStream("destination pdf file path"));

close the PdfStamper by

pdfStamper.close();

It will close the PdfReader too.

Upvotes: 0

mkl
mkl

Reputation: 96064

You can store the result using a PdfStamper like this:

PdfReader reader = new PdfReader (inputStream);
reader.selectPages("1-30");
ByteArrayOutputStream os = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, os);
stamper.close();
byte[] changedPdf = os.toByteArray();

If you want the result again to be in the InputStream inputStream variable, simply add a line

inputStream = new ByteArrayInputStream(changedPdf);

Upvotes: 2

Related Questions