需要通过iText PDF生成器在PDF中显示变量value1到value4。当我使用该值时,它显示“无法对非静态字段值1进行静态引用”。我怎么能解决这个问题? 这是代码:
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class GenerateSummonPDF
{
private String value1;
private String value2;
private String value3;
private String value4; //this variables with constant updated string data
public String getValue1()
{
return this.value1;
}
public void userdata(String p1, String p2, String p3, String p4)
{
this.value1 = p1;
this.value2 = p2;
this.value3 = p3;
this.value4 = p4;
}
public static void main(String[] args)
{
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
}
答案 0 :(得分:1)
您需要GenerateSummonPDF
的实例来调用非静态方法:
public static void main(String[] args)
{
GenerateSummonPDF generateSummonPDF = new GenerateSummonPDF(); //create an instance
generateSummonPDF.userdata("TestString1", "TestString2", "TestString3", "TestString4"); //some content
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(generateSummonPDF.getValue1()); //get value1
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}
答案 1 :(得分:0)
您正在调用静态方法中的值,以便您收到此错误,只需创建一个函数并将代码放在那里就好了。
public static void main(String[] args)
{
createPdf();
}
createPdf(){
Document document = new Document();
try
{
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("C:\\Users\\User\\workspace\\enforement system\\Summon PDF list\\Serial No.pdf"));
document.open();
document.add(new Paragraph(getValue1()); //i need to print all the data here from the userdata
document.close();
writer.close();
} catch (DocumentException e)
{
e.printStackTrace();
} catch (FileNotFoundException e)
{
e.printStackTrace();
}
}