Example usage for com.itextpdf.text.pdf PdfStamper PdfStamper

List of usage examples for com.itextpdf.text.pdf PdfStamper PdfStamper

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf PdfStamper PdfStamper.

Prototype

public PdfStamper(final PdfReader reader, final OutputStream os, final char pdfVersion, final boolean append)
        throws DocumentException, IOException 

Source Link

Document

Starts the process of adding extra content to an existing PDF document, possibly as a new revision.

Usage

From source file:com.ots.jsp1.itext.ADAStamper.java

License:Open Source License

public void addADAAsWatermark(InputStream inStream, OutputStream outputStream, String ADA)
        throws DocumentException, IOException {
    PdfStamper stamper = null;/*from   w w  w.jav  a  2  s .  c  om*/
    PdfReader reader = null;
    try {

        reader = new PdfReader(inStream);
        //The zero byte means we dont want to change the version number of the PDF file.
        //true->not to change any of the original bytes
        stamper = new PdfStamper(reader, outputStream, '\0', true);
        int numberOfPages = reader.getNumberOfPages();

        for (int currentPage = 1; currentPage <= numberOfPages; currentPage++) {

            PdfAppearance canvas = PdfAppearance.createAppearance(stamper.getWriter(), 100, 30);
            canvas.setFontAndSize(
                    BaseFont.createFont(fontFilePath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED, true), 11);
            Rectangle pageSize = reader.getPageSizeWithRotation(currentPage);
            Rectangle watermarkPosition = new Rectangle(pageSize.getRight() - 150, pageSize.getTop() - 30,
                    pageSize.getRight() - 50, pageSize.getTop() - 10, 0);
            PdfAnnotation annotation = PdfAnnotation.createFreeText(stamper.getWriter(), watermarkPosition, ADA,
                    canvas);
            annotation.put(PdfName.F, new PdfNumber(PdfAnnotation.FLAGS_READONLY));

            //  annotation.put(PdfName.FONT, canvas);
            //  PdfAnnotation annotation = PdfAnnotation.createText(stamper.getWriter(), watermarkPosition, "", ADA, true, "Key");
            // 

            PdfBorderDictionary borderDictionary = new PdfBorderDictionary(0, PdfBorderDictionary.STYLE_SOLID);

            annotation.setBorderStyle(borderDictionary);
            stamper.addAnnotation(annotation, currentPage);
        }
    } finally {
        stamper.close();
        reader.close();
    }

}

From source file:com.swisscom.ais.itext.PDF.java

License:Open Source License

/** 
 * Add external revocation information to DSS Dictionary, to enable Long Term Validation (LTV) in Adobe Reader
 * /*from  ww  w.j av  a  2s .  co m*/
 * @param ocspArr List of OCSP Responses as base64 encoded String
 * @param crlArr  List of CRLs as base64 encoded String
 * @throws Exception 
 */
