Here is a snippet of my Servlet code which generates a PDF and then opens it. It can not open the “AvtoSolaZaposleniXSL.xsl” file. If I run the same procedure in a normal Java class everything runs smooth.
public class PDF extends HttpServlet {
private static final long serialVersionUID = 1L;
public PDF() { super(); }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Generiraj PDF
File xmlfile = new File(getServletContext().getRealPath("AvtoSolaZ.xml"));
File xsltfile = new File(getServletContext().getRealPath("AvtoSolaZaposleniXSL.xsl"));
ExampleXML2PDF.generirajPDF(xmlfile, xsltfile);
//Počakaj da se v miru zgenerira PDF
try {
Thread.sleep(5000L);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
//Zaženi pdf
File f1 = new File(getServletContext().getRealPath("Avtosola.pdf"));
String pdfKoncni = f1.toString();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfReader reader = new PdfReader(pdfKoncni);
PdfStamper stamper = null;
try {
stamper = new PdfStamper(reader, baos);
} catch (DocumentException e) {
e.printStackTrace();
}
try {
stamper.close();
} catch (DocumentException e) {
e.printStackTrace();
}
// set some response headers
response.setHeader("Expires", "0");
response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
response.setHeader("Pragma", "public");
response.setContentType("application/pdf");
response.setContentLength(baos.size());
OutputStream os = response.getOutputStream();
baos.writeTo(os);
os.flush();
os.close();
}
All my files are in the WebContent folder and my Servlet in a default package.
Error:
(Location of error unknown)java.io.FileNotFoundException: C:\Eclipse\eclipse\WebContent\AvtoSolaZaposleniXSL.xsl (The system cannot find the file specified)
java.lang.NullPointerException
Believe me that I have searched for an answer like this and haven’t found anything that could actually help me. Even if I put the whole path (Which is not C:\Eclipse\eclipse… and I don’t know why it states that way..) it still does not work.
Like I said. If I run it in a normal Java class it generates the PDF normally and works just fine…
import java.io.File;
public class Test {
public static void main(String[] args) {
File xmlfile = new File("WebContent/AvtoSolaZ.xml");
File xsltfile = new File("WebContent/AvtoSolaZaposleniXSL.xsl");
ExampleXML2PDF.generirajPDF(xmlfile, xsltfile);
}
}
Please help!
I re-thinked my problem and came up with an easier solution on how to display a pdf which was generated. I just used my class, which generates a pdf(XSL-FO transformation, for which an xml and xsl is needed..) and copied the code into the servlet. Adjusted the output stream and voula!
Here is the code of the new servlet which works perfectly fine: