Reputation: 701
I have wrote a jsp servlet to read pdf using itextpdf , i end up with exception Can someone tell me the reason for exception
page.jsp
<html>
<%@page import="java.io.File"%>
<%@page import="java.io.*"%>
<%@page import="javax.servlet.*"%>
<%@page import="com.itextpdf.text.Image"%>
<%@page import="com.itextpdf.text.Document"%>
<%@page import="com.itextpdf.text.DocumentException"%>
<%@page import="com.itextpdf.text.pdf.PdfReader"%>
<%@page import="com.itextpdf.text.pdf.PdfImportedPage"%>
<%@page import="com.itextpdf.text.pdf.PdfWriter"%>
<%@page import="com.itextpdf.text.pdf.PdfContentByte"%>
<%
response.reset();
response.setContentType("application/pdf");
response.setHeader("Content-Disposition",
"inline;filename=Saba_PhBill.pdf");
File file = new File(
"D:\\TNWRD_Documents\\Knowladge_Base\\CHAPTER_I.pdf");
String OUTPUTFILE = "D:\\TNWRD_Documents\\CHAPTER_II.pdf";
FileInputStream in = new FileInputStream(file);
PdfReader reader = new PdfReader(in);
Document document = new Document();
//PdfWriter writer = PdfWriter.getInstance(document,
// new FileOutputStream(OUTPUTFILE));
OutputStream outputStream = new FileOutputStream(OUTPUTFILE);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
//PdfReader reader = new PdfReader(INPUTFILE);
PdfContentByte cb = writer.getDirectContent();
int n = reader.getNumberOfPages();
PdfImportedPage pages;
// Go through all pages
for (int i = 1; i <= n; i++) {
// Only page number 2 will be included
pages = writer.getImportedPage(reader, i);
Image instance = Image.getInstance(pages);
document.add(instance);
cb.addTemplate(pages, 0, 0);
document.addHeader("pdf", "pdf");
}
document.close();
%>
</html>
Upvotes: 0
Views: 704
Reputation: 77546
Well, you won't be able to display a PDF in a browser if you enclose the PDF file between <html>
and </html>
tags. That's illegal syntax.
Furthermore, you're writing the PDF to a FileOutputStream
. That's... very odd. You need to send the PDF bytes to a ServletOutputStream.
This is the most simple Hello World Servlet: Hello.
Do you see which OutputStream is used when creating the PdfWriter
instance? response.getOutputStream()
is a ServletOutputStream
instance.
Of course, while this works for most browsers, you'll encounter some problems with some legacy browser versions. That's why there's also this example: PdfServlet
Finally, you're a JSP developer, so you remember from your JSP courses that creating binary files from JSP is always a bad idea. Good developers write a Servlet to create binary documents.
Upvotes: 1