Java Tutorial/PDF/PDF Copy

Материал из Java эксперт
Версия от 17:44, 31 мая 2010; (обсуждение)
(разн.) ← Предыдущая | Текущая версия (разн.) | Следующая → (разн.)
Перейти к: навигация, поиск

Combine the different PDFs with forms and fields into one

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();
  }
}





Copy three PDF files into one PDF

import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfReader;
public class CopyThreePDFToOne {
  public static void main(String[] args) throws Exception {
    PdfReader reader = new PdfReader("Hello1.pdf");
    Document document = new Document(reader.getPageSizeWithRotation(1));
    PdfCopy copy = new PdfCopy(document, new FileOutputStream(
        "Pdf.pdf"));
    document.open();
    copy.addPage(copy.getImportedPage(reader, 1));
    reader = new PdfReader("Hello2.pdf");
    copy.addPage(copy.getImportedPage(reader, 1));
    reader = new PdfReader("Hello3.pdf");
    copy.addPage(copy.getImportedPage(reader, 1));
    document.close();
  }
}