如何使用iText在JSP中显示有限数量的PDF文件页面?

问题描述:

我必须在JSP页面中显示PDF文档。 PDF文档有25页,但我只想显示10页的PDF文件。如何在iText的帮助下实现这一目标?

I have to display a PDF document in a JSP page. The PDF document has 25 pages, but I want to display only 10 pages of the PDF file. How can I achieve this with help of iText?

假设您已经拥有PDF文件。

Assuming you have the PDF file already.

您可以使用 PdfStamper PdfCopy 来分割PDF:

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 

至于将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.

这基本上是一个新的PDF文件,但在内存中。如果每次都是同一个文件的10页,您可以考虑将其保存为文件。

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.