Java Tutorial/PDF/Security

Материал из Java эксперт
Перейти к: навигация, поиск

Add Certificate to Pdf document

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.security.KeyStore;
import java.security.PrivateKey;
import java.security.cert.Certificate;
import com.lowagie.text.pdf.PdfReader;
import com.lowagie.text.pdf.PdfSignatureAppearance;
import com.lowagie.text.pdf.PdfStamper;
public class MainClass {
  public static void main(String[] args) throws Exception {
    PdfReader reader;
    KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
    ks.load(new FileInputStream(".keystore"), "string".toCharArray());
    PrivateKey key = (PrivateKey) ks.getKey("key", "value".toCharArray());
    Certificate[] chain = ks.getCertificateChain("foobar");
    reader = new PdfReader("2.pdf");
    FileOutputStream os = new FileOutputStream("1.pdf");
    PdfStamper stamper = PdfStamper.createSignature(reader, os, "\0");
    PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED);
    appearance.setReason("personal");
    appearance.setLocation("Foobar");
    appearance.setVisibleSignature("yoursig");
    stamper.close();
  }
}





PDF with an unsigned signature field

import java.io.FileOutputStream;
import com.lowagie.text.Document;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.PdfAcroForm;
import com.lowagie.text.pdf.PdfWriter;
public class MainClass {
  public static void main(String[] args) throws Exception {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("2.pdf"));
    document.open();
    document.add(new Paragraph("This is a message."));
    PdfAcroForm acroForm = writer.getAcroForm();
    acroForm.addSignature("yoursig", 73, 705, 149, 759);
    document.close();
  }
}