Example usage for com.lowagie.text.pdf PdfTemplate addImage

List of usage examples for com.lowagie.text.pdf PdfTemplate addImage

Introduction

In this page you can find the example usage for com.lowagie.text.pdf PdfTemplate addImage.

Prototype

public void addImage(Image image) throws DocumentException 

Source Link

Document

Adds an Image to the page.

Usage

From source file:org.mapfish.print.PDFUtils.java

License:Open Source License

/**
 * Gets an iText image with a cache that uses PdfTemplates to re-use the same
 * bitmap content multiple times in order to reduce the file size.
 *//*ww  w .  j av  a2  s . c om*/
public static Image getImage(RenderingContext context, URI uri, float w, float h)
        throws IOException, DocumentException {
    //Check the image is not already used in the PDF file.
    //
    //This part is not protected against multi-threads... worst case, a single image can
    //be twice in the PDF, if used more than one time. But since only one !map
    //block is dealed with at a time, this should not happen
    Map<URI, PdfTemplate> cache = context.getTemplateCache();
    PdfTemplate template = cache.get(uri);
    if (template == null) {
        Image content = getImageDirect(context, uri);
        content.setAbsolutePosition(0, 0);
        final PdfContentByte dc = context.getDirectContent();
        synchronized (context.getPdfLock()) { //protect against parallel writing on the PDF file
            template = dc.createTemplate(content.getPlainWidth(), content.getPlainHeight());
            template.addImage(content);
        }
        cache.put(uri, template);
    }

    //fix the size/aspect ratio of the image in function of what is specified by the user
    if (w == 0.0f) {
        if (h == 0.0f) {
            w = template.getWidth();
            h = template.getHeight();
        } else {
            w = h / template.getHeight() * template.getWidth();
        }
    } else {
        if (h == 0.0f) {
            h = w / template.getWidth() * template.getHeight();
        }
    }

    final Image result = Image.getInstance(template);
    result.scaleToFit(w, h);
    return result;
}

From source file:org.signserver.module.pdfsigner.PDFSigner.java

License:Open Source License

