是否可以在Java中将.jpg转换为.pdf?

时间:2018-04-18 13:44:34

标签: java

是否可以在Java中将.jpg转换为.pdf?

尝试以下方法:

// 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();
  

错误:无法对非静态方法进行静态引用   来自Object

类型的getClass()

3 个答案:

答案 0 :(得分:0)

使用 nameOfClass.class 代替 getClass()

例如,请参阅以下代码段:

与您一样:

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();

    }
}

将其更改为:

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();
    }
}

答案 1 :(得分:0)

这对我有用。

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();
        }
    }

答案 2 :(得分:0)

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();
        }
    }
}