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

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

Introduction

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

Prototype

public void setMoreInfo(final Map<String, String> moreInfo) 

Source Link

Document

An optional String map to add or change values in the info dictionary.

Usage

From source file:SignPDF.java

License:Open Source License

public static void main(String args[]) {
    try {/*from ww  w . j a v a  2s.  c o m*/

        if (args.length != 1) {
            System.err.println("usage: $0 <pdf-file>");
            System.exit(1);
        }
        src = args[0];
        dest = src + ".temp";

        rcname = System.getenv("SIGNPDFRC");
        if (rcname == null || rcname.length() == 0)
            rcname = System.getenv("HOME") + "/.signpdf";
        else
            System.out.println("using SIGNPDFRC=" + rcname);

        if (!getProperties())
            createDefaultProperties();

        KeyStore ks = KeyStore.getInstance(KeyStore.getDefaultType());
        ks.load(new FileInputStream(path), keystore_password.toCharArray());
        if (alias == null || alias.length() == 0)
            alias = (String) ks.aliases().nextElement();
        Certificate[] chain = ks.getCertificateChain(alias);
        PrivateKey key = (PrivateKey) ks.getKey(alias, key_password.toCharArray());

        X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
        System.out.println("Signer ID serial     " + cert.getSerialNumber());
        System.out.println("Signer ID version    " + cert.getVersion());
        System.out.println("Signer ID issuer     " + cert.getIssuerDN());
        System.out.println("Signer ID not before " + cert.getNotBefore());
        System.out.println("Signer ID not after  " + cert.getNotAfter());

        // show days valid
        long ticks_now = new Date().getTime();
        long ticks_to = cert.getNotAfter().getTime();

        long ticks_delta = (ticks_to - ticks_now) / TICKS_PER_DAY;
        System.out.println("Certificate will expire in " + ticks_delta + " days.");

        Signature s = Signature.getInstance("SHA1withRSA");
        s.initVerify(ks.getCertificate(alias));

        try {
            cert.checkValidity();
            System.out.println("Validation check passed.");
        } catch (Exception e) {
            System.out.println("Certificate expired or invalid. Abroting.");
            System.exit(1);
        }

        PdfReader reader = new PdfReader(src);
        FileOutputStream os = new FileOutputStream(dest);
        //PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0', null, false);
        PdfStamper stamper = PdfStamper.createSignature(reader, os, '\0');
        stamper.setEncryption(true, null, null,
                PdfWriter.ALLOW_PRINTING | PdfWriter.ALLOW_SCREENREADERS | PdfWriter.ALLOW_COPY);

        HashMap<String, String> info = reader.getInfo();
        info.put("Creator", "SingPDF " + version);
        stamper.setMoreInfo(info);

        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();

        appearance.setReason(reason);
        appearance.setLocation(location);
        appearance.setContact(contact);
        appearance.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED);
        appearance.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);

        /// ts + ocsp
        PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
        dic.setReason(appearance.getReason());
        dic.setLocation(appearance.getLocation());
        dic.setContact(appearance.getContact());
        dic.setDate(new PdfDate(appearance.getSignDate()));
        appearance.setCryptoDictionary(dic);

        // timestamping + ocsp

        if (tsa_url != null && tsa_url.length() > 0) {

            byte[] ocsp = null;
            TSAClient tsc = null;

            int contentEstimated = 15000;
            HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
            exc.put(PdfName.CONTENTS, new Integer(contentEstimated * 2 + 2));
            appearance.preClose(exc);

            InputStream data = appearance.getRangeStream();
            MessageDigest mdig = MessageDigest.getInstance("SHA1");

            byte buf[] = new byte[8192];
            int n;
            while ((n = data.read(buf)) > 0) {
                mdig.update(buf, 0, n);
            }

            if (root_cert != null && root_cert.length() > 0) {
                String url = PdfPKCS7.getOCSPURL((X509Certificate) chain[0]);
                CertificateFactory cf = CertificateFactory.getInstance("X509");
                FileInputStream is = new FileInputStream(root_cert);
                X509Certificate root = (X509Certificate) cf.generateCertificate(is);
                ocsp = new OcspClientBouncyCastle().getEncoded((X509Certificate) chain[0], root, url);
            }

            byte hash[] = mdig.digest();
            Calendar cal = Calendar.getInstance();
            PdfPKCS7 sgn = new PdfPKCS7(key, chain, null, "SHA1", null, false);
            byte sh[] = sgn.getAuthenticatedAttributeBytes(hash, cal, ocsp);
            sgn.update(sh, 0, sh.length);

            if (tsa_url != null && tsa_url.length() > 0) {
                tsc = new TSAClientBouncyCastle(tsa_url, tsa_login, tsa_passw);
                byte[] encodedSig = sgn.getEncodedPKCS7(hash, cal, tsc, ocsp);
                if (contentEstimated + 2 < encodedSig.length)
                    throw new Exception("Not enough space");
                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));
                appearance.close(dic2);
            }
        }
        // ~timestamping + ocsp 

        File mysrc = new File(src);
        mysrc.delete();
        File mydest = new File(dest);
        mydest.renameTo(mysrc);

        System.exit(0);
    }

    catch (Exception e) {
        e.printStackTrace();
        System.exit(1);
    }
}

