Convert a png/jpg/gif file to PDF using iTextTag(s): IO Open Source


iText

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();
    }
  }
}
You can get the image from an URL :
      document.add(Image.getInstance
        (new java.net.URL("http://www.rgagnon.com/images/javahowto.jpg")));
And you can resize it :
      Image img = Image.getInstance
         (new java.net.URL("http://www.rgagnon.com/images/javahowto.jpg"));
      img.scalePercent(50);
      document.add(img);

blog comments powered by Disqus