Example usage for com.lowagie.text Rectangle Rectangle

List of usage examples for com.lowagie.text Rectangle Rectangle

Introduction

In this page you can find the example usage for com.lowagie.text Rectangle Rectangle.

Prototype

public Rectangle(float llx, float lly, float urx, float ury) 

Source Link

Document

Constructs a Rectangle -object.

Usage

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 ww w . ja v a 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.javascript.TriggerMenuButtons.java

public static final void main(String[] args) {
    Document document = new Document();
    try {//from  w  ww  .j  ava 2s  .co  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESULT));
        document.open();
        document.add(new Paragraph("Triggering Menu Items"));
        PushbuttonField saveAs = new PushbuttonField(writer, new Rectangle(40, 760, 100, 780), "Save");
        saveAs.setBorderColor(Color.BLACK);
        saveAs.setText("Save");
        saveAs.setTextColor(Color.RED);
        saveAs.setLayout(PushbuttonField.LAYOUT_LABEL_ONLY);
        PdfFormField saveAsButton = saveAs.getField();
        saveAsButton.setAction(PdfAction.javaScript("app.execMenuItem('SaveAs')", writer));
        writer.addAnnotation(saveAsButton);
        PushbuttonField mail = new PushbuttonField(writer, new Rectangle(120, 760, 180, 780), "Mail");
        mail.setBorderColor(Color.BLACK);
        mail.setText("Mail");
        mail.setTextColor(Color.RED);
        mail.setLayout(PushbuttonField.LAYOUT_LABEL_ONLY);
        PdfFormField mailButton = mail.getField();
        mailButton.setAction(PdfAction.javaScript("app.execMenuItem('AcroSendMail:SendMail')", writer));
        writer.addAnnotation(mailButton);
    } catch (IOException e) {
        e.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    }
    document.close();
}

From source file:questions.ocg.StatusBars1.java

public Image getImage(PdfContentByte cb, int i) throws BadElementException {
    PdfTemplate tmp = cb.createTemplate(100, 10);
    tmp.setBoundingBox(new Rectangle(-5, -2, 105, 12));
    Rectangle r = new Rectangle(0, 0, 100, 10);
    tmp.rectangle(r);//from w w  w  . jav a  2 s. c  o m
    r = new Rectangle(0, 0, i, 10);
    tmp.beginLayer(colorLayerColored);
    if (i % 2 == 0)
        r.setBackgroundColor(Color.RED);
    else
        r.setBackgroundColor(Color.GREEN);
    tmp.rectangle(r);
    tmp.endLayer();
    tmp.beginLayer(colorLayerGreyed);
    r = new Rectangle(0, 0, i, 10);
    if (i % 2 == 0)
        r.setBackgroundColor(new GrayColor(10));
    else
        r.setBackgroundColor(new GrayColor(97));
    tmp.rectangle(r);
    tmp.endLayer();
    return Image.getInstance(tmp);
}

From source file:questions.stamppages.RemoveAttachmentAnnotations.java

public static void createPdfWithAttachments() throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(RESOURCE));
    document.open();/*from  w  ww  .j av a  2 s .co  m*/
    document.add(new Paragraph("page 1"));
    writer.addAnnotation(PdfAnnotation.createFileAttachment(writer, new Rectangle(100f, 780f, 120f, 800f),
            "This is some text", "some text".getBytes(), null, "some.txt"));
    writer.addAnnotation(PdfAnnotation.createText(writer, new Rectangle(100f, 750f, 120f, 770f), "Help",
            "This Help annotation was made with 'createText'", false, "Help"));
    document.newPage();
    document.add(new Paragraph("page 2"));
    document.newPage();
    document.add(new Paragraph("page 3"));
    PdfFileSpecification fs1 = PdfFileSpecification.fileEmbedded(writer, TXT, "caesar.txt", null);
    writer.addAnnotation(
            PdfAnnotation.createFileAttachment(writer, new Rectangle(100f, 780f, 120f, 800f), "Caesar", fs1));
    PdfFileSpecification fs2 = PdfFileSpecification.fileEmbedded(writer, IMG, "1t3xt.gif", null);
    writer.addAnnotation(
            PdfAnnotation.createFileAttachment(writer, new Rectangle(100f, 750f, 120f, 770f), "1t3xt", fs2));
    document.close();
}

