Example usage for com.lowagie.text Rectangle getHeight

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

Introduction

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

Prototype

public float getHeight() 

Source Link

Document

Returns the height of the rectangle.

Usage

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un documento sellado en fichero pdf.
 * //from w w w . j a  v  a2s. c om
 * @param input
 *            Fichero pdf de entrada
 * @param texto
 * @param textoQR
 * @param codFirma
 * @param out
 * @throws ExcepcionErrorInterno
 */
public void firmarPDFSellado(InputStream input, String texto, String texto2Line, String textoQR,
        String codFirma, OutputStream out) throws ExcepcionErrorInterno {
    // leemos el pdf utilizando iText.
    try {
        // Recuperamos el documento original
        PdfReader reader = new PdfReader(input);

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = reader.getPageSize(1);

        // Creamos un nuevo documento del mismo tamao que el original
        Document document = new Document(pageSize);

        // creo una instancia para escritura en el documento
        PdfWriter writer = PdfWriter.getInstance(document, out);
        document.open();

        // Aadimos al documento la imagen de cabecera y de pie
        float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true,
                true);
        altoCabeceraYPie = altoCabeceraYPie + document.topMargin();
        // insertamos la portada del documento que estamos firmando.
        float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage portada = writer.getImportedPage(reader, 1);
        cb.setRGBColorStroke(0xCC, 0xCC, 0xCC);
        cb.transform(AffineTransform.getScaleInstance(escala, escala));
        cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5,
                ALTO_ETIQUETA + document.topMargin()));

        cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy);
        document.close();
        out.close();
    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }
}

From source file:org.webguitoolkit.ui.util.export.PDFEvent.java

License:Apache License

public void onEndPage(PdfWriter writer, Document document) {
    TableExportOptions exportOptions = wgtTable.getExportOptions();
    try {/*from  w w  w.j  a v  a  2s . com*/
        Rectangle page = document.getPageSize();
        if (exportOptions.isShowDefaultHeader() || StringUtils.isNotEmpty(exportOptions.getHeaderImage())) {
            PdfPTable head = new PdfPTable(3);
            head.getDefaultCell().setBorder(Rectangle.NO_BORDER);
            Paragraph title = new Paragraph(wgtTable.getTitle());
            title.setAlignment(Element.ALIGN_LEFT);
            head.addCell(title);

            Paragraph empty = new Paragraph("");
            head.addCell(empty);
            if (StringUtils.isNotEmpty(exportOptions.getHeaderImage())) {
                try {
                    URL absoluteFileUrl = wgtTable.getPage().getClass()
                            .getResource("/" + exportOptions.getHeaderImage());
                    if (absoluteFileUrl != null) {
                        String path = absoluteFileUrl.getPath();
                        Image jpg = Image.getInstance(path);
                        jpg.scaleAbsoluteHeight(40);
                        jpg.scaleAbsoluteWidth(200);
                        head.addCell(jpg);
                    }
                } catch (Exception e) {
                    logger.error(e.getMessage());
                    Paragraph noImage = new Paragraph("Image not found!");
                    head.addCell(noImage);
                }
            } else {
                head.addCell(empty);
            }
            head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
            head.writeSelectedRows(0, -1, document.leftMargin(),
                    page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());
        }

        if (exportOptions.isShowDefaultFooter() || StringUtils.isNotEmpty(exportOptions.getFooterText())
                || exportOptions.isShowPageNumber()) {
            PdfPTable foot = new PdfPTable(3);
            String footerText = exportOptions.getFooterText() != null ? exportOptions.getFooterText() : "";

            if (!exportOptions.isShowDefaultFooter()) {
                foot.addCell(new Paragraph(footerText));
                foot.addCell(new Paragraph(""));
            } else {
                foot.getDefaultCell().setBorder(Rectangle.NO_BORDER);
                String leftText = "";
                if (StringUtils.isNotEmpty(exportOptions.getFooterText())) {
                    leftText = exportOptions.getFooterText();
                }
                Paragraph left = new Paragraph(leftText);
                left.setAlignment(Element.ALIGN_LEFT);
                foot.addCell(left);

                DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM,
                        TextService.getLocale());
                Date today = new Date();
                String date = df.format(today);
                Paragraph center = new Paragraph(date);
                center.setAlignment(Element.ALIGN_CENTER);
                foot.addCell(center);
            }

            if (exportOptions.isShowPageNumber()) {
                Paragraph right = new Paragraph(
                        TextService.getString("pdf.page@Page:") + " " + writer.getPageNumber());
                right.setAlignment(Element.ALIGN_LEFT);
                foot.addCell(right);

                foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin());
                foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                        writer.getDirectContent());
            } else {
                foot.addCell(new Paragraph(""));
            }
        }
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:org.xhtmlrenderer.pdf.ITextUserAgent.java

