I came across this question on SO.
Java application runs properly in Eclipse, but not as .jar
I don't have any images in my code.I created a runnable jar file in the following way,
- Right click on project,
- Click Export,
- select "Runnable JAR File",
- Extract required libraries into generated JAR
When I run the .jar file on my desktop, the PDF file is being created. But it shows the following error
Adobe Reader could not open 'Result-itext.pdf' because it is either not a supported file type or because the file has been damaged
My Code:
try {
PdfWriter w = new PdfWriter("Result-itext.pdf");
PdfDocument d = new PdfDocument(w);
Document doc = new Document(d);
/** Added **/
Image img = new Image(ImageDataFactory.create(logo));
img.setHorizontalAlignment(HorizontalAlignment.CENTER);
doc.add(img);
/** Added **/
doc.add(new Paragraph("Test Name : Hello World").setTextAlignment(TextAlignment.CENTER));
doc.add(new Paragraph("Maximum Marks : 20").setTextAlignment(TextAlignment.CENTER));
doc.add(new Paragraph("RESULTS").setBold().setTextAlignment(TextAlignment.CENTER));
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA_OBLIQUE);
Table t = new Table(3);
t.setWidthPercent(70);
t.setHorizontalAlignment(HorizontalAlignment.CENTER);
t.setFont(font);
Cell cell = new Cell().add("User-ID").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
cell = new Cell().add("User-Name").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
cell = new Cell().add("Marks").setTextAlignment(TextAlignment.CENTER).setFont(font);
t.addCell(cell);
PdfFont font1 = PdfFontFactory.createFont(FontConstants.TIMES_ROMAN);
t.setFont(font1);
ArrayList<String> a = new ArrayList<String>();
for(int i=0;i<3;i++){
a.add(String.valueOf(i));a.add("jack");a.add(String.valueOf(i+10));
}
for(int i=0;i<9;i++){
cell = new Cell().add(a.get(i)).setTextAlignment(TextAlignment.CENTER);
t.addCell(cell);
}
doc.add(t);
doc.close();
JOptionPane.showMessageDialog(null, "Created file");
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}