I have to display a PDF document in a JSP page. The PDF document has 25 pages, but I want to display only 10 pag开发者_StackOverflow社区es of the PDF file. How can I achieve this with help of iText?
Assuming you have the PDF file already.
You can use PdfStamper
and PdfCopy
to slice the PDF up:
PdfReader reader = new PdfReader("THE PDF SOURCE");
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
Document document = new Document();
PdfCopy copy = new PdfCopy(document, outputStream);
document.open();
PdfStamper stamper = new PdfStamper(reader, outputStream);
for (int i = 1; i < reader.getNumberOfPages(); i++) {
// Select what pages you need here
PdfImportedPage importedPage = stamper.getImportedPage(reader, i);
copy.addPage(importedPage);
}
copy.freeReader(reader);
outputStream.flush();
document.close();
// Now you can send the byte array to your user
// set content type to application/pdf
As for sending the pdf to display, it depends on the way you display it. The outputstream will at the end of the supplied code contain the pages you copy in the loop, in the example it is all of the pages.
This essentially is a new PDF file, but in memory. If it is the same 10 pages of the same file every time, you may consider saving it as a file.
精彩评论