From source file:at.laborg.briss.CropManager.java

License:Open Source License

private static void cropMultipliedFile(File source, CropJob cropJob)
        throws FileNotFoundException, DocumentException, IOException {

    PdfReader reader = new PdfReader(source.getAbsolutePath());
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropJob.getDestinationFile()));
    stamper.setMoreInfo(cropJob.getSourceMetaInfo());

    PdfDictionary pageDict;//from  w  w  w  .  j a v  a2  s.  c  o m
    int newPageNumber = 1;
    for (int origPageNumber = 1; origPageNumber <= cropJob.getSourcePageCount(); origPageNumber++) {
        SingleCluster cluster = cropJob.getClusterCollection().getSingleCluster(origPageNumber);

        // if no crop was selected do nothing
        if (cluster.getRatiosList().size() == 0) {
            newPageNumber++;
            continue;
        }

        for (Float[] ratios : cluster.getRatiosList()) {

            pageDict = reader.getPageN(newPageNumber);

            List<Rectangle> boxes = new ArrayList<Rectangle>();
            boxes.add(reader.getBoxSize(newPageNumber, "media"));
            boxes.add(reader.getBoxSize(newPageNumber, "crop"));
            int rotation = reader.getPageRotation(newPageNumber);

            Rectangle scaledBox = calculateScaledRectangle(boxes, ratios, rotation);

            PdfArray scaleBoxArray = new PdfArray();
            scaleBoxArray.add(new PdfNumber(scaledBox.getLeft()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getBottom()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getRight()));
            scaleBoxArray.add(new PdfNumber(scaledBox.getTop()));

            pageDict.put(PdfName.CROPBOX, scaleBoxArray);
            pageDict.put(PdfName.MEDIABOX, scaleBoxArray);
            // increment the pagenumber
            newPageNumber++;
        }
        int[] range = new int[2];
        range[0] = newPageNumber - 1;
        range[1] = cropJob.getSourcePageCount() + (newPageNumber - origPageNumber);
        SimpleBookmark.shiftPageNumbers(cropJob.getSourceBookmarks(), cluster.getRatiosList().size() - 1,
                range);
    }
    stamper.setOutlines(cropJob.getSourceBookmarks());
    stamper.close();
    reader.close();
}

From source file:at.laborg.briss.utils.DocumentCropper.java

License:Open Source License

