Stamping PDF file

by Mohan 2012-09-21 13:44:47

Stamping PDF file


import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
import com.lowagie.text.pdf.AcroFields;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.GrayColor;
import com.lowagie.text.pdf.PdfContentByte;
import com.lowagie.text.pdf.PdfCopyFields;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfStamper;
import com.lowagie.text.pdf.PdfWriter;
import com.lowagie.text.pdf.TextField;

public class MainClass{
public static void main(String[] args) throws Exception {
createPdf("1.pdf", "field1", "value");
createPdf("2.pdf", "field2", "value");
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfCopyFields copy = new PdfCopyFields(baos);
copy.addDocument(new PdfReader("1.pdf"));
copy.addDocument(new PdfReader("2.pdf"));
copy.close();

PdfReader reader = new PdfReader(baos.toByteArray());
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(
"HelloWorldCopyStamp.pdf"));
AcroFields form = stamper.getAcroFields();
form.setField("field1", "World");
form.setField("field2", "People");
stamper.setFormFlattening(true);
stamper.close();
}

private static void createPdf(String filename, String field, String value)
throws Exception {
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(
filename));
document.open();
BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI,
BaseFont.NOT_EMBEDDED);
PdfContentByte cb = writer.getDirectContent();
cb.beginText();
cb.setFontAndSize(bf, 12);
cb.setLeading(16);
cb.moveText(36f, 788f);
cb.showText("Hi");
cb.newlineShowText("this is a atest");
cb.endText();

TextField tf = new TextField(writer, new Rectangle(64, 785, 340, 800),
field);
tf.setFontSize(12);
tf.setFont(bf);
tf.setText(value);
tf.setTextColor(new GrayColor(0.5f));
writer.addAnnotation(tf.getTextField());

document.close();
}
}

Tagged in:

603
like
0
dislike
0
mail
flag

You must LOGIN to add comments