protected byte[] addSignatureToPDFDocument(final ICryptoInstance crypto, PDFSignerParameters params,
        byte[] pdfbytes, byte[] password, int contentEstimated, final ProcessRequest request,
        final RequestContext context) throws IOException, DocumentException, CryptoTokenOfflineException,
        SignServerException, IllegalRequestException {
    // when given a content length (i.e. non-zero), it means we are running a second try
    boolean secondTry = contentEstimated != 0;

    // get signing cert certificate chain and private key
    final List<Certificate> certs = getSigningCertificateChain(crypto);
    if (certs == null) {
        throw new SignServerException("Null certificate chain. This signer needs a certificate.");
    }/*from w w  w .  ja  v  a  2  s.  c  o  m*/
    final List<Certificate> includedCerts = includedCertificates(certs);
    Certificate[] certChain = includedCerts.toArray(new Certificate[includedCerts.size()]);
    PrivateKey privKey = crypto.getPrivateKey();

    // need to check digest algorithms for DSA private key at signing
    // time since we can't be sure what key a configured alias selector gives back
    if (privKey instanceof DSAPrivateKey) {
        if (!"SHA1".equals(digestAlgorithm)) {
            throw new IllegalRequestException(
                    "Only SHA1 is permitted as digest algorithm for DSA private keys");
        }
    }

    PdfReader reader = new PdfReader(pdfbytes, password);
    boolean appendMode = true; // TODO: This could be good to have as a property in the future

    int pdfVersion;

    try {
        pdfVersion = Integer.parseInt(Character.toString(reader.getPdfVersion()));
    } catch (NumberFormatException e) {
        pdfVersion = 0;
    }

    if (LOG.isDebugEnabled()) {
        LOG.debug("PDF version: " + pdfVersion);
    }

    // Don't certify already certified documents
    if (reader.getCertificationLevel() != PdfSignatureAppearance.NOT_CERTIFIED
            && params.getCertification_level() != PdfSignatureAppearance.NOT_CERTIFIED) {
        throw new IllegalRequestException("Will not certify an already certified document");
    }

    // Don't sign documents where the certification does not allow it
    if (reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED
            || reader.getCertificationLevel() == PdfSignatureAppearance.CERTIFIED_FORM_FILLING) {
        throw new IllegalRequestException("Will not sign a certified document where signing is not allowed");
    }

    Permissions currentPermissions = Permissions.fromInt(reader.getPermissions());

    if (params.getSetPermissions() != null && params.getRemovePermissions() != null) {
        throw new SignServerException("Signer " + workerId + " missconfigured. Only one of " + SET_PERMISSIONS
                + " and " + REMOVE_PERMISSIONS + " should be specified.");
    }

    Permissions newPermissions;
    if (params.getSetPermissions() != null) {
        newPermissions = params.getSetPermissions();
    } else if (params.getRemovePermissions() != null) {
        newPermissions = currentPermissions.withRemoved(params.getRemovePermissions());
    } else {
        newPermissions = null;
    }

    Permissions rejectPermissions = Permissions.fromSet(params.getRejectPermissions());
    byte[] userPassword = reader.computeUserPassword();
    int cryptoMode = reader.getCryptoMode();
    if (LOG.isDebugEnabled()) {
        StringBuilder buff = new StringBuilder();
        buff.append("Current permissions: ").append(currentPermissions).append("\n")
                .append("Remove permissions: ").append(params.getRemovePermissions()).append("\n")
                .append("Reject permissions: ").append(rejectPermissions).append("\n")
                .append("New permissions: ").append(newPermissions).append("\n").append("userPassword: ")
                .append(userPassword == null ? "null" : "yes").append("\n").append("ownerPassword: ")
                .append(password == null ? "no" : (isUserPassword(reader, password) ? "no" : "yes"))
                .append("\n").append("setOwnerPassword: ")
                .append(params.getSetOwnerPassword() == null ? "no" : "yes").append("\n").append("cryptoMode: ")
                .append(cryptoMode);
        LOG.debug(buff.toString());
    }

    if (appendMode && (newPermissions != null || params.getSetOwnerPassword() != null)) {
        appendMode = false;
        if (LOG.isDebugEnabled()) {
            LOG.debug("Changing appendMode to false to be able to change permissions");
        }
    }

    ByteArrayOutputStream fout = new ByteArrayOutputStream();

    // increase PDF version if needed by digest algorithm
    final char updatedPdfVersion;
    if (minimumPdfVersion > pdfVersion) {
        updatedPdfVersion = Character.forDigit(minimumPdfVersion, 10);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Need to upgrade PDF to version 1." + updatedPdfVersion);
        }

        // check that the document isn't already signed 
        // when trying to upgrade version
        final AcroFields af = reader.getAcroFields();
        final List<String> sigNames = af.getSignatureNames();

        if (!sigNames.isEmpty()) {
            // TODO: in the future we might want to support
            // a fallback option in this case to allow re-signing using the same version (using append)
            throw new IllegalRequestException(
                    "Can not upgrade an already signed PDF and a higher version is required to support the configured digest algorithm");
        }

        appendMode = false;
    } else {
        updatedPdfVersion = '\0';
    }

    PdfStamper stp = PdfStamper.createSignature(reader, fout, updatedPdfVersion, null, appendMode);
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    // Set the new permissions
    if (newPermissions != null || params.getSetOwnerPassword() != null) {
        if (cryptoMode < 0) {
            cryptoMode = PdfWriter.STANDARD_ENCRYPTION_128;
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting default encryption algorithm");
            }
        }
        if (newPermissions == null) {
            newPermissions = currentPermissions;
        }
        if (params.getSetOwnerPassword() != null) {
            password = params.getSetOwnerPassword().getBytes("ISO-8859-1");
        } else if (isUserPassword(reader, password)) {
            // We do not have an owner password so lets use a random one
            password = new byte[16];
            random.nextBytes(password);
            if (LOG.isDebugEnabled()) {
                LOG.debug("Setting random owner password");
            }
        }
        stp.setEncryption(userPassword, password, newPermissions.asInt(), cryptoMode);
        currentPermissions = newPermissions;
    }

    // Reject if any permissions are rejected and the document does not use a permission password
    // or if it contains any of the rejected permissions
    if (rejectPermissions.asInt() != 0) {
        if (cryptoMode < 0 || currentPermissions.containsAnyOf(rejectPermissions)) {
            throw new IllegalRequestException("Document contains permissions not allowed by this signer");
        }
    }

    // include signer certificate crl inside cms package if requested
    CRL[] crlList = null;
    if (params.isEmbed_crl()) {
        crlList = getCrlsForChain(certs);
    }
    sap.setCrypto(null, certChain, crlList, PdfSignatureAppearance.SELF_SIGNED);

    // add visible signature if requested
    if (params.isAdd_visible_signature()) {
        int signaturePage = getPageNumberForSignature(reader, params);
        sap.setVisibleSignature(new com.lowagie.text.Rectangle(params.getVisible_sig_rectangle_llx(),
                params.getVisible_sig_rectangle_lly(), params.getVisible_sig_rectangle_urx(),
                params.getVisible_sig_rectangle_ury()), signaturePage, null);

        // set custom image if requested
        if (params.isUse_custom_image()) {
            sap.setAcro6Layers(true);
            PdfTemplate n2 = sap.getLayer(2);
            params.getCustom_image().setAbsolutePosition(0, 0);
            n2.addImage(params.getCustom_image());
        }
    }

    // Certification level
    sap.setCertificationLevel(params.getCertification_level());

    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("adbe.pkcs7.detached"));
    dic.setReason(params.getReason());
    dic.setLocation(params.getLocation());
    dic.setDate(new PdfDate(Calendar.getInstance()));

    sap.setCryptoDictionary(dic);

    // add timestamp to signature if requested
    TSAClient tsc = null;
    if (params.isUse_timestamp()) {
        final String tsaUrl = params.getTsa_url();

        if (tsaUrl != null) {
            tsc = getTimeStampClient(params.getTsa_url(), params.getTsa_username(), params.getTsa_password());
        } else {
            tsc = new InternalTSAClient(getWorkerSession(), params.getTsa_worker(), params.getTsa_username(),
                    params.getTsa_password());
        }
    }

    // embed ocsp response in cms package if requested
    // for ocsp request to be formed there needs to be issuer certificate in
    // chain
    byte[] ocsp = null;
    if (params.isEmbed_ocsp_response() && certChain.length >= 2) {
        String url;
        try {
            url = PdfPKCS7.getOCSPURL((X509Certificate) certChain[0]);
            if (url != null && url.length() > 0) {
                ocsp = new OcspClientBouncyCastle((X509Certificate) certChain[0],
                        (X509Certificate) certChain[1], url).getEncoded();
            }
        } catch (CertificateParsingException e) {
            throw new SignServerException("Error getting OCSP URL from certificate", e);
        }

    }

    PdfPKCS7 sgn;
    try {
        sgn = new PdfPKCS7(privKey, certChain, crlList, digestAlgorithm, null, false);
    } catch (InvalidKeyException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchProviderException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error constructing PKCS7 package", e);
    }

    MessageDigest messageDigest;
    try {
        messageDigest = MessageDigest.getInstance(digestAlgorithm);
    } catch (NoSuchAlgorithmException e) {
        throw new SignServerException("Error creating " + digestAlgorithm + " digest", e);
    }

    Calendar cal = Calendar.getInstance();

    // calculate signature size
    if (contentEstimated == 0) {
        contentEstimated = calculateEstimatedSignatureSize(certChain, tsc, ocsp, crlList);
    }

    byte[] encodedSig = calculateSignature(sgn, contentEstimated, messageDigest, cal, params, certChain, tsc,
            ocsp, sap);

    if (LOG.isDebugEnabled()) {
        LOG.debug("Estimated size: " + contentEstimated);
        LOG.debug("Encoded length: " + encodedSig.length);
    }

    if (contentEstimated + 2 < encodedSig.length) {
        if (!secondTry) {
            int contentExact = encodedSig.length;
            LOG.warn(
                    "Estimated signature size too small, usinging accurate calculation (resulting in an extra signature computation).");

            if (LOG.isDebugEnabled()) {
                LOG.debug("Estimated size: " + contentEstimated + ", actual size: " + contentExact);
            }

            // try signing again
            return addSignatureToPDFDocument(crypto, params, pdfbytes, password, contentExact, request,
                    context);
        } else {
            // if we fail to get an accurate signature size on the second attempt, bail out (this shouldn't happen)
            throw new SignServerException("Failed to calculate signature size");
        }
    }

    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);
    reader.close();

    fout.close();
    return fout.toByteArray();
}

From source file:recite18th.controller.Controller.java

License:Open Source License

public void print(String action) {
    /** thanks to http://www.java2s.com/Code/Java/PDF-RTF/DemonstratesthecreatingPDFinportraitlandscape.htm
     * QUICK FIX : do landscape/*  w w w .  j  a  v a2s.c  o m*/
     */
    response.setContentType("application/pdf"); // Code 1
    if (action.equals("download")) {
        response.setHeader("Content-Transfer-Encoding", "binary");
        response.setHeader("Content-Disposition",
                "attachment; filename=\"" + "Report " + controllerName + ".pdf\"");
    }
    Document document = new Document(PageSize.A1.rotate());
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // Code 2
        document.open();

        // various fonts
        BaseFont bf_helv = BaseFont.createFont(BaseFont.HELVETICA, "Cp1252", false);
        BaseFont bf_times = BaseFont.createFont(BaseFont.TIMES_ROMAN, "Cp1252", false);
        BaseFont bf_courier = BaseFont.createFont(BaseFont.COURIER, "Cp1252", false);
        BaseFont bf_symbol = BaseFont.createFont(BaseFont.SYMBOL, "Cp1252", false);

        String headerImage = Config.base_path + "images/report-logo.gif";

        Image imghead = Image.getInstance(headerImage);
        imghead.setAbsolutePosition(0, 0);
        PdfContentByte cbhead = writer.getDirectContent();
        PdfTemplate tpLogo = cbhead.createTemplate(600, 300);
        tpLogo.addImage(imghead);

        PdfTemplate tpTitle = cbhead.createTemplate(1100, 300);
        String txtHeader = "BADAN KEPEGAWAIAN DAERAH PEMERINTAH DAERAH";//Config.application_title;
        tpTitle.beginText();
        tpTitle.setFontAndSize(bf_times, 36);
        tpTitle.showText(txtHeader);
        tpTitle.endText();

        PdfTemplate tpTitle2 = cbhead.createTemplate(900, 300);
        String txtHeader2 = "         KABUPATEN BANTUL YOGYAKARTA";
        tpTitle2.beginText();
        tpTitle2.setFontAndSize(bf_times, 36);
        tpTitle2.showText(txtHeader2);
        tpTitle2.endText();

        PdfTemplate tpAlamat = cbhead.createTemplate(1000, 400);
        tpAlamat.beginText();
        tpAlamat.setFontAndSize(bf_times, 24);
        tpAlamat.showText(
                "Alamat : Jln. R. W. Monginsidi No. 01 Kompleks Parasamya Bantul, Telp. (0274) 367509");
        tpAlamat.endText();

        DateFormat df = new SimpleDateFormat("dd MMM yyyy");
        java.util.Date dt = new java.util.Date();
        PdfTemplate tp3 = cbhead.createTemplate(600, 300);
        tp3.beginText();
        tp3.setFontAndSize(bf_times, 16);

        tp3.showText("Tanggal : " + df.format(dt));
        tp3.endText();

        cbhead.addTemplate(tpLogo, 800, 1500);//logo
        cbhead.addTemplate(tpTitle, 1000, 1580);
        cbhead.addTemplate(tpTitle2, 1000, 1540);
        cbhead.addTemplate(tpAlamat, 1000, 1500);//alamat
        cbhead.addTemplate(tp3, 270, 1500);//tanggal

        HeaderFooter header = new HeaderFooter(new Phrase(cbhead + "", new Font(bf_helv)), false);
        header.setAlignment(Element.ALIGN_CENTER);

        document.setHeader(header);

        //PdfContentByte cb = writer.getDirectContent();
        Paragraph par = new Paragraph(
                "\n\n\n\n\n\n\nLAPORAN DATA SELURUH " + controllerName.toUpperCase() + "\n");
        par.getFont().setStyle(Font.BOLD);
        par.getFont().setSize(18);
        par.setAlignment("center");
        document.add(par);
        document.add(new Paragraph("\n\n"));

        // get data
        initSqlViewDataPerPage();
        if (sqlViewDataPerPageForReport == null) {
            sqlViewDataPerPageForReport = sqlViewDataPerPage;
        }
        PreparedStatement pstmt = Db.getCon().prepareStatement(sqlViewDataPerPageForReport,
                ResultSet.TYPE_SCROLL_SENSITIVE, ResultSet.CONCUR_READ_ONLY);
        ResultSet resultSet = pstmt.executeQuery();
        ResultSetMetaData metaColumn = resultSet.getMetaData();
        int nColoumn = metaColumn.getColumnCount();
        // thanks to set cell width http://www.jexp.ru/index.php/Java/PDF_RTF/Table_Cell_Size#Setting_Cell_Widths
        if (nColoumn > 0) {
            Model model = initModel();
            String tableName = model.getTableName();
            // create table header
            //     float[] widths = {1, 4};
            PdfPTable table;// = new PdfPTable(nColoumn);
            PdfPCell cell = new PdfPCell(new Paragraph("Daftar " + controllerName));

            Hashtable hashModel = TableCustomization.getTable(model.getTableName());

            int ncolumnHeader = nColoumn + 1; // +1 because of row. number
            if (hashModel != null) {
                ncolumnHeader = Integer.parseInt("" + hashModel.get("columnCount")) + 1;
            }
            table = new PdfPTable(ncolumnHeader);
            cell.setColspan(ncolumnHeader);
            cell.setHorizontalAlignment(Element.ALIGN_CENTER);

            Paragraph p2 = new Paragraph("No.");
            p2.getFont().setSize(20);
            PdfPCell cellColNo = new PdfPCell(p2);
            cellColNo.setNoWrap(true);
            cellColNo.setMinimumHeight(50);
            cellColNo.setHorizontalAlignment(Element.ALIGN_CENTER);
            table.addCell(cellColNo);

            if (hashModel != null) {
                Enumeration k = hashModel.keys();
                while (k.hasMoreElements()) {
                    String key = (String) k.nextElement();
                    if (key.equals("columnCount")) {
                        continue;
                    }
                    PdfPCell cellCol = new PdfPCell(new Paragraph(hashModel.get(key) + ""));
                    cellCol.setNoWrap(true);
                    cellCol.setMinimumHeight(50);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);

                    table.addCell(cellCol);
                }
            } else {
                for (int i = 1; i < ncolumnHeader; i++) {
                    System.out.println("DATA = " + metaColumn.getColumnName(i));
                    Paragraph p1 = new Paragraph(metaColumn.getColumnName(i) + "");
                    p1.getFont().setSize(20);
                    PdfPCell cellCol = new PdfPCell(p1);
                    cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                    table.addCell(cellCol);
                }
            }

            //iterate all columns : table data
            resultSet.beforeFirst();
            int row = 1;
            while (resultSet.next()) {
                System.out.println(row);
                Paragraph p3 = new Paragraph(row + "");
                p3.getFont().setSize(20);
                cell = new PdfPCell(p3);
                cell.setHorizontalAlignment(Element.ALIGN_CENTER);
                table.addCell(cell);
                if (hashModel != null) {//skip dulu u/ kasus ga pny class kustomasi table
                    Enumeration k = hashModel.keys();
                    while (k.hasMoreElements()) {
                        String key = (String) k.nextElement();
                        if (key.equals("columnCount")) {
                            continue;
                        }
                        table.addCell(resultSet.getObject(key) + "");
                    }
                } else {
                    for (int i = 1; i < ncolumnHeader; i++) {
                        System.out.println("DATA = " + metaColumn.getColumnName(i));
                        Paragraph p1 = new Paragraph(resultSet.getObject(metaColumn.getColumnName(i)) + "");
                        p1.getFont().setSize(18);
                        PdfPCell cellCol = new PdfPCell(p1);
                        cellCol.setHorizontalAlignment(Element.ALIGN_CENTER);
                        table.addCell(cellCol);
                    }
                }

                row++;
            }

            document.add(table);
            document.add(new Paragraph("\n\n"));
            par = new Paragraph("Mengetahui");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Kepada Badan Kepegawaian");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("\n\n\n");

            document.add(par);
            par = new Paragraph("Drs. Maman Permana");
            par.setAlignment("center");
            document.add(par);
            par = new Paragraph("Nip: 197802042006041013");
            par.setAlignment("center");

            document.add(par);

        }
        document.close();
    } catch (Exception e) {
        e.printStackTrace();
    }
}