License:Open Source License

public ImageResource getImageResource(String uriStr) {
    ImageResource resource = null;/*from  www  .j  av  a 2s.  co  m*/
    if (ImageUtil.isEmbeddedBase64Image(uriStr)) {
        resource = loadEmbeddedBase64ImageResource(uriStr);
    } else {
        uriStr = resolveURI(uriStr);
        resource = (ImageResource) _imageCache.get(uriStr);
        if (resource == null) {
            InputStream is = resolveAndOpenStream(uriStr);
            if (is != null) {
                try {
                    URI uri = new URI(uriStr);
                    if (uri.getPath() != null && uri.getPath().toLowerCase().endsWith(".pdf")) {
                        PdfReader reader = _outputDevice.getReader(uri);
                        PDFAsImage image = new PDFAsImage(uri);
                        Rectangle rect = reader.getPageSizeWithRotation(1);
                        image.setInitialWidth(rect.getWidth() * _outputDevice.getDotsPerPoint());
                        image.setInitialHeight(rect.getHeight() * _outputDevice.getDotsPerPoint());
                        resource = new ImageResource(uriStr, image);
                    } else {
                        Image image = Image.getInstance(readStream(is));
                        scaleToOutputResolution(image);
                        resource = new ImageResource(uriStr, new ITextFSImage(image));
                    }
                    _imageCache.put(uriStr, resource);
                } catch (Exception e) {
                    XRLog.exception("Can't read image file; unexpected problem for URI '" + uriStr + "'", e);
                } finally {
                    try {
                        is.close();
                    } catch (IOException e) {
                        // ignore
                    }
                }
            }
        }

        if (resource != null) {
            FSImage image = resource.getImage();
            if (image instanceof ITextFSImage) {
                image = (FSImage) ((ITextFSImage) resource.getImage()).clone();
            }
            resource = new ImageResource(resource.getImageUri(), image);
        } else {
            resource = new ImageResource(uriStr, null);
        }
    }
    return resource;
}

From source file:oscar.eform.util.EFormPDFServlet.java

License:Open Source License

/**
 * the form txt file has lines in the form:
 *
 * For Checkboxes://from ww w . j ava2  s . com
 * ie.  ohip : left, 76, 193, 0, BaseFont.ZAPFDINGBATS, 8, \u2713
 * requestParamName : alignment, Xcoord, Ycoord, 0, font, fontSize, textToPrint[if empty, prints the value of the request param]
 * NOTE: the Xcoord and Ycoord refer to the bottom-left corner of the element
 *
 * For single-line text:
 * ie. patientCity  : left, 242, 261, 0, BaseFont.HELVETICA, 12
 * See checkbox explanation
 *
 * For multi-line text (textarea)
 * ie.  aci : left, 20, 308, 0, BaseFont.HELVETICA, 8, _, 238, 222, 10
 * requestParamName : alignment, bottomLeftXcoord, bottomLeftYcoord, 0, font, fontSize, _, topRightXcoord, topRightYcoord, spacingBtwnLines
 *
 *NOTE: When working on these forms in linux, it helps to load the PDF file into gimp, switch to pt. coordinate system and use the mouse to find the coordinates.
 *Prepare to be bored!
 *
 *
 * @throws Exception 
 */
