我必须在 JSP 页面中显示 PDF 文档。 PDF 文档有 25 页,但我只想显示 PDF 文件的 10 页。如何在 iText 的帮助下实现这一目标?
最佳答案
假设您已经有了 PDF 文件。
您可以使用 PdfStamper
和 PdfCopy
将 PDF 切片:
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显示,就看你的显示方式了。输出流将在所提供代码的末尾包含您在循环中复制的页面,在示例中它是所有页面。
这本质上是一个新的 PDF 文件,但在内存中。如果每次都是同一个文件的10页,可以考虑保存为文件。
关于java - 如何使用 iText 在 JSP 中显示有限页数的 PDF 文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7213067/