public void addValidationInformation(ArrayList<String> ocspArr, ArrayList<String> crlArr) throws Exception {
    if (ocspArr == null && crlArr == null)
        return;

    PdfReader reader = new PdfReader(outputFilePath);

    // Check if source pdf is not protected by a certification
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED)
        throw new Exception(
                "Could not apply revocation information (LTV) to the DSS Dictionary. Document contains a certification that does not allow any changes.");

    Collection<byte[]> ocspColl = new ArrayList<byte[]>();
    Collection<byte[]> crlColl = new ArrayList<byte[]>();

    // Decode each OCSP Response (String of base64 encoded form) and add it to the Collection (byte[])
    if (ocspArr != null) {
        for (String ocspBase64 : ocspArr) {
            OCSPResp ocspResp = new OCSPResp(new ByteArrayInputStream(Base64.decode(ocspBase64)));
            BasicOCSPResp basicResp = (BasicOCSPResp) ocspResp.getResponseObject();

            if (Soap._debugMode) {
                System.out.println("\nEmbedding OCSP Response...");
                System.out.println("Status                : " + ((ocspResp.getStatus() == 0) ? "GOOD" : "BAD"));
                System.out.println("Produced at           : " + basicResp.getProducedAt());
                System.out.println("This Update           : " + basicResp.getResponses()[0].getThisUpdate());
                System.out.println("Next Update           : " + basicResp.getResponses()[0].getNextUpdate());
                System.out.println("X509 Cert Issuer      : " + basicResp.getCerts()[0].getIssuer());
                System.out.println("X509 Cert Subject     : " + basicResp.getCerts()[0].getSubject());
                System.out.println(
                        "Responder ID X500Name : " + basicResp.getResponderId().toASN1Object().getName());
                System.out.println("Certificate ID        : "
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString() + " ("
                        + basicResp.getResponses()[0].getCertID().getSerialNumber().toString(16).toUpperCase()
                        + ")");
            }

            ocspColl.add(basicResp.getEncoded()); // Add Basic OCSP Response to Collection (ASN.1 encoded representation of this object)
        }
    }

    // Decode each CRL (String of base64 encoded form) and add it to the Collection (byte[])
    if (crlArr != null) {
        for (String crlBase64 : crlArr) {
            X509CRL x509crl = (X509CRL) CertificateFactory.getInstance("X.509")
                    .generateCRL(new ByteArrayInputStream(Base64.decode(crlBase64)));

            if (Soap._debugMode) {
                System.out.println("\nEmbedding CRL...");
                System.out.println("IssuerDN                    : " + x509crl.getIssuerDN());
                System.out.println("This Update                 : " + x509crl.getThisUpdate());
                System.out.println("Next Update                 : " + x509crl.getNextUpdate());
                System.out.println(
                        "No. of Revoked Certificates : " + ((x509crl.getRevokedCertificates() == null) ? "0"
                                : x509crl.getRevokedCertificates().size()));
            }

            crlColl.add(x509crl.getEncoded()); // Add CRL to Collection (ASN.1 DER-encoded form of this CRL)
        }
    }

    byteArrayOutputStream = new ByteArrayOutputStream();
    PdfStamper stamper = new PdfStamper(reader, byteArrayOutputStream, '\0', true);
    LtvVerification validation = stamper.getLtvVerification();

    // Add the CRL/OCSP validation information to the DSS Dictionary
    boolean addVerification = false;
    for (String sigName : stamper.getAcroFields().getSignatureNames()) {
        addVerification = validation.addVerification(sigName, // Signature Name
                ocspColl, // OCSP
                crlColl, // CRL
                null // certs
        );
    }

    validation.merge(); // Merges the validation with any validation already in the document or creates a new one.

    stamper.close();
    reader.close();

    // Save to (same) file
    OutputStream outputStream = new FileOutputStream(outputFilePath);
    byteArrayOutputStream.writeTo(outputStream);

    if (Soap._debugMode) {
        if (addVerification)
            System.out.println("\nOK merging LTV validation information to " + outputFilePath);
        else
            System.out.println("\nFAILED merging LTV validation information to " + outputFilePath);
    }

    byteArrayOutputStream.close();
    outputStream.close();
}

From source file:cz.hobrasoft.pdfmu.operation.args.OutPdfArgs.java

License:Open Source License

private void openStpNew(PdfReader pdfReader, char pdfVersion) throws OperationException {
    assert os != null;
    assert stp == null;

    // Open the PDF stamper
    try {/*from  w  w  w. j  a  va  2  s  .c  om*/
        stp = new PdfStamper(pdfReader, os, pdfVersion, append);
    } catch (DocumentException | IOException ex) {
        throw new OperationException(OUTPUT_STAMPER_OPEN, ex,
                PdfmuUtils.sortedMap(new SimpleEntry<String, Object>("outputFile", file)));
    }
}

From source file:utility.pdfRead.java