private static void cropMultipliedFile(final CropDefinition cropDefinition, final File multipliedDocument,
        final PdfMetaInformation pdfMetaInformation) throws DocumentException, IOException {

    PdfReader reader = new PdfReader(multipliedDocument.getAbsolutePath());

    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(cropDefinition.getDestinationFile()));
    stamper.setMoreInfo(pdfMetaInformation.getSourceMetaInfo());

    PdfDictionary pageDict;//from  w w  w.  ja  v  a  2s.c  o m
    int newPageNumber = 1;

    for (int sourcePageNumber = 1; sourcePageNumber <= pdfMetaInformation
            .getSourcePageCount(); sourcePageNumber++) {

        List<Float[]> rectangleList = cropDefinition.getRectanglesForPage(sourcePageNumber);

        // if no crop was selected do nothing
        if (rectangleList.isEmpty()) {
            newPageNumber++;
            continue;
        }

        for (Float[] ratios : rectangleList) {

            pageDict = reader.getPageN(newPageNumber);

            List<Rectangle> boxes = new ArrayList<Rectangle>();
            boxes.add(reader.getBoxSize(newPageNumber, "media"));
            boxes.add(reader.getBoxSize(newPageNumber, "crop"));
            int rotation = reader.getPageRotation(newPageNumber);

            Rectangle scaledBox = RectangleHandler.calculateScaledRectangle(boxes, ratios, rotation);

            PdfArray scaleBoxArray = createScaledBoxArray(scaledBox);

            pageDict.put(PdfName.CROPBOX, scaleBoxArray);
            pageDict.put(PdfName.MEDIABOX, scaleBoxArray);
            // increment the pagenumber
            newPageNumber++;
        }
        int[] range = new int[2];
        range[0] = newPageNumber - 1;
        range[1] = pdfMetaInformation.getSourcePageCount() + (newPageNumber - sourcePageNumber);
        SimpleBookmark.shiftPageNumbers(pdfMetaInformation.getSourceBookmarks(), rectangleList.size() - 1,
                range);
    }
    stamper.setOutlines(pdfMetaInformation.getSourceBookmarks());
    stamper.close();
    reader.close();
}

From source file:be.roots.taconic.pricingguide.service.PDFServiceImpl.java

License:Open Source License

private byte[] setDocumentProperties(Contact contact, byte[] guide) throws IOException, DocumentException {

    try (final ByteArrayOutputStream baos = new ByteArrayOutputStream()) {

        final PdfReader reader = new PdfReader(guide);
        final PdfStamper stamper = new PdfStamper(reader, baos);

        final Map<String, String> info = reader.getInfo();

        info.put("Title", documentTitle);
        info.put("Subject", documentTitle);

        info.put("Keywords",
                "Created for " + contact.getFullName() + ". " + "Currency used : " + contact.getCurrency()
                        + ". " + "Mailed to " + contact.getEmail() + ". " + "Build on "
                        + gitService.getCommitId());

        info.put("Creator", "Roots Software - http://www.roots.be - info@roots.be");
        info.put("Author", "Taconic - http://www.taconic.com");

        stamper.setMoreInfo(info);

        stamper.close();/*w  w w.j  av a2  s  . c  om*/
        reader.close();

        return baos.toByteArray();

    }
}

From source file:co.unicauca.proyectobase.entidades.MetodosPDF.java

public void manipulatePdf(String src, String dest) throws IOException, DocumentException {
    PdfReader reader = new PdfReader(src);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
    HashMap<String, String> info = reader.getInfo();
    info.put("Title", "Hello World stamped");
    info.put("Subject", "Hello World with changed metadata");
    info.put("Keywords", "iText in Action, PdfStamper");
    info.put("Creator", "Silly standalone example");
    info.put("Author", "Also Bruno Lowagie");
    info.put("Cod", codigoFirma("104611024139"));
    stamper.setMoreInfo(info);
    stamper.close();/*from   w w  w. j a  v a  2 s. co  m*/
    reader.close();
}

From source file:com.poet.ar.remover.AnnotationRemover.java

/**
 * remove Creator,Subject,Producer,Author,Title,Keywords
 * @param reader/*from   w  ww  .  ja v  a 2 s  . c  o  m*/
 * @param stamper
 */
private static void removeInfo(PdfReader reader, PdfStamper stamper) {
    Map<String, String> infos = reader.getInfo();

    infos.put(Meta.AUTHOR, "");
    infos.put(Meta.KEYWORDS, "");
    infos.put(Meta.TITLE, "");
    infos.put(Meta.SUBJECT, "");

    infos.put("Creator", "");
    infos.put("Subject", "");
    infos.put("Author", "");
    infos.put("Title", "");
    infos.put("Keywords", "");

    // this will not work ,if you want change producer , you need buy a itext license
    infos.put(Meta.PRODUCER, "");

    stamper.setMoreInfo(infos);
}

From source file:cz.hobrasoft.pdfmu.operation.metadata.OperationMetadataSet.java

License:Open Source License