From source file:questions.tables.AddTableAsHeaderFooter.java

public void onOpenDocument(PdfWriter writer, Document document) {
    try {/*from w  ww  .j  a  va2s  .  c o m*/
        // initializations
        tpl = writer.getDirectContent().createTemplate(150, 18);
        Rectangle rect = new Rectangle(0, 0, 150, 18);
        rect.setBackgroundColor(Color.GRAY);
        tpl.setBoundingBox(rect);
        tpl.rectangle(rect);
        helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false);
        // header
        headerTable = new PdfPTable(1);
        PdfPCell cell = new PdfPCell(new Paragraph("Header Text"));
        headerTable.addCell(cell);
        headerTable.setTotalWidth(document.right() - document.left());
        headerTable.setLockedWidth(true);
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:questions.tables.AlternateBackground.java

public void tableLayout(PdfPTable table, float[][] widths, float[] heights, int headerRows, int rowStart,
        PdfContentByte[] canvases) {/* w  w  w  .  ja va2  s.c o m*/
    int rows = widths.length;
    int columns;
    Rectangle rect;
    for (int row = headerRows + 1; row < rows; row += 2) {
        columns = widths[row].length - 1;
        rect = new Rectangle(widths[row][0], heights[row], widths[row][columns], heights[row + 1]);
        rect.setBackgroundColor(Color.YELLOW);
        rect.setBorder(Rectangle.NO_BORDER);
        canvases[PdfPTable.BACKGROUNDCANVAS].rectangle(rect);

    }
}

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");
    }//from w w  w. j  a v  a 2s.  c  om

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

From source file:songscribe.ui.mainframeactions.ExportPDFAction.java

License:Open Source License

public static void createPDF(Data data, File outputFile, Boolean isGUI) {
    float resolution = 72f / MusicSheet.RESOLUTION;
    float paperWidth = data.paperWidth * resolution;
    float paperHeight = data.paperHeight * resolution;
    MainFrame mainFrame = data.mainFrame;
    Document document = new Document(new Rectangle(0, 0, paperWidth, paperHeight), 0, 0, 0, 0);
    document.addCreator(mainFrame.PROG_NAME);
    document.addTitle(mainFrame.getMusicSheet().getComposition().getSongTitle());

    // Scale to fit
    int sheetWidth = mainFrame.getMusicSheet().getSheetWidth();
    int sheetHeight = mainFrame.getMusicSheet().getSheetHeight();
    double horizontalMargin = (data.leftInnerMargin + data.rightOuterMargin) * resolution;
    double horizontalScale = (paperWidth - horizontalMargin) / sheetWidth;
    double verticalMargin = (data.topMargin + data.bottomMargin) * resolution;
    double verticalScale = (paperHeight - verticalMargin) / sheetHeight;
    double scale;
    double leftMargin = data.leftInnerMargin * resolution;

    if (horizontalScale < verticalScale) {
        scale = horizontalScale;/*from   w  ww  .j av a2  s  .c  o m*/
    } else {
        // If scaling vertically, the horizontal margin will be larger than
        // what is specified in Data. So we calculate the total margin available,
        // then give the left margin the same fraction of the total margin
        // it would have had before scaling.
        scale = verticalScale;
        double scaledMargin = paperWidth - (sheetWidth * scale);
        double leftMarginFactor = (double) data.leftInnerMargin
                / (double) (data.leftInnerMargin + data.rightOuterMargin);
        leftMargin = scaledMargin * leftMarginFactor;
    }

    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        Graphics2D g2 = cb.createGraphicsShapes(paperWidth, paperHeight);
        g2.translate(leftMargin, data.topMargin * resolution);
        mainFrame.getMusicSheet().getBestDrawer().drawMusicSheet(g2, false, scale);
        g2.dispose();
        document.close();

        if (isGUI) {
            Utilities.openExportFile(mainFrame, outputFile);
        }
    } catch (DocumentException e1) {
        if (isGUI) {
            mainFrame.showErrorMessage("An unexpected error occurred and could not export as PDF.");
        }

        logger.error("PDF save", e1);
    } catch (FileNotFoundException e1) {
        if (isGUI) {
            mainFrame.showErrorMessage(MainFrame.COULD_NOT_SAVE_MESSAGE);
        }

        logger.error("PDF save", e1);
    }
}