Sunday, November 20, 2011

creating header and footer for a existing pdf with iText


import java.awt.Color;
import java.io.FileOutputStream;

import com.itextpdf.text.Anchor;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfImportedPage;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;

public class PDF {

/**
* @param args
*/
public static void main(String[] args) {
Document document = new Document();
try {
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("/home/zana/Desktop/v59-10.pdf"));

document.open();

PdfContentByte cb = writer.getDirectContent();

// Load existing PDF
PdfReader reader = new PdfReader(new PdfReader(
"/home/zana/Desktop/v59-9.pdf"));
PdfImportedPage page = writer.getImportedPage(reader, 1);

// Copy first page of existing PDF into output PDF
document.newPage();
cb.addTemplate(page, 0, 0);

// Add your new data / text here
// for example...
Font font = new Font();
font.setColor(BaseColor.BLUE);
font.setStyle(Font.UNDERLINE);
Paragraph paragraph = new Paragraph();
paragraph.setLeading(0, 25);
paragraph.setAlignment(Paragraph.ALIGN_LEFT);
paragraph.setAlignment(Paragraph.ALIGN_BASELINE);
Chunk chunk = new Chunk("http://www.geek-tutorials.com", font)
.setAnchor("http://www.geek-tutorials.com");
paragraph.add(chunk);
document.add(paragraph);

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

}

No comments:

Post a Comment