-1

I have the following situation.

I have a Main class in which I declared the standard public static void main(String[] args) method

Into the body of this main() method I am trying to call the following printPdf() declared into the Main class:

private void printPdf() {

    /** The resulting PDF file: */
    String result = "D:/SOFTLAB/massive_pdf_print.pdf";

    // STEP 1 Creazione del documento in formato A4 e senza margini:
    com.itextpdf.text.Document document = new com.itextpdf.text.Document(com.itextpdf.text.PageSize.A4, 0, 0, 0, 0);

    try {
        /* STEP 2 Constructs a PdfWriter.
                  document: The PdfDocument that has to be written.
                  os: The OutputStream the writer has to write to
         */
        PdfWriter.getInstance(document, new FileOutputStream(result));

        // STEP 3:
        document.open();

        // STEP 4:
        document.add(new Paragraph("Hello World!"));

        // STEP 5:
        document.close();

    }catch (DocumentException ex){
        ex.printStackTrace();
    }
    catch (IOException ex){
        ex.printStackTrace();
    }

}

To call it I do:

this.printPdf();

but I obtain the following error message: 'mainPkg.Main.this' cannot be referenced from a static context

So I think that it happens because the main() method is a static method but how can I correctly call my printPdf() method (that is declared in the same Main class that contains the main()) ?

Tnx

AndreaNobili
  • 40,955
  • 107
  • 324
  • 596
  • `printPdf()` is not static method. It has to be wether you want to call it from another static method, like `main`. – Héctor Feb 17 '15 at 14:24
  • @bigdestroyer: Well, no, it doesn't - the OP could create an instance of the containing class. It's far too simplistic to say that from within static methods you can only call other static methods. – Jon Skeet Feb 17 '15 at 14:32

1 Answers1

4

Declare the method printPdf() as static, or instantiate a new object of class Main, then call it from it.

Michał Szydłowski
  • 3,261
  • 5
  • 33
  • 55