Example usage for com.lowagie.text.pdf PdfDictionary put

List of usage examples for com.lowagie.text.pdf PdfDictionary put

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfDictionary put.

Prototype

public void put(PdfName key, PdfObject object) 

Source Link

Document

Associates the specified PdfObject as value with the specified PdfName as key in this map.

Usage

From source file:questions.images.TransparentEllipse2.java

public static void main(String[] args) {

    Document document = new Document(PageSize.POSTCARD);
    try {/*  w w w.  java2s .c  om*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        PdfContentByte cb = writer.getDirectContent();

        // clipped image
        cb.ellipse(1, 1, PageSize.POSTCARD.getWidth() - 2, PageSize.POSTCARD.getHeight() - 2);
        cb.clip();
        cb.newPath();
        Image img = Image.getInstance(RESOURCE);
        img.scaleToFit(PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
        cb.addImage(img, PageSize.POSTCARD.getWidth(), 0, 0, PageSize.POSTCARD.getHeight(), 0, 0);

        //Prepare gradation list
        int gradationStep = 40;
        float[] gradationRatioList = new float[gradationStep];
        for (int i = 0; i < gradationStep; i++) {
            gradationRatioList[i] = 1 - (float) Math.sin(Math.toRadians(90.0f / gradationStep * (i + 1)));
        }

        //Create template
        PdfTemplate template = cb.createTemplate(PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());

        //Prepare transparent group
        PdfTransparencyGroup transGroup = new PdfTransparencyGroup();
        transGroup.put(PdfName.CS, PdfName.DEVICEGRAY);
        transGroup.setIsolated(true);
        transGroup.setKnockout(false);
        template.setGroup(transGroup);

        //Prepare graphic state
        PdfGState gState = new PdfGState();
        PdfDictionary maskDict = new PdfDictionary();
        maskDict.put(PdfName.TYPE, PdfName.MASK);
        maskDict.put(PdfName.S, new PdfName("Luminosity"));
        maskDict.put(new PdfName("G"), template.getIndirectReference());
        gState.put(PdfName.SMASK, maskDict);
        cb.setGState(gState);

        //Create gradation for mask
        for (int i = 1; i < gradationStep + 1; i++) {
            template.setLineWidth(gradationStep + 1 - i);
            template.setGrayStroke(gradationRatioList[gradationStep - i]);
            template.ellipse(0, 0, PageSize.POSTCARD.getWidth(), PageSize.POSTCARD.getHeight());
            template.stroke();
        }

        //Place template
        cb.addTemplate(template, 0, 0);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    document.close();
}

From source file:questions.importpages.ExportArea.java

public static void main(String[] args) {
    try {/*from   w w w .  j a v a  2 s  . co  m*/
        PdfReader reader = new PdfReader(SOURCE);
        PdfDictionary pagedict = reader.getPageN(1);
        PdfRectangle rect = new PdfRectangle(45, 610, 603, 906);
        pagedict.put(PdfName.MEDIABOX, rect);
        pagedict.put(PdfName.CROPBOX, rect);
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.javascript.AddJavaScriptToForm.java

public static void addJavaScript(String input, String output) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(input);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(output));
    stamper.getWriter()/*from   w  ww  . ja va  2  s.c o m*/
            .addJavaScript("function setReadOnly(readonly) {" + "var partner = this.getField('partner');"
                    + "if(readonly) {" + "partner.value = '';" + "}" + "partner.readonly = readonly;" + " }"
                    + "function validate() {" + "var married = this.getField('married');"
                    + "var partner = this.getField('partner');"
                    + "if (married.value == 'yes' && partner.value == '') {"
                    + "app.alert('please enter the name of your partner');" + "}" + "else {"
                    + "this.submitForm({" + " cURL:\"http://1t3xt.info/examples/request.php\","
                    + " cSubmitAs: \"HTML\"" + "});" + "}" + " }");
    AcroFields form = stamper.getAcroFields();
    Item fd = form.getFieldItem("married");

    PdfDictionary dictYes = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(0));
    PdfDictionary yesAction = dictYes.getAsDict(PdfName.AA);
    if (yesAction == null)
        yesAction = new PdfDictionary();
    yesAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(false);", stamper.getWriter()));
    dictYes.put(PdfName.AA, yesAction);

    PdfDictionary dictNo = (PdfDictionary) PdfReader.getPdfObject((PdfObject) fd.getWidgetRef(1));
    PdfDictionary noAction = dictNo.getAsDict(PdfName.AA);
    if (noAction == null)
        noAction = new PdfDictionary();
    noAction.put(new PdfName("Fo"), PdfAction.javaScript("setReadOnly(true);", stamper.getWriter()));
    dictNo.put(PdfName.AA, noAction);

    PdfWriter writer = stamper.getWriter();
    PushbuttonField button = new PushbuttonField(writer, new Rectangle(40, 690, 200, 710), "submit");
    button.setText("validate and submit");
    button.setOptions(PushbuttonField.VISIBLE_BUT_DOES_NOT_PRINT);
    PdfFormField validateAndSubmit = button.getField();
    validateAndSubmit.setAction(PdfAction.javaScript("validate();", stamper.getWriter()));
    stamper.addAnnotation(validateAndSubmit, 1);

    stamper.close();
}