protected ByteArrayOutputStream generatePDFDocumentBytes(final HttpServletRequest req, final ServletContext ctx,
        int multiple) throws Exception {

    // added by vic, hsfo
    if (HSFO_RX_DATA_KEY.equals(req.getParameter("__title")))
        return generateHsfoRxPDF(req);

    String suffix = (multiple > 0) ? String.valueOf(multiple) : "";

    ByteArrayOutputStream baosPDF = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter writer = null;
    try {
        writer = PdfWriter.getInstance(document, baosPDF);

        String title = req.getParameter("__title" + suffix) != null ? req.getParameter("__title" + suffix)
                : "Unknown";
        String template = req.getParameter("__template" + suffix) != null
                ? req.getParameter("__template" + suffix) + ".pdf"
                : "";

        int numPages = 1;
        String pages = req.getParameter("__numPages" + suffix);
        if (pages != null) {
            numPages = Integer.parseInt(pages);
        }

        //load config files
        Properties[] printCfg = loadPrintCfg(req, suffix);
        Properties[][] graphicCfg = loadGraphicCfg(req, suffix, numPages);
        int cfgFileNo = printCfg == null ? 0 : printCfg.length;

        Properties props = new Properties();
        getPrintPropValues(props, req, suffix);

        Properties measurements = new Properties();

        //initialise measurement collections = a list of pages sections measurements
        List<List<List<String>>> xMeasurementValues = new ArrayList<List<List<String>>>();
        List<List<List<String>>> yMeasurementValues = new ArrayList<List<List<String>>>();
        for (int idx = 0; idx < numPages; ++idx) {
            MiscUtils.getLogger().debug("Adding page " + idx);
            xMeasurementValues.add(new ArrayList<List<String>>());
            yMeasurementValues.add(new ArrayList<List<String>>());
        }

        saveMeasurementValues(measurements, props, req, numPages, xMeasurementValues, yMeasurementValues);
        addDocumentProps(document, title, props);

        // create a reader for a certain document
        String propFilename = OscarProperties.getInstance().getProperty("eform_image", "") + "/" + template;
        PdfReader reader = null;

        try {
            reader = new PdfReader(propFilename);
            log.debug("Found template at " + propFilename);
        } catch (Exception dex) {
            log.warn("Cannot find template at : " + propFilename);
        }

        // retrieve the total number of pages
        int n = reader.getNumberOfPages();
        // retrieve the size of the first page
        Rectangle pSize = reader.getPageSize(1);
        float height = pSize.getHeight();

        PdfContentByte cb = writer.getDirectContent();
        int i = 0;

        while (i < n) {
            document.newPage();

            i++;
            PdfImportedPage page1 = writer.getImportedPage(reader, i);
            cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);

            cb.setRGBColorStroke(0, 0, 255);
            // LEFT/CENTER/RIGHT, X, Y,

            if (i <= cfgFileNo) {
                writeContent(printCfg[i - 1], props, measurements, height, cb);
            } //end if there are print properties

            //graphic
            Properties[] tempPropertiesArray;
            if (i <= graphicCfg.length) {
                tempPropertiesArray = graphicCfg[i - 1];
                MiscUtils.getLogger().debug("Plotting page " + i);
            } else {
                tempPropertiesArray = null;
                MiscUtils.getLogger().debug("Skipped Plotting page " + i);
            }

            //if there are properties to plot
            if (tempPropertiesArray != null) {
                MiscUtils.getLogger().debug("TEMP PROP LENGTH " + tempPropertiesArray.length);
                for (int k = 0; k < tempPropertiesArray.length; k++) {

                    //initialise with measurement values which are mapped to config file by form get graphic function
                    List<String> xDate, yHeight;
                    if (xMeasurementValues.get(i - 1).size() > k && yMeasurementValues.get(i - 1).size() > k) {
                        xDate = new ArrayList<String>(xMeasurementValues.get(i - 1).get(k));
                        yHeight = new ArrayList<String>(yMeasurementValues.get(i - 1).get(k));
                    } else {
                        xDate = new ArrayList<String>();
                        yHeight = new ArrayList<String>();
                    }
                    plotProperties(tempPropertiesArray[k], props, xDate, yHeight, height, cb, (k % 2 == 0));
                }
            } //end: if there are properties to plot
        }
    } finally {
        if (document.isOpen())
            document.close();
        if (writer != null)
            writer.close();
    }
    return baosPDF;
}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.EctConsultationFormRequestPrintPdf.java

License:Open Source License