public static void set(PdfStamper stp, Map<String, String> info) {
    assert stp != null;
    assert info != null;

    for (String key : ignoredProperties) {
        if (info.containsKey(key)) {
            String value = info.get(key);
            logger.warning(String.format(
                    "Warning: The property %s is set automatically. The value \"%s\" will be ignored.", key,
                    value));//w ww  . ja  v a2 s .  c  o  m
        }
    }

    stp.setMoreInfo(info);
    logger.info("PDF metadata have been set.");
}

From source file:net.ionescu.jhocr2pdf.Jhocr2pdf.java

License:Open Source License

/**
 * @param args//from   www.ja  v a 2s. c  o m
 * The arguments are:
 *  [options] output_pdf
 * The name of the output PDF file with the added OCR information must be the last argument
 * Other 
 * flags:
 *   -i pdf_file PDF file containing the TIFF images
 *   -hocr html_file hOCR file generated by Tesseract 
 *   -visible render the text above the image (mostry for debugging)
 *   -font font_path  path to the font file to use
 *   -hocrnameformat string to use to construct the name of the hocr file depending on page number
 *
 * Usage example:
 * java -jar jhorc2pdf.jar -font /usr/share/fonts/truetype/ttf-dejavu/DejaVuSans.ttf -i input.pdf -hocr input.html output.pdf
 *
 * @throws SAXException
 * @throws IOException
 * @throws DocumentException
 */
public static void main(String[] args) throws SAXException, IOException, DocumentException {
    /*
     * process input parameters
     * 
     * -visible -font font_path inputPDF inputOCR outputPDF
     */
    boolean visible = false;
    String fontPath = null;
    String fileNameFormat = null;
    String inputPDF = null;
    String inputHOCR = null;
    String outputPDF = null;

    for (int i = 0; i < args.length; i++) {
        if (args[i].startsWith("-")) {
            switch (args[i]) {

            case "-visible":
                visible = true;
                break;

            case "-font":
                fontPath = args[++i];
                break;

            case "-hocrnameformat":
                fileNameFormat = args[++i];
                break;

            case "-i":
                inputPDF = args[++i];
                break;

            case "-hocr":
                inputHOCR = args[++i];
                break;

            default:
                System.err.println("Invalid parameter: " + args[i]);
                System.exit(1);
            }
        } else {
            if (i < args.length - 1) {
                System.err.println("Ouput file name should be the last argument");
                System.exit(1);
            }
            outputPDF = args[i];
        }
    }

    log.fine("load the PDF file, initialize the Stamper");
    PdfReader reader = new PdfReader(inputPDF);
    PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputPDF));

    Map<String, String> info = reader.getInfo();
    info.put("Title", new File(outputPDF).getName());
    stamper.setMoreInfo(info);

    Jhocr2pdf ocrStamp = new Jhocr2pdf(stamper, visible, fontPath);
    if (null != fileNameFormat) {
        log.fine("iterate through all the pages looking for separate hocr files");
        for (int i = 1, maxPages = reader.getNumberOfPages() + 1; i < maxPages; i++) {
            String hocrFileName = String.format(fileNameFormat, i);
            try {
                ocrStamp.parse(hocrFileName, i);
            } catch (SAXException saxException) {
                System.err.println("Error processing hocr file: " + hocrFileName);
                throw saxException;
            }
        }
    } else {
        ocrStamp.parse(inputHOCR, -1);
    }
    stamper.close();
}

From source file:net.pflaeging.PortableSigner.PDFSigner.java

License:Open Source License

