Saturday, March 18, 2017

Image to PDF using Java

This blog post will allow you to convert your images from either your local system or from URL into pdf format using java code. This will make use of itextpdf library.

Language Used:
Java

Git Location:
https://github.com/csanuragjain/extra/tree/master/Image2PDF

POM Dependency:
  <dependency>  
       <groupId>com.itextpdf</groupId>  
       <artifactId>itextpdf</artifactId>  
       <version>5.0.6</version>  
       <scope>test</scope>  
  </dependency>  

Program:
main method:
      public static void main(String[] args) {  
           Scanner s =new Scanner(System.in);  
           System.out.println("Please provide the path of image");  
           String imgPath=s.nextLine();  
           System.out.println("Please provide the path of pdf");  
           String pdfPath=s.nextLine();  
           boolean isValidURL=false;  
           URL url;  
           try {  
             url = new URL(imgPath);  
             isValidURL=true;  
           } catch (MalformedURLException e) {  
           }  
           new ImageToPDF().imageToPdf(imgPath, pdfPath, isValidURL);  
           s.close();  
           System.out.println("PDF created...");
      }  

How it works:
  1. We create a scanner object to get user input.
  2. We obtain the source path of image and pdf to be created.
  3. We check if the source path of image is a url or is coming from user local computer. We do this by making a URL class object with the image path passed. If the URL is valid then we update isValidURL to true else false.
  4. Now we call the imagetoPDF method which actually converts the image to pdf.
  5. First argument is the path of image. Second one is the path of pdf. Third argument tell if the image is coming from a URL or from user local computer.
imageToPdf method:
      public void imageToPdf(String imgPath, String pdfPath, boolean isValidURL)  
      {  
           Document document= new Document(PageSize.A4);  
           FileOutputStream fos;  
           try {  
                fos = new FileOutputStream(new File(pdfPath));  
                PdfWriter writer = PdfWriter.getInstance(document, fos);  
                writer.open();  
             document.open();  
             if(isValidURL)  
             {  
                  Image img=Image.getInstance(new java.net.URL(imgPath));  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             else  
             {  
                  Image img=Image.getInstance(imgPath);  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             document.close();  
             writer.close();  
           } catch (FileNotFoundException e) {  
                System.out.println("File not found "+e.getMessage());  
           } catch (DocumentException e) {  
                System.out.println("Document exception "+e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Incorrect path given "+e.getMessage());  
           } catch (IOException e) {  
                System.out.println("Issue while accessing the input file "+e.getMessage());  
           }  
      }  


How it works:
  1. We make a document object and pass PageSize.A4 which simply tells that resulting pdf has A4 size page.
  2. We create a PDFWriter object passing the document we created in step1 and a FileOutputStream object pointing to the pdf file to be created as argument. PDFWriter will be responsible of actually writing on the pdf.
  3. We open the writer object and document object.
  4. Now we prepare the document by adding the image to it. For this we use the add function on document. 
  5. We resized the image using scalePercent so that image does not become larger than pdf.
  6. We close the document and writer which ultimately completes the process and pdf is created.
Output:
 #1  
 Please provide the path of image  
 screen1.jpg  
 Please provide the path of pdf  
 screen1.pdf  
 PDF created...  
 #2  
 Please provide the path of image  
 https://ul-a.akamaihd.net/images/products/94427/product/Apollo_Infinite_FNSF51APMI30000SAAAA.jpg?1467964020  
 Please provide the path of pdf  
 abc.pdf  
 PDF created...  

Full Program:
 package com.cooltrickshome;  
 import java.io.File;  
 import java.io.FileNotFoundException;  
 import java.io.FileOutputStream;  
 import java.io.IOException;  
 import java.net.MalformedURLException;  
 import java.net.URL;  
 import java.util.Scanner;  
 import com.itextpdf.text.Document;  
 import com.itextpdf.text.DocumentException;  
 import com.itextpdf.text.Image;  
 import com.itextpdf.text.PageSize;  
 import com.itextpdf.text.pdf.PdfWriter;  
 public class ImageToPDF {  
      /**  
       * @param args  
       */  
      public static void main(String[] args) {  
           Scanner s =new Scanner(System.in);  
           System.out.println("Please provide the path of image");  
           String imgPath=s.nextLine();  
           System.out.println("Please provide the path of pdf");  
           String pdfPath=s.nextLine();  
           boolean isValidURL=false;  
           URL url;  
           try {  
             url = new URL(imgPath);  
             isValidURL=true;  
           } catch (MalformedURLException e) {  
           }  
           new ImageToPDF().imageToPdf(imgPath, pdfPath, isValidURL);  
           s.close();  
           System.out.println("PDF created...");  
      }  
      public void imageToPdf(String imgPath, String pdfPath, boolean isValidURL)  
      {  
           Document document= new Document(PageSize.A4);  
           FileOutputStream fos;  
           try {  
                fos = new FileOutputStream(new File(pdfPath));  
                PdfWriter writer = PdfWriter.getInstance(document, fos);  
                writer.open();  
             document.open();  
             if(isValidURL)  
             {  
                  Image img=Image.getInstance(new java.net.URL(imgPath));  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             else  
             {  
                  Image img=Image.getInstance(imgPath);  
                  float scaler = ((document.getPageSize().getWidth() - document.leftMargin()  
                   - document.rightMargin()) / img.getWidth()) * 100;  
                  img.scalePercent(scaler);  
                  document.add(img);  
             }  
             document.close();  
             writer.close();  
           } catch (FileNotFoundException e) {  
                System.out.println("File not found "+e.getMessage());  
           } catch (DocumentException e) {  
                System.out.println("Document exception "+e.getMessage());  
           } catch (MalformedURLException e) {  
                System.out.println("Incorrect path given "+e.getMessage());  
           } catch (IOException e) {  
                System.out.println("Issue while accessing the input file "+e.getMessage());  
           }  
      }  
 }  

Hope it helps :)

No comments:

Post a Comment