public void printPdf() throws IOException, DocumentException {

    EctConsultationFormRequestUtil reqForm = new EctConsultationFormRequestUtil();
    reqForm.estRequestFromId((String) request.getAttribute("reqId"));

    //make sure we have data to print
    if (reqForm == null)
        throw new DocumentException();

    // init req form info
    reqForm.specAddr = request.getParameter("address");
    if (reqForm.specAddr == null) {
        reqForm.specAddr = new String();
    }/*w  ww .  j  a va 2  s .co  m*/
    reqForm.specPhone = request.getParameter("phone");
    if (reqForm.specPhone == null) {
        reqForm.specPhone = "";
    }
    reqForm.specFax = request.getParameter("fax");
    if (reqForm.specFax == null) {
        reqForm.specFax = "";
    }

    //Create new file to save form to
    String path = OscarProperties.getInstance().getProperty("DOCUMENT_DIR");
    String fileName = path + "ConsultationRequestForm-" + UtilDateUtilities.getToday("yyyy-MM-dd.hh.mm.ss")
            + ".pdf";
    FileOutputStream out = new FileOutputStream(fileName);

    //Create the document we are going to write to
    document = new Document();
    writer = PdfWriter.getInstance(document, out);

    //Use the template located at '/oscar/oscarEncounter/oscarConsultationRequest/props'
    reader = new PdfReader("/oscar/oscarEncounter/oscarConsultationRequest/props/consultationFormRequest.pdf");
    Rectangle pSize = reader.getPageSize(1);
    width = pSize.getWidth();
    height = pSize.getHeight();
    document.setPageSize(pSize);

    document.addTitle("Consultation Form Request");
    document.addCreator("OSCAR");
    document.open();

    //Create the font we are going to print to
    bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

    cb = writer.getDirectContent();
    ct = new ColumnText(cb);
    cb.setColorStroke(new Color(0, 0, 0));

    // start writing the pdf document
    PdfImportedPage page1 = writer.getImportedPage(reader, 1);
    cb.addTemplate(page1, 1, 0, 0, 1, 0, 0);
    addFooter();
    setAppointmentInfo(reqForm);

    // add the dynamically positioned text elements
    float dynamicHeight = 0;
    dynamicHeight = addDynamicPositionedText("Reason For Consultation: ", reqForm.reasonForConsultation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Pertinent Clinical Information: ", reqForm.clinicalInformation,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Significant Concurrent Problems: ", reqForm.concurrentProblems,
            dynamicHeight, reqForm);
    dynamicHeight = addDynamicPositionedText("Current Medications: ", reqForm.currentMedications, dynamicHeight,
            reqForm);
    dynamicHeight = addDynamicPositionedText("Allergies: ", reqForm.allergies, dynamicHeight, reqForm);

    document.close();
    reader.close();
    writer.close();
    out.close();

    // combine the recently created pdf with any pdfs that were added to the consultation request form
    combinePDFs(fileName);

}

From source file:oscar.oscarLab.ca.all.pageUtil.LabPDFCreator.java

License:Open Source License

public void onEndPage(PdfWriter writer, Document document) {
    try {/*w ww.  j  a  v a  2s .  co m*/

        Rectangle page = document.getPageSize();
        PdfContentByte cb = writer.getDirectContent();
        BaseFont bf = BaseFont.createFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        int pageNum = document.getPageNumber();
        float width = page.getWidth();
        float height = page.getHeight();

        //add patient name header for every page but the first.
        if (pageNum > 1) {
            cb.beginText();
            cb.setFontAndSize(bf, 8);
            cb.showTextAligned(PdfContentByte.ALIGN_RIGHT, handler.getPatientName(), 575, height - 30, 0);
            cb.endText();

        }

        //add footer for every page
        cb.beginText();
        cb.setFontAndSize(bf, 8);
        cb.showTextAligned(PdfContentByte.ALIGN_CENTER, "-" + pageNum + "-", width / 2, 30, 0);
        cb.endText();

        // add promotext as footer if it is enabled
        if (OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT") != null) {
            cb.beginText();
            cb.setFontAndSize(BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED),
                    6);
            cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                    OscarProperties.getInstance().getProperty("FORMS_PROMOTEXT"), width / 2, 19, 0);
            cb.endText();
        }

        // throw any exceptions
    } catch (Exception e) {
        throw new ExceptionConverter(e);
    }
}

From source file:questions.importpages.NameCard.java

public static void createOneCard() throws DocumentException, IOException {
    Rectangle rect = new Rectangle(Utilities.millimetersToPoints(86.5f), Utilities.millimetersToPoints(55));
    Document document = new Document(rect);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(CARD));
    writer.setViewerPreferences(PdfWriter.PrintScalingNone);
    document.open();//w  w w .j  a  v a2s .  c om
    PdfReader reader = new PdfReader(LOGO);
    Image img = Image.getInstance(writer.getImportedPage(reader, 1));
    img.scaleToFit(rect.getWidth() / 1.5f, rect.getHeight() / 1.5f);
    img.setAbsolutePosition((rect.getWidth() - img.getScaledWidth()) / 2,
            (rect.getHeight() - img.getScaledHeight()) / 2);
    document.add(img);
    document.newPage();
    BaseFont bf = BaseFont.createFont(FONT, BaseFont.WINANSI, BaseFont.NOT_EMBEDDED);
    Font font = new Font(bf, 12);
    font.setColor(new CMYKColor(1, 0.5f, 0, 0.467f));
    ColumnText column = new ColumnText(writer.getDirectContent());
    Paragraph p;
    p = new Paragraph("Bruno Lowagie\n1T3XT\nbruno@1t3xt.com", font);
    p.setAlignment(Element.ALIGN_CENTER);
    column.addElement(p);
    column.setSimpleColumn(0, 0, rect.getWidth(), rect.getHeight() * 0.75f);
    column.go();
    document.close();
}

