Thursday 15 October 2015

Image Alignment along with Image Hyperlink URL in PDF using itextpdf

I am posting this simple but useful code for those friends who want's to align Image and also want to set anchor(for hyperlink) to that image. I found my team member struggling with Image alignment with it's hyperlink URL alignment  in a PDF file.

Jar Used - itextpdf.-5.4.3.jar

Code-

package com.nik.service;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.net.URL;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Image;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfAction;
import com.itextpdf.text.pdf.PdfWriter;

public class FileGeneratorServiceImpl {
public static void main(String[] args) {
try {
createPdf("testPdf2.pdf");
} catch (DocumentException e) {
e.printStackTrace();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}

protected static void createPdf(String filename) throws IOException,
DocumentException {
// ----------step 1-----------
Document document = new Document();
// ---------step 2------------
PdfWriter.getInstance(document, new FileOutputStream(filename));
// ---------step 3---------------
document.open();
// --------step 4---------------

Paragraph p = new Paragraph(200);

Image img = Image.getInstance("D:\\chrome.jpg");
img.setAlignment(Image.ALIGN_LEFT);
img.scaleAbsolute(100, 100);
Chunk imgChunk1 = new Chunk(img, 0f, -200f);
imgChunk1.setGenericTag("Google");
imgChunk1.setAction(new PdfAction(new URL("http://www.google.com")));
p = new Paragraph();
p.setAlignment(Paragraph.ALIGN_LEFT);
p.add(imgChunk1);

document.add(p);

// --------------------Adding 2nd Image in doc---------------

Image img2 = Image.getInstance("D:\\servicedesk.jpg");
img2.setAlignment(Image.ALIGN_RIGHT);
img2.scaleAbsolute(100, 100);
Chunk imgChunk2 = new Chunk(img2, 0f, -200f);
imgChunk2.setAction(new PdfAction(new URL("https://www.yahoo.com/")));
p = new Paragraph();
p.setAlignment(Paragraph.ALIGN_RIGHT);
p.add(imgChunk2);
document.add(p);

// step 5
document.close();// Closing the doc
}
}

No comments:

Post a Comment