saratkumar
saratkumar

Reputation: 59

Is it possible to convert JPEG file to PDF file in Java?

Is it possible to convert a JPEG file to a PDF file in Java?

Tried the below:

// pdf converter
Document document = new Document(PageSize.A4, 20, 20, 20, 20);
PdfWriter.getInstance(document, new FileOutputStream("C:\\ss.jpeg"));
document.open();
Image image = Image.getInstance(getClass().getResource("C:\\file.pdf"));
document.add(image);
document.close();

Error: Cannot make a static reference to the non-static method getClass() from the type Object

Upvotes: 2

Views: 11285

Answers (3)

Shivaraja HN
Shivaraja HN

Reputation: 168

public class ImageToPdf {
    public static void main(String... args) {
        Document document = new Document();
        String input = "resources/GMARBLES.png"; // .gif and .jpg are ok too!
        String output = "resources/GMARBLES.pdf";
        try {
            FileOutputStream fos = new FileOutputStream(output);
            PdfWriter writer = PdfWriter.getInstance(document, fos);
            writer.open();
            document.open();
            document.add(Image.getInstance(input));
            document.close();
            writer.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

Upvotes: 0

saratkumar
saratkumar

Reputation: 59

This worked for me.

public class CreatePDF {
        public static void main (String args[]) {
            Document document = new Document();
            document.addAuthor("authorname");
            document.addTitle("This is my pdf doc");
            PdfWriter.getInstance(document, new FileOutputStream("C:\\file.pdf"));
            document.open();
            Image image = Image.getInstance("C:\\img.png");
            document.add(image);
            document.close();
        }
    }

Upvotes: 2

Pritam Maske
Pritam Maske

Reputation: 2760

Use nameOfClass.class instead of getClass().

For Example Refer following code snippet :

Like as your :

public class Test {
    public static void main(String[] args) {
    Document document = new Document(PageSize.A4, 20, 20, 20, 20);
    PdfWriter.getInstance(document, new FileOutputStream("C:\\ss.jpeg"));
    document.open();
    Image image = Image.getInstance(getClass().getResource("C:\\file.pdf"));
    document.add(image);
    document.close();

    }
}

Change it to :

public class Test {

public static void main(String[] args) {
        Document document = new Document(PageSize.A4, 20, 20, 20, 20);
        PdfWriter.getInstance(document, new FileOutputStream("C:\\ss.jpeg"));
        document.open();
        Image image = Image.getInstance(Test.class.getResource("C:\\file.pdf"));
        document.add(image);
        document.close();
    }
}

Upvotes: 0

Related Questions