public void readPdfFromUrl(String url) throws MalformedURLException, Exception {
    URL urlnya = new URL(url);
    String namafile;//  w w w . j  a  va 2  s .c om
    Date d = new Date();
    // kode 
    String dataAkun = "Surat Keterangan Domisili Usaha dari Kelurahan dan Kecamatan yang masih berlaku atau Fotocopy dilegalisir Kecamatan";
    pdfRead myEncryptor = new pdfRead();
    String dataAkunEnkripsi = myEncryptor.encrypt(dataAkun);
    String dataAkunDekripsi = myEncryptor.decrypt(
            "AYxJhAMLk4fftR5XcqYDoUO4GaMY7sNX19k5SRxWWedGj6RB3tSUUmtdx1KHYf19EE1rLonm/3XikRnNoG/Q0rXkbiXO3QXHnmn2douw6SSwrirgYGoHmR3U4wmGUCxXqAERQFd5rdCZcK0CII7sPsb2uiTYqA97");

    System.out.println("Text Asli: " + dataAkun);
    System.out.println("Text Terenkripsi :" + dataAkunEnkripsi);
    System.out.println("Text Terdekripsi :" + dataAkunDekripsi);

    // kode 
    byte[] ba1 = new byte[5 * 1024];
    //        byte[] ba1 = new byte[10*1024];
    int baLength;
    InputStream is1 = null;
    ByteArrayOutputStream bios = new ByteArrayOutputStream();
    ByteArrayOutputStream biosPlusWatermark = new ByteArrayOutputStream();
    ByteArrayOutputStream biosPlusWatermarkQr = new ByteArrayOutputStream();
    AMedia amedia = null;
    try {

        //        report.setSrc(url);
        //            ssl disable
        // Create a trust manager that does not validate certificate chains
        TrustManager[] trustAllCerts = new TrustManager[] { new X509TrustManager() {
            public java.security.cert.X509Certificate[] getAcceptedIssuers() {
                return null;
            }

            public void checkClientTrusted(X509Certificate[] certs, String authType) {
            }

            public void checkServerTrusted(X509Certificate[] certs, String authType) {
            }
        } };

        // Install the all-trusting trust manager
        SSLContext sc = SSLContext.getInstance("SSL");
        sc.init(null, trustAllCerts, new java.security.SecureRandom());
        HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());

        // Create all-trusting host name verifier
        HostnameVerifier allHostsValid = new HostnameVerifier() {
            public boolean verify(String hostname, SSLSession session) {
                return true;
            }
        };

        // Install the all-trusting host verifier
        HttpsURLConnection.setDefaultHostnameVerifier(allHostsValid);

        URLConnection urlConn = urlnya.openConnection();
        try {

            // Read the PDF from the URL and save to a local file
            is1 = urlnya.openStream();
            while ((baLength = is1.read(ba1)) != -1) {
                bios.write(ba1, 0, baLength);
            }
        } catch (Exception e) {
        } finally {

            is1.close();
            bios.close();
        }

        // add watermark
        try {
            PdfReader reader = new PdfReader(bios.toByteArray());
            int n = reader.getNumberOfPages();
            // create a stamper that will copy the document to a new file
            try {
                // Read the PDF from the URL and save to a local file
                is1 = urlnya.openStream();
                while ((baLength = is1.read(ba1)) != -1) {
                    biosPlusWatermark.write(ba1, 0, baLength);
                }
            } catch (Exception e) {
            } finally {

                is1.close();
                biosPlusWatermark.close();
            }

            PdfStamper stamp = new PdfStamper(reader, biosPlusWatermark, '\0', true);
            int i = 0;
            PdfContentByte under;

            Image img = Image.getInstance("img/watermark.png");
            img.setTransparency(new int[] { 0x00, 0x10 });
            img.setAbsolutePosition(0, 0);
            while (i < n) {
                i++;
                under = stamp.getOverContent(i);
                under.addImage(img);
            }
            stamp.close();
        } catch (Exception e) {
            System.out.println("err watermark:" + e);
            amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray());
        }
        // add QRcode
        try {
            PdfReader reader = new PdfReader(biosPlusWatermark.toByteArray());

            int n = reader.getNumberOfPages();
            BarcodeQRCode qrcode = new BarcodeQRCode(dataAkunEnkripsi, 50, 50, null);
            Image image = qrcode.getImage();
            Image mask = qrcode.getImage();
            mask.makeMask();
            image.setImageMask(mask);
            // create a stamper that will copy the document to a new file
            try {
                // Read the PDF from the URL and save to a local file
                is1 = urlnya.openStream();
                while ((baLength = is1.read(ba1)) != -1) {
                    biosPlusWatermarkQr.write(ba1, 0, baLength);
                }
            } catch (Exception e) {
            } finally {
                is1.close();
                biosPlusWatermarkQr.close();
            }

            PdfStamper stamp = new PdfStamper(reader, biosPlusWatermarkQr, '\0', false);
            int i = 0;
            PdfContentByte under;
            Image img = Image.getInstance(image);
            img.setTransparency(new int[] { 0x00, 0x10 });
            img.setAbsolutePosition(0, 0);
            while (i < n) {
                i++;
                under = stamp.getOverContent(i);
                under.addImage(img);
            }
            stamp.close();
            amedia = new AMedia("Dokumen", "pdf", "application/pdf", biosPlusWatermarkQr.toByteArray());
        } catch (Exception e) {
            System.out.println("err qrcode:" + e);
            amedia = new AMedia("Dokumen", "pdf", "application/pdf", bios.toByteArray());
        }

        report.setContent(amedia);

    } catch (Exception e) {
        System.out.println("url tidak dapat diakses");
    }

}