/** Creates a new instance of DoSignPDF */
public void doSignPDF(String pdfInputFileName, String pdfOutputFileName, String pkcs12FileName, String password,
        Boolean signText, String signLanguage, String sigLogo, Boolean finalize, String sigComment,
        String signReason, String signLocation, Boolean noExtraPage, float verticalPos, float leftMargin,
        float rightMargin, Boolean signLastPage, byte[] ownerPassword) throws PDFSignerException {
    try {/*from w  ww .jav  a2 s  .  c  o m*/
        //System.out.println("-> DoSignPDF <-");
        //System.out.println("Eingabedatei: " + pdfInputFileName);
        //System.out.println("Ausgabedatei: " + pdfOutputFileName);
        //System.out.println("Signaturdatei: " + pkcs12FileName);
        //System.out.println("Signaturblock?: " + signText);
        //System.out.println("Sprache der Blocks: " + signLanguage);
        //System.out.println("Signaturlogo: " + sigLogo);
        System.err.println("Position V:" + verticalPos + " L:" + leftMargin + " R:" + rightMargin);
        Rectangle signatureBlock;

        java.security.Security.insertProviderAt(new org.bouncycastle.jce.provider.BouncyCastleProvider(), 2);

        pkcs12 = new GetPKCS12(pkcs12FileName, password);

        PdfReader reader = null;
        try {
            //                System.out.println("Password:" + ownerPassword.toString());
            if (ownerPassword == null)
                reader = new PdfReader(pdfInputFileName);
            else
                reader = new PdfReader(pdfInputFileName, ownerPassword);
        } catch (IOException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle(
                "net/pflaeging/PortableSigner/i18n").getString(
                "CouldNotBeOpened"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeOpened"), true, e.getLocalizedMessage());
        }
        FileOutputStream fout = null;
        try {
            fout = new FileOutputStream(pdfOutputFileName);
        } catch (FileNotFoundException e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("CouldNotBeWritten"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("CouldNotBeWritten"), true, e.getLocalizedMessage());

        }
        PdfStamper stp = null;
        try {
            Date datum = new Date(System.currentTimeMillis());

            int pages = reader.getNumberOfPages();

            Rectangle size = reader.getPageSize(pages);
            stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
            HashMap<String, String> pdfInfo = reader.getInfo();
            // thanks to Markus Feisst
            String pdfInfoProducer = "";

            if (pdfInfo.get("Producer") != null) {
                pdfInfoProducer = pdfInfo.get("Producer").toString();
                pdfInfoProducer = pdfInfoProducer + " (signed with PortableSigner " + Version.release + ")";
            } else {
                pdfInfoProducer = "Unknown Producer (signed with PortableSigner " + Version.release + ")";
            }
            pdfInfo.put("Producer", pdfInfoProducer);
            //System.err.print("++ Producer:" + pdfInfo.get("Producer").toString());
            stp.setMoreInfo(pdfInfo);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            XmpWriter xmp = new XmpWriter(baos, pdfInfo);
            xmp.close();
            stp.setXmpMetadata(baos.toByteArray());
            if (signText) {
                String greet, signator, datestr, ca, serial, special, note, urn, urnvalue;
                int specialcount = 0;
                int sigpage;
                int rightMarginPT, leftMarginPT;
                float verticalPositionPT;
                ResourceBundle block = ResourceBundle
                        .getBundle("net/pflaeging/PortableSigner/Signatureblock_" + signLanguage);
                greet = block.getString("greeting");
                signator = block.getString("signator");
                datestr = block.getString("date");
                ca = block.getString("issuer");
                serial = block.getString("serial");
                special = block.getString("special");
                note = block.getString("note");
                urn = block.getString("urn");
                urnvalue = block.getString("urnvalue");

                //sigcomment = block.getString(signLanguage + "-comment");
                // upper y
                float topy = size.getTop();
                System.err.println("Top: " + topy * ptToCm);
                // right x
                float rightx = size.getRight();
                System.err.println("Right: " + rightx * ptToCm);
                if (!noExtraPage) {
                    sigpage = pages + 1;
                    stp.insertPage(sigpage, size);
                    // 30pt left, 30pt right, 20pt from top
                    rightMarginPT = 30;
                    leftMarginPT = 30;
                    verticalPositionPT = topy - 20;
                } else {
                    if (signLastPage) {
                        sigpage = pages;
                    } else {
                        sigpage = 1;
                    }
                    System.err.println("Page: " + sigpage);
                    rightMarginPT = Math.round(rightMargin / ptToCm);
                    leftMarginPT = Math.round(leftMargin / ptToCm);
                    verticalPositionPT = topy - Math.round(verticalPos / ptToCm);
                }
                if (!GetPKCS12.atEgovOID.equals("")) {
                    specialcount = 1;
                }
                PdfContentByte content = stp.getOverContent(sigpage);

                float[] cellsize = new float[2];
                cellsize[0] = 100f;
                // rightx = width of page
                // 60 = 2x30 margins
                // cellsize[0] = description row
                // cellsize[1] = 0
                // 70 = logo width
                cellsize[1] = rightx - rightMarginPT - leftMarginPT - cellsize[0] - cellsize[1] - 70;

                // Pagetable = Greeting, signatureblock, comment
                // sigpagetable = outer table
                //      consist: greetingcell, signatureblock , commentcell
                PdfPTable signatureBlockCompleteTable = new PdfPTable(2);
                PdfPTable signatureTextTable = new PdfPTable(2);
                PdfPCell signatureBlockHeadingCell = new PdfPCell(
                        new Paragraph(new Chunk(greet, new Font(Font.FontFamily.HELVETICA, 12))));
                signatureBlockHeadingCell.setPaddingBottom(5);
                signatureBlockHeadingCell.setColspan(2);
                signatureBlockHeadingCell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(signatureBlockHeadingCell);

                // inner table start
                // Line 1
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(signator, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.subject, new Font(Font.FontFamily.COURIER, 10))));
                // Line 2
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datestr, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(datum.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 3
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(ca, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(GetPKCS12.issuer, new Font(Font.FontFamily.COURIER, 10))));
                // Line 4
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(serial, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable.addCell(new Paragraph(
                        new Chunk(GetPKCS12.serial.toString(), new Font(Font.FontFamily.COURIER, 10))));
                // Line 5
                if (specialcount == 1) {
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(special, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                    signatureTextTable.addCell(new Paragraph(
                            new Chunk(GetPKCS12.atEgovOID, new Font(Font.FontFamily.COURIER, 10))));
                }
                signatureTextTable.addCell(
                        new Paragraph(new Chunk(urn, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                signatureTextTable
                        .addCell(new Paragraph(new Chunk(urnvalue, new Font(Font.FontFamily.COURIER, 10))));
                signatureTextTable.setTotalWidth(cellsize);
                System.err.println(
                        "signatureTextTable Width: " + cellsize[0] * ptToCm + " " + cellsize[1] * ptToCm);
                // inner table end

                signatureBlockCompleteTable.setHorizontalAlignment(PdfPTable.ALIGN_CENTER);
                Image logo;
                //                     System.out.println("Logo:" + sigLogo + ":");
                if (sigLogo == null || "".equals(sigLogo)) {
                    logo = Image.getInstance(
                            getClass().getResource("/net/pflaeging/PortableSigner/SignatureLogo.png"));
                } else {
                    logo = Image.getInstance(sigLogo);
                }

                PdfPCell logocell = new PdfPCell();
                logocell.setVerticalAlignment(PdfPCell.ALIGN_MIDDLE);
                logocell.setHorizontalAlignment(PdfPCell.ALIGN_CENTER);
                logocell.setImage(logo);
                signatureBlockCompleteTable.addCell(logocell);
                PdfPCell incell = new PdfPCell(signatureTextTable);
                incell.setBorderWidth(0f);
                signatureBlockCompleteTable.addCell(incell);
                PdfPCell commentcell = new PdfPCell(
                        new Paragraph(new Chunk(sigComment, new Font(Font.FontFamily.HELVETICA, 10))));
                PdfPCell notecell = new PdfPCell(
                        new Paragraph(new Chunk(note, new Font(Font.FontFamily.HELVETICA, 10, Font.BOLD))));
                //commentcell.setPaddingTop(10);
                //commentcell.setColspan(2);
                // commentcell.setBorderWidth(0f);
                if (!sigComment.equals("")) {
                    signatureBlockCompleteTable.addCell(notecell);
                    signatureBlockCompleteTable.addCell(commentcell);
                }
                float[] cells = { 70, cellsize[0] + cellsize[1] };
                signatureBlockCompleteTable.setTotalWidth(cells);
                System.err.println(
                        "signatureBlockCompleteTable Width: " + cells[0] * ptToCm + " " + cells[1] * ptToCm);
                signatureBlockCompleteTable.writeSelectedRows(0, 4 + specialcount, leftMarginPT,
                        verticalPositionPT, content);
                System.err.println(
                        "signatureBlockCompleteTable Position " + 30 * ptToCm + " " + (topy - 20) * ptToCm);
                signatureBlock = new Rectangle(30 + signatureBlockCompleteTable.getTotalWidth() - 20,
                        topy - 20 - 20, 30 + signatureBlockCompleteTable.getTotalWidth(), topy - 20);
                //                    //////
                //                    AcroFields af = reader.getAcroFields();
                //                    ArrayList names = af.getSignatureNames();
                //                    for (int k = 0; k < names.size(); ++k) {
                //                        String name = (String) names.get(k);
                //                        System.out.println("Signature name: " + name);
                //                        System.out.println("\tSignature covers whole document: " + af.signatureCoversWholeDocument(name));
                //                        System.out.println("\tDocument revision: " + af.getRevision(name) + " of " + af.getTotalRevisions());
                //                        PdfPKCS7 pk = af.verifySignature(name);
                //                        X509Certificate tempsigner = pk.getSigningCertificate();
                //                        Calendar cal = pk.getSignDate();
                //                        Certificate pkc[] = pk.getCertificates();
                //                        java.util.ResourceBundle tempoid =
                //                                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/SpecialOID");
                //                        String tmpEgovOID = "";
                //
                //                        for (Enumeration<String> o = tempoid.getKeys(); o.hasMoreElements();) {
                //                            String element = o.nextElement();
                //                            // System.out.println(element + ":" + oid.getString(element));
                //                            if (tempsigner.getNonCriticalExtensionOIDs().contains(element)) {
                //                                if (!tmpEgovOID.equals("")) {
                //                                    tmpEgovOID += ", ";
                //                                }
                //                                tmpEgovOID += tempoid.getString(element) + " (OID=" + element + ")";
                //                            }
                //                        }
                //                        //System.out.println("\tSigniert von: " + PdfPKCS7.getSubjectFields(pk.getSigningCertificate()));
                //                        System.out.println("\tSigniert von: " + tempsigner.getSubjectX500Principal().toString());
                //                        System.out.println("\tDatum: " + cal.getTime().toString());
                //                        System.out.println("\tAusgestellt von: " + tempsigner.getIssuerX500Principal().toString());
                //                        System.out.println("\tSeriennummer: " + tempsigner.getSerialNumber());
                //                        if (!tmpEgovOID.equals("")) {
                //                            System.out.println("\tVerwaltungseigenschaft: " + tmpEgovOID);
                //                        }
                //                        System.out.println("\n");
                //                        System.out.println("\tDocument modified: " + !pk.verify());
                ////                Object fails[] = PdfPKCS7.verifyCertificates(pkc, kall, null, cal);
                ////                if (fails == null) {
                ////                    System.out.println("\tCertificates verified against the KeyStore");
                ////                } else {
                ////                    System.out.println("\tCertificate failed: " + fails[1]);
                ////                }
                //                    }
                //
                //                //////
            } else {
                signatureBlock = new Rectangle(0, 0, 0, 0); // fake definition
            }
            PdfSignatureAppearance sap = stp.getSignatureAppearance();
            //                sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null,
            //                        PdfSignatureAppearance.WINCER_SIGNED );
            sap.setCrypto(GetPKCS12.privateKey, GetPKCS12.certificateChain, null, null);
            sap.setReason(signReason);
            sap.setLocation(signLocation);
            //                if (signText) {
            //                    sap.setVisibleSignature(signatureBlock,
            //                            pages + 1, "PortableSigner");
            //                }
            if (finalize) {
                sap.setCertificationLevel(PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED);
            } else {
                sap.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
            }
            stp.close();

            /* MODIFY BY: Denis Torresan
            Main.setResult(
              java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("IsGeneratedAndSigned"),
              false,
              "");
                */

        } catch (Exception e) {

            /* MODIFY BY: Denis Torresan
             Main.setResult(
                java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorWhileSigningFile"),
                true,
                e.getLocalizedMessage());
             */

            throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                    .getString("ErrorWhileSigningFile"), true, e.getLocalizedMessage());

        }
    } catch (KeyStoreException kse) {

        /* MODIFY BY: Denis Torresan
         Main.setResult(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n").getString("ErrorCreatingKeystore"),
            true, kse.getLocalizedMessage());
         */

        throw new PDFSignerException(java.util.ResourceBundle.getBundle("net/pflaeging/PortableSigner/i18n")
                .getString("ErrorCreatingKeystore"), true, kse.getLocalizedMessage());

    }
}