From source file:questions.importpages.NameCards.java

public static void createSheet(int p) throws DocumentException, IOException {
    Rectangle rect = new Rectangle(PageSize.A4);
    Document document = new Document(rect);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(SHEET[p - 1]));
    document.open();/*from ww  w .ja v  a  2  s .  co m*/
    PdfContentByte canvas = writer.getDirectContentUnder();
    PdfReader reader = new PdfReader(NameCard.CARD);
    PdfImportedPage front = writer.getImportedPage(reader, p);
    float x = rect.getWidth() / 2 - front.getWidth();
    float y = (rect.getHeight() - (front.getHeight() * 5)) / 2;
    canvas.setLineWidth(0.5f);
    canvas.moveTo(x, y - 15);
    canvas.lineTo(x, y);
    canvas.lineTo(x - 15, y);
    canvas.moveTo(x + front.getWidth(), y - 15);
    canvas.lineTo(x + front.getWidth(), y);
    canvas.moveTo(x + front.getWidth() * 2, y - 15);
    canvas.lineTo(x + front.getWidth() * 2, y);
    canvas.lineTo(x + front.getWidth() * 2 + 15, y);
    canvas.stroke();
    for (int i = 0; i < 5; i++) {
        for (int j = 0; j < 2; j++) {
            canvas.addTemplate(front, x, y);
            x += front.getWidth();
        }
        x = rect.getWidth() / 2 - front.getWidth();
        y += front.getHeight();
        canvas.moveTo(x, y);
        canvas.lineTo(x - 15, y);
        canvas.moveTo(x + front.getWidth() * 2, y);
        canvas.lineTo(x + front.getWidth() * 2 + 15, y);
        canvas.stroke();
    }
    canvas.moveTo(x, y + 15);
    canvas.lineTo(x, y);
    canvas.moveTo(x + front.getWidth(), y + 15);
    canvas.lineTo(x + front.getWidth(), y);
    canvas.moveTo(x + front.getWidth() * 2, y + 15);
    canvas.lineTo(x + front.getWidth() * 2, y);
    canvas.stroke();
    document.close();
}

From source file:questions.ocg.AddOptionalWatermark.java

public static void main(String[] args) throws DocumentException, IOException {
    PdfReader reader = new PdfReader(RESOURCE);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(RESULT));
    Image image1 = Image.getInstance(IMAGE_PRINTED);
    Image image2 = Image.getInstance(IMAGE_NOT_PRINTED);
    PdfLayer watermark_printed = new PdfLayer("printed", stamper.getWriter());
    watermark_printed.setOn(false);//from   w ww .j  av a 2 s. c om
    watermark_printed.setOnPanel(false);
    watermark_printed.setPrint("print", true);
    PdfLayer watermark_not_printed = new PdfLayer("not_printed", stamper.getWriter());
    watermark_not_printed.setOn(true);
    watermark_not_printed.setOnPanel(false);
    watermark_not_printed.setPrint("print", false);
    for (int i = 0; i < stamper.getReader().getNumberOfPages();) {
        PdfContentByte cb = stamper.getUnderContent(++i);
        Rectangle rectangle = stamper.getReader().getPageSizeWithRotation(i);
        cb.beginLayer(watermark_printed);
        float AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image1.getPlainWidth()) / 2;
        float AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image1.getPlainHeight()) / 2;
        image1.setAbsolutePosition(AbsoluteX, AbsoluteY);
        cb.addImage(image1);
        cb.endLayer();
        cb.beginLayer(watermark_not_printed);
        AbsoluteX = rectangle.getLeft() + (rectangle.getWidth() - image2.getPlainWidth()) / 2;
        AbsoluteY = rectangle.getBottom() + (rectangle.getHeight() - image2.getPlainHeight()) / 2;
        image2.setAbsolutePosition(AbsoluteX, AbsoluteY);
        cb.addImage(image2);
        cb.endLayer();
    }
    stamper.close();
}

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