From source file:questions.markedcontent.ObjectData.java

public static void main(String[] args) {
    Document document = new Document(PageSize.A5.rotate());
    try {/*ww w  . j  a  v a2  s. c o  m*/
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        writer.setTagged();

        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfStructureTreeRoot tree = writer.getStructureTreeRoot();
        PdfStructureElement se = new PdfStructureElement(tree, new PdfName("Figure"));
        PdfStructureElement element = new PdfStructureElement(se, new PdfName("Element"));
        PdfDictionary userproperties = new PdfDictionary();
        userproperties.put(PdfName.O, PdfName.USERPROPERTIES);
        userproperties.put(PdfName.S, new PdfName("Figure"));
        PdfArray properties = new PdfArray();
        PdfDictionary property1 = new PdfDictionary();
        property1.put(PdfName.N, new PdfString("Name1"));
        property1.put(PdfName.V, new PdfString("Value1"));
        properties.add(property1);
        PdfDictionary property2 = new PdfDictionary();
        property2.put(PdfName.N, new PdfString("Name2"));
        property2.put(PdfName.V, new PdfString("Value2"));
        properties.add(property2);
        PdfDictionary property3 = new PdfDictionary();
        property3.put(PdfName.N, new PdfString("Name3"));
        property3.put(PdfName.V, new PdfString("Value3"));
        properties.add(property3);
        userproperties.put(PdfName.P, properties);
        element.put(PdfName.A, userproperties);

        PdfLayer lay1 = new PdfLayer("My object", writer);

        cb.beginMarkedContentSequence(element);
        cb.beginLayer(lay1);
        cb.setColorFill(Color.BLUE);
        cb.rectangle(50, 50, 200, 200);
        cb.fill();
        cb.endLayer();
        cb.endMarkedContentSequence();

    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    document.close();

}

From source file:questions.stamppages.AddCropbox.java

public static void main(String[] args) {
    try {/*  w w w  .  j  a v a 2 s. c o  m*/
        PdfImportedPage page;
        PdfDictionary pageDict;
        PdfReader reader = new PdfReader(RESOURCE);
        Document document = new Document(reader.getPageSizeWithRotation(1));
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT2));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            page = writer.getImportedPage(reader, 1);
            cb.rectangle(0, 52, 612, 668);
            cb.clip();
            cb.newPath();
            cb.addTemplate(page, 0, 0);
            pageDict = reader.getPageN(i);
            PdfArray crop = new PdfRectangle(0, 52, 612, 720);
            pageDict.put(PdfName.CROPBOX, crop);
        }
        document.close();
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT1));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:questions.stamppages.IncreaseMediabox.java

