Refresh Your Java - Before Java Interview
We are Agile, believe in less Documentation - Only Quick notes (Java Interview Questions) of Java/J2ee Read more....
PDF Servlet with Spring "AbstractPdfView" :
This example
shows us how to open the Servlet output as
PDF file with
Spring "AbstractPdfView" and
"lowagie" API.
Please simply
select with your mouse and copy if you want
to use this
ready made sample.
import
com.lowagie.text.Document;
import
com.lowagie.text.pdf.PdfContentByte;
import
com.lowagie.text.pdf.PdfImportedPage;
import
com.lowagie.text.pdf.PdfReader;
import
com.lowagie.text.pdf.PdfWriter;
import
org.springframework.web.servlet.view.document.AbstractPdfView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import
java.io.FileInputStream;
import java.util.Map;
public class PDFView extends AbstractPdfView {
private String filename;
public String getFilename() {
return filename;
}
public void
setFilename(String filename) {
this.filename = filename;
}
protected void
buildPdfDocument(
Map model,
Document doc,
PdfWriter
writer,
HttpServletRequest req,
HttpServletResponse resp)
throws Exception {
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new
PdfReader(new FileInputStream(filename));
for (int i = 1; i <=
reader.getNumberOfPages(); i++) {
doc.newPage();
//import the
page from source pdf
PdfImportedPage page =
writer.getImportedPage(reader, i);
//add the page
to the destination pdf
cb.addTemplate(page, 0, 0);
}
}
protected Document newDocument()
{
return new
Document();
}
}
Spring Config XML:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-2.5.xsd">
<bean
name="*.pdf"
class="salesOrder.PDFView">
</bean>
</beans>
Web.xml Changes :
<servlet>
<servlet-name>pdfViewer</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>pdfViewer</servlet-name>
<url-pattern>*.pdf</url-pattern>
</servlet-mapping>
This Portal is intended to put all Java/J2ee related topics at one single place for quick referance, not only Technical , but also the Project Management Related thing such as Development Process methodoogies build process, unit testing etc.,
This Portal has More than 500 Java Interview Questions (also could be Considered as Quick Notes) very neatly separated topic by topic with simple diagrams which makes you easily understandable. Importantly these are from our Realtime expericance.