Example usage for com.itextpdf.text.pdf PdfWriter VERSION_1_3

List of usage examples for com.itextpdf.text.pdf PdfWriter VERSION_1_3

Introduction

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

Prototype

char VERSION_1_3

To view the source code for com.itextpdf.text.pdf PdfWriter VERSION_1_3.

Click Source Link

Document

possible PDF version (header)

Usage

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/*from   w w w  .j  av  a2  s .c o m*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:ptolemy.vergil.basic.export.itextpdf.ExportPDFAction.java

License:Open Source License

/** Export PDF to a file.
 *  This uses the iText library at http://itextpdf.com/.
 *
 *  <p>If {@link ptolemy.gui.PtGUIUtilities#useFileDialog()} returns true
 *  then a java.awt.FileDialog is used, otherwise a javax.swing.JFileChooser
 *  is used.</p>/*from   w  ww.j a v a 2s  .  c  o  m*/
 */
private void _exportPDF() {
    Dimension size = _frame.getContentSize();
    Rectangle pageSize = null;
    try {
        pageSize = new Rectangle(size.width, size.height);
    } catch (Throwable ex) {
        // This exception will occur if the iText library is not installed.
        MessageHandler.error("iText library is not installed. See http://itextpdf.com/."
                + "  You must have iText.jar in your classpath.  Sometimes, "
                + "iText.jar may be found in $PTII/vendors/itext/iText.jar.", ex);
        return;
    }
    Document document = new Document(pageSize);
    JFileChooserBugFix jFileChooserBugFix = new JFileChooserBugFix();
    Color background = null;
    PtFileChooser ptFileChooser = null;
    try {
        background = jFileChooserBugFix.saveBackground();

        ptFileChooser = new PtFileChooser(_frame, "Specify a pdf file to be written.",
                JFileChooser.SAVE_DIALOG);

        LinkedList extensions = new LinkedList();
        extensions.add("pdf");
        ptFileChooser.addChoosableFileFilter(new ExtensionFilenameFilter(extensions));

        BasicGraphFrame basicGraphFrame = null;
        if (_frame instanceof BasicGraphFrame) {
            basicGraphFrame = (BasicGraphFrame) _frame;
            ptFileChooser.setCurrentDirectory(basicGraphFrame.getLastDirectory());
            ptFileChooser.setSelectedFile(new File(basicGraphFrame.getModel().getName() + ".pdf"));
        }
        int returnVal = ptFileChooser.showDialog(_frame, "Export PDF");

        if (returnVal == JFileChooser.APPROVE_OPTION) {
            if (basicGraphFrame != null) {
                basicGraphFrame.setLastDirectory(ptFileChooser.getCurrentDirectory());
            }
            File pdfFile = ptFileChooser.getSelectedFile().getCanonicalFile();

            if (pdfFile.getName().indexOf(".") == -1) {
                // If the user has not given the file an extension, add it
                pdfFile = new File(pdfFile.getAbsolutePath() + ".pdf");
            }

            // The Mac OS X FileDialog will ask if we want to save before this point.
            if (pdfFile.exists() && !PtGUIUtilities.useFileDialog()) {
                if (!MessageHandler.yesNoQuestion("Overwrite " + pdfFile.getName() + "?")) {
                    return;
                }
            }

            PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdfFile));
            // To ensure Latex compatibility, use earlier PDF version.
            writer.setPdfVersion(PdfWriter.VERSION_1_3);
            document.open();
            PdfContentByte contentByte = writer.getDirectContent();

            PdfTemplate template = contentByte.createTemplate(size.width, size.height);
            Graphics2D graphics = template.createGraphics(size.width, size.height);
            template.setWidth(size.width);
            template.setHeight(size.height);

            Paper paper = new Paper();
            paper.setSize(size.width, size.height);
            paper.setImageableArea(0.0, 0.0, size.width, size.height);
            PageFormat format = new PageFormat();
            format.setPaper(paper);
            ((Printable) _frame).print(graphics, format, 0);
            graphics.dispose();
            contentByte.addTemplate(template, 0, 0);

            // Open the PDF file.
            // FIXME: _read is protected in BasicGraphFrame
            //_read(pdfFile.toURI().toURL());
            // Open the image pdfFile.
            if (basicGraphFrame == null) {
                MessageHandler.message("PDF file exported to " + pdfFile.getName());
                /* Remove the following. The extra click is annoying...
                } else {
                if (MessageHandler.yesNoQuestion("Open \""
                        + pdfFile.getCanonicalPath() + "\" in a browser?")) {
                    Configuration configuration = basicGraphFrame
                            .getConfiguration();
                    try {
                        URL imageURL = new URL(pdfFile.toURI().toURL()
                                .toString()
                                + "#in_browser");
                        configuration.openModel(imageURL, imageURL,
                                imageURL.toExternalForm(),
                                BrowserEffigy.staticFactory);
                    } catch (Throwable throwable) {
                        MessageHandler.error(
                                "Failed to open \"" + pdfFile.getName()
                                        + "\".", throwable);
                    }
                }
                 */
            }
        }
    } catch (Exception e) {
        MessageHandler.error("Export to PDF failed", e);
    } finally {
        try {
            document.close();
        } finally {
            jFileChooserBugFix.restoreBackground(background);
        }
    }
}