public static void main(String[] args) {
    try {//  www.  ja v  a  2 s .  c  o m
        PdfDictionary pageDict;
        PdfReader reader = new PdfReader(RESOURCE);
        int n = reader.getNumberOfPages();
        for (int i = 1; i <= n; i++) {
            Rectangle rect = reader.getPageSize(i);
            pageDict = reader.getPageN(i);
            PdfRectangle pdfrect = new PdfRectangle(rect.getLeft(-36), rect.getBottom(-36), rect.getRight(-36),
                    rect.getTop(-36));
            pageDict.put(PdfName.MEDIABOX, pdfrect);
        }
        PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
        stamper.close();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
}

From source file:si.vsrs.cif.svev.example.utils.PDFSignature.java

License:EUPL

public File signPDF(File document, InputStream keystore, String password, String keyPassord,
        String keystoreType, String alias, boolean bshowVisualization) {
    if (document == null || !document.exists()) {
        throw new RuntimeException("Error reading pdf");
    }//  w  w  w  .  jav a 2  s .  c o  m

    String name = document.getName();
    String substring = name.substring(0, name.lastIndexOf("."));

    File outputDocument = new File(document.getParent(), substring + "_signed.pdf");

    try (FileInputStream fis = new FileInputStream(document);
            FileOutputStream fout = new FileOutputStream(outputDocument)) {

        KeyStore ks = KeyStore.getInstance(keystoreType);
        ks.load(keystore, password.toCharArray());
        PrivateKey key = (PrivateKey) ks.getKey(alias, keyPassord.toCharArray());
        Certificate[] chain = ks.getCertificateChain(alias);
        X509Certificate xcert = (X509Certificate) chain[0];
        PdfReader reader = new PdfReader(fis);

        char tmpPdfVersion = '\0'; // default version - the same as input
        final PdfStamper stp = PdfStamper.createSignature(reader, fout, tmpPdfVersion, null, true);
        final PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        sap.setReason("Testni podpis");
        sap.setLocation("Maribor");
        sap.setContact(xcert.getSubjectDN().getName());

        //            sap.setLayer2Text("");
        //          sap.setLayer4Text("");
        sap.setAcro6Layers(true); // --:> 

        Rectangle rc = reader.getPageSize(1);
        if (bshowVisualization) {
            sap.setVisibleSignature(new Rectangle(5, rc.getHeight() - 40, 240, rc.getHeight() - 5), 1, null);
        }

        final PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));

        dic.setReason(sap.getReason());
        dic.setLocation(sap.getLocation());
        dic.setContact(sap.getContact());
        dic.setDate(new PdfDate(sap.getSignDate()));
        sap.setCryptoDictionary(dic);
        final int contentEstimated = 15000;
        final HashMap<PdfName, Integer> exc = new HashMap<>();
        exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2);
        sap.preClose(exc);

        PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA-256", null, false);
        InputStream data = sap.getRangeStream();
        final MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
        byte buf[] = new byte[8192];
        int n;
        while ((n = data.read(buf)) > 0) {
            messageDigest.update(buf, 0, n);
        }
        byte hash[] = messageDigest.digest();
        Calendar cal = Calendar.getInstance();

        byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, null);
        sgn.update(sh, 0, sh.length);

        byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, null, null);

        byte[] paddedSig = new byte[contentEstimated];
        System.arraycopy(encodedSig, 0, paddedSig, 0, encodedSig.length);

        PdfDictionary dic2 = new PdfDictionary();
        dic2.put(PdfName.CONTENTS, new PdfString(paddedSig).setHexWriting(true));

        sap.close(dic2);
    } catch (IOException | KeyStoreException | NoSuchAlgorithmException | CertificateException
            | UnrecoverableKeyException | DocumentException | InvalidKeyException | NoSuchProviderException
            | SignatureException ex) {
        throw new RuntimeException(ex.getMessage(), ex);
    }

    return outputDocument;
}