Thursday, 10 November 2016

Convert Image to PDF

package com.gb.samples;

import java.io.File;
import java.io.FileOutputStream;

import com.itextpdf.text.Document;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;

public class Sample {

public static void main(String[] args) {
Rectangle pageSize = new Rectangle(2780, 2525);
Document pdfDocument = new Document(PageSize.A4);
String pdfFilePath = "C:/Users/vgrandhi/Desktop/sam/Converted_Image_to_PDF.pdf";
String inputFile = "C:/Users/vgrandhi/Desktop/sam/Converted_PdfFiles_to_Image/org_cropped.png";
try
{
    FileOutputStream fileOutputStream = new FileOutputStream(pdfFilePath);
    PdfWriter writer = null;
    writer = PdfWriter.getInstance(pdfDocument, fileOutputStream);
    writer.open();
    pdfDocument.open();
    /**
    * Proceed if the file given is a picture file
    */
    if (true)
    {
        pdfDocument.add(com.itextpdf.text.Image.getInstance(inputFile));
    }
    /**
    * Proceed if the file given is (.txt,.html,.doc etc)
    */
    else
    {
    File file = new File(inputFile);
    //pdfDocument.add(new Paragraph(org.apache.commons.io.FileUtils.readFileToString(file)));
    }

    pdfDocument.close();
    writer.close();
}
catch (Exception exception)
{
    System.out.println("Document Exception!" + exception);
}
}
}

Crop image in Java

package com.gb.samples;

import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

import javax.imageio.ImageIO;

public class Sample {

public static void main(String[] args) {
Image src = null;
try {
src = ImageIO.read(new File("C:/Users/vgrandhi/Desktop/sam/Converted_PdfFiles_to_Image/org_1.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}

int x = 0, y = 0, w = 400, h = 1600;

BufferedImage dst = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
dst.getGraphics().drawImage(src, 0, 0, w, h, x, y, x + w, y + h, null);

try {
ImageIO.write(dst, "png", new File("C:/Users/vgrandhi/Desktop/sam/Converted_PdfFiles_to_Image/org_cropped.png"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

Convert PDF to Image in Java

package com.gb.samples;

import java.awt.image.BufferedImage;
import java.io.File;
import java.util.List;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;

public class Sample {

public static void main(String[] args) {
       try {
       String sourceDir = "C:/Users/vgrandhi/Desktop/sam/org.pdf"; // Pdf files are read from this folder
       String destinationDir = "C:/Users/vgrandhi/Desktop/sam/Converted_PdfFiles_to_Image/"; // converted images from pdf document are saved here

       File sourceFile = new File(sourceDir);
       File destinationFile = new File(destinationDir);
       if (!destinationFile.exists()) {
           destinationFile.mkdir();
           System.out.println("Folder Created -> "+ destinationFile.getAbsolutePath());
       }
       if (sourceFile.exists()) {
           System.out.println("Images copied to Folder: "+ destinationFile.getName());            
           PDDocument document = PDDocument.load(new File(sourceDir));
           List<PDPage> list = document.getDocumentCatalog().getAllPages();
           System.out.println("Total files to be converted -> "+ list.size());

           String fileName = sourceFile.getName().replace(".pdf", "");            
           int pageNumber = 1;
           for (PDPage page : list) {
               BufferedImage image = page.convertToImage();
               File outputfile = new File(destinationDir + fileName +"_"+ pageNumber +".png");
               System.out.println("Image Created -> "+ outputfile.getName());
               ImageIO.write(image, "png", outputfile);
               pageNumber++;
           }
           document.close();
           System.out.println("Converted Images are saved at -> "+ destinationFile.getAbsolutePath());
       } else {
           System.err.println(sourceFile.getName() +" File not exists");
       }

   } catch (Exception e) {
       e.printStackTrace();
   }
}
}

Needed jars:

pdfbox-app-1.8.3, itextpdf-5.5.9

Divide single pdf into multiple pdf's

package com.gb.samples;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfCopy;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class Sample {

public static void main(String[] args) {

        try {
            String inFile = "C:/Users/vgrandhi/Desktop/sam/bill.pdf";

           System.out.println ("Reading " + inFile);
            PdfReader reader = new PdfReader(inFile);
            Rectangle cropBox = reader.getCropBox(1);          
            Rectangle  psize = reader.getPageSize(1);
            cropBox.setRight(psize.getWidth()/2);
            System.out.println(psize.getWidth());
            System.out.println(psize.getHeight());
            int n = reader.getNumberOfPages();
            System.out.println ("Number of pages : " + n);
            int i = 0;
            while ( i < n ) {
                String outFile = inFile.substring(0, inFile.indexOf(".pdf"))
                    + "-" + String.format("%03d", i + 1) + ".pdf";
                System.out.println ("Writing " + outFile);
                Document document = new Document(cropBox);
                PdfCopy writer = new PdfCopy(document, new FileOutputStream(outFile));
                writer.setCropBoxSize(cropBox);
                document.open();
                PdfImportedPage page = writer.getImportedPage(reader, ++i);
                writer.addPage(page);
                document.close();
                writer.close();                    
            }
        }
        catch (Exception e) {
            e.printStackTrace();
        }  
    }  
}