How can I convert a PNG file to PDF using java?

前端 未结 4 959
眼角桃花
眼角桃花 2020-12-30 14:11

Are there any open source libraries that I can use?

4条回答
  •  礼貌的吻别
    2020-12-30 14:59

    Use iText to convert jpg/png/gif to pdf with following code. It's work perfect.

    import java.io.FileOutputStream;
    //com.lowagie...   old version
    //com.itextpdf...  recent version
    import com.itextpdf.text.Document;
    import com.itextpdf.text.pdf.PdfWriter;
    import com.itextpdf.text.Image;
    
    public class ImageToPDF {
      public static void main(String ... args) {
        Document document = new Document();
        String input = "c:/temp/capture.png"; // .gif and .jpg are ok too!
        String output = "c:/temp/capture.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();
        }
      }
    }
    

提交回复
热议问题