Combine the different PDFs with forms and fields into one : PDF Copy « PDF « Java Tutorial






import java.io.FileOutputStream;

import com.lowagie.text.Document;
import com.lowagie.text.PageSize;
import com.lowagie.text.Rectangle;
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.PdfWriter;
import com.lowagie.text.pdf.TextField;

public class HelloWorldCopyFields {

  public static void main(String[] args) throws Exception {
    createPdf("1.pdf", "field1", "value1.1");
    createPdf("2.pdf", "field1", "value1.2");
    createPdf("3.pdf", "field2", "value2");

    PdfCopyFields copy = new PdfCopyFields(new FileOutputStream(
        "CopyFields.pdf"));
    copy.addDocument(new PdfReader("1.pdf"));
    copy.addDocument(new PdfReader("2.pdf"));
    copy.addDocument(new PdfReader("3.pdf"));
    copy.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.moveText(36f, 788);
    cb.showText("Hello");
    cb.endText();

    TextField tf = new TextField(writer, new Rectangle(67, 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();
  }
}








29.7.PDF Copy
29.7.1.Copy three PDF files into one PDF
29.7.2.Combine the different PDFs with forms and fields into one