Search code examples
javaeclipsepdfboxeclipse-junojava-6

Error while using pdfbox to create pdf : Identifier expected after this token


I am working on a plain Java project in eclipse juno using jre6/jdk6 as runtime/compiler. I wish to use apache pdfbox to generate some pdfs. i have downloaded and added pdfbox 1.8.9 to my build path. now i took a code sample from here, and used it in my application, but it is giving me multiple error which i think is related to some environment problems.

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
public class TestPdf {

PDDocument document = new PDDocument();
// Create a new blank page and add it to the document
PDPage blankPage = new PDPage();
document.addPage( blankPage );
// Save the newly created document
document.save("BlankPage.pdf");
// finally make sure that the document is properly
// closed.
document.close();
}

These are the errors i am getting :

Syntax error on token "blankPage", VariableDeclaratorId expected after this token
Syntax error on token ""BlankPage.pdf"", delete this token
Syntax error on token "close", Identifier expected after this token

Solution

  • You should create a method and move some of the code inside the method :

    public class TestPdf {
    
        PDDocument document = new PDDocument();
        // Create a new blank page and add it to the document
        PDPage blankPage = new PDPage();
    
        public void createDocument()throws Exception {
            document.addPage(blankPage);
            // Save the newly created document
            document.save("BlankPage.pdf");
            // finally make sure that the document is properly
            // closed.
            document.close();
        }
    }
    

    The code that you posted in your question is against the syntax rules of the Java language. You can read more about the structure of a class here