-1

I tried to generate a pdf with two classes, but, I don't get the pdf because I have a NullPointerException in the line where I call the function that generates the document in the second class. I separate the process to generate pdf´s, because the first class have many other necessary functions. I don't know what causes this problem.

package org.ors.osc;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.ors.osc.Eml2Pdf2;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;

import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class Managepdf {

  private Eml2Pdf2 eml2Pdf2;

  public publishPdf2()  {
  Document doc = new Document();
  File pdfFile = dataDir.resourcePdfFile(resource.getShortname());
  OutputStream out = null;

  try {
      out = new FileOutputStream(pdfFile);
      PdfWriter.getInstance(doc, out);
      eml2Pdf2.writeEmlIntoPdf(doc); //In this part get null
  } catch (Exception e) {
        e.printStackTrace();
  } finally {
      if (out != null) {
          try {
                  out.close();
                } catch (IOException e) {
                  e.printStackTrace();
          }
      }
  }  
 }

}

This class call the function writeEmlIntoPdf

package org.ors.oscar;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;


import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;

import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;

public class Eml2Pdf2 {

    public void writeEmlIntoPdf (Document doc) throws DocumentException, FileNotFoundException {

        doc.open();
        doc.add(new Paragraph("Hello World, iText!!"));
        doc.add(new Paragraph(":D"));
        doc.close();

    }

}
morgano
  • 17,210
  • 10
  • 45
  • 56
user2928923
  • 1
  • 1
  • 1
  • private Eml2Pdf2 eml2Pdf2 = new Eml2Pdf2(); You are trying to access an object's methods without instantiating it; hence the NPE. – TEK Feb 07 '14 at 22:06

1 Answers1

1

You never instantiate eml2Pdf2 in Managepdf.

private Eml2Pdf2 eml2Pdf2;

Should be:

private Eml2Pdf2 eml2Pdf2 = new Eml2Pdf2();

It's also good practice to ensure each class has a constructor; although not strictly essential as a constructor will be implicitly created. The constructor is a the ideal place to instantiate your field variables (a good way to avoid getting NPE).

TEK
  • 1,265
  • 1
  • 15
  • 30