Example usage for com.lowagie.text Image getInstance

List of usage examples for com.lowagie.text Image getInstance

Introduction

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

Prototype

public static Image getInstance(Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:ambit.data.qmrf.MyHandler.java

License:Open Source License

@Override
public void handleStartingTags(String name, Properties attributes) {
    System.out.println(name);//from  www  . j av  a2  s .  c om
    if (Image.isTag(name)) {
        try {
            //                Image img = Image.getInstance(attributes);
            System.out.println("ambit/data/qmrf/logo.png");
            Image img = Image
                    .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
            Object current;
            try {
                // if there is an element on the stack...
                current = stack.pop();
                // ...and it's a Chapter or a Section, the Image can be
                // added directly
                if (current instanceof Chapter || current instanceof Section || current instanceof Cell) {
                    ((TextElementArray) current).add(img);
                    stack.push(current);
                    return;
                }
                // ...if not, the Image is wrapped in a Chunk before it's
                // added
                else {
                    Stack newStack = new Stack();
                    try {
                        while (!(current instanceof Chapter || current instanceof Section
                                || current instanceof Cell)) {
                            newStack.push(current);
                            if (current instanceof Anchor) {
                                img.setAnnotation(new Annotation(0, 0, 0, 0, ((Anchor) current).reference()));
                            }
                            current = stack.pop();
                        }
                        ((TextElementArray) current).add(img);
                        stack.push(current);
                    } catch (EmptyStackException ese) {
                        document.add(img);
                    }
                    while (!newStack.empty()) {
                        stack.push(newStack.pop());
                    }
                    return;
                }
            } catch (EmptyStackException ese) {
                // if there is no element on the stack, the Image is added
                // to the document
                try {
                    document.add(img);
                } catch (DocumentException de) {
                    throw new ExceptionConverter(de);
                }
                return;
            }
        } catch (Exception e) {
            throw new ExceptionConverter(e);
        }

    } else
        super.handleStartingTags(name, attributes);
}

From source file:ambit.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void headerTable(Document pdfdoc, org.w3c.dom.Document xmldoc) {
    try {//from   w  ww.j a  va2s  .c o  m
        int header_font_size = 10;
        Image png_left = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        Image png_right = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        png_left.setAlignment(Image.LEFT);
        png_right.setAlignment(Image.RIGHT);
        png_left.scalePercent(60);
        png_right.scalePercent(60);
        //png.scaleAbsolute(76, 67);
        //png.setAlignment(Image.MIDDLE);

        PdfPCell cell;

        float[] widths = { 1f, 5f, 1f };
        float[] widths1 = { 1f };
        PdfPTable table = new PdfPTable(widths);
        PdfPTable table1 = new PdfPTable(widths1);

        table.setWidthPercentage(100);

        cell = new PdfPCell();
        cell.setMinimumHeight(70);
        cell.addElement(new Chunk(png_left, +14, -40));
        table.addCell(cell);

        String Text = "";
        try {

            Text = findNodeValue(xml_QMRF_number, xmldoc);
            Chunk ident_title = new Chunk("QMRF identifier (JRC Inventory):");
            Chunk ident_text = new Chunk(Text);

            Font bi_font = new Font(baseFont, header_font_size, Font.BOLDITALIC);
            Font i_font = new Font(baseFont, header_font_size, Font.ITALIC);

            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            Paragraph p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            ident_title = new Chunk("QMRF Title:");
            Phrase textPhrase = new Phrase();
            createNodePhrase("QSAR_title", xmldoc, textPhrase, i_font);
            ident_title.setFont(bi_font);

            p = new Paragraph();
            p.add(ident_title);
            p.add(textPhrase);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            java.util.Date now = new java.util.Date();
            java.text.DateFormat df = java.text.DateFormat.getDateInstance();
            String date = df.format(now);
            ident_title = new Chunk("Printing Date:");
            ident_text = new Chunk(date);
            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);

            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            p = new Paragraph("");
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);
            cell = new PdfPCell(table1);
            cell.setPadding(0f);
            table.addCell(cell);

        } catch (Throwable x) {
            x.printStackTrace();

        }

        //table.addCell(new PdfPCell(png, true));
        cell.addElement(new Chunk(png_right, +14, -40));
        table.addCell(cell);
        pdfdoc.add(table);
        pdfdoc.add(new Paragraph(16));

    } catch (Exception x) {
        x.printStackTrace();
    }
}

From source file:ambit2.data.qmrf.Qmrf_Xml_Pdf.java

License:Open Source License

public void headerTable(Document pdfdoc, org.w3c.dom.Document xmldoc) {
    try {//w w  w. j  av  a2s .com
        int header_font_size = 10;
        Image png_left = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        Image png_right = Image
                .getInstance(Qmrf_Xml_Pdf.class.getClassLoader().getResource("ambit/data/qmrf/logo.png"));
        png_left.setAlignment(Image.LEFT);
        png_right.setAlignment(Image.RIGHT);
        png_left.scalePercent(60);
        png_right.scalePercent(60);
        //png.scaleAbsolute(76, 67);
        //png.setAlignment(Image.MIDDLE);

        PdfPCell cell;

        float[] widths = { 1f, 5f, 1f };
        float[] widths1 = { 1f };
        PdfPTable table = new PdfPTable(widths);
        PdfPTable table1 = new PdfPTable(widths1);

        table.setWidthPercentage(100);

        cell = new PdfPCell();
        cell.setMinimumHeight(70);
        cell.addElement(new Chunk(png_left, +14, -40));
        table.addCell(cell);

        String Text = "";
        try {

            Text = findNodeValue(xml_QMRF_number, xmldoc);
            Chunk ident_title = new Chunk("QMRF identifier (ECB Inventory):");
            Chunk ident_text = new Chunk(Text);

            Font bi_font = new Font(baseFont, header_font_size, Font.BOLDITALIC);
            Font i_font = new Font(baseFont, header_font_size, Font.ITALIC);

            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            Paragraph p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            ident_title = new Chunk("QMRF Title:");
            Phrase textPhrase = new Phrase();
            createNodePhrase("QSAR_title", xmldoc, textPhrase, i_font);
            ident_title.setFont(bi_font);

            p = new Paragraph();
            p.add(ident_title);
            p.add(textPhrase);
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            java.util.Date now = new java.util.Date();
            java.text.DateFormat df = java.text.DateFormat.getDateInstance();
            String date = df.format(now);
            ident_title = new Chunk("Printing Date:");
            ident_text = new Chunk(date);
            ident_title.setFont(bi_font);
            ident_text.setFont(i_font);
            p = new Paragraph();
            p.add(ident_title);
            p.add(ident_text);

            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);

            p = new Paragraph("");
            cell = new PdfPCell(p);
            cell.setHorizontalAlignment(Element.ALIGN_LEFT);
            table1.addCell(cell);
            cell = new PdfPCell(table1);
            cell.setPadding(0f);
            table.addCell(cell);

        } catch (Throwable x) {
            x.printStackTrace();

        }

        //table.addCell(new PdfPCell(png, true));
        cell.addElement(new Chunk(png_right, +14, -40));
        table.addCell(cell);
        pdfdoc.add(table);
        pdfdoc.add(new Paragraph(16));

    } catch (Exception x) {
        x.printStackTrace();
    }
}

From source file:androidGLUESigner.pdf.PDFSignerEngine.java

License:Open Source License

/**
 * Prepare the signing of the pdf (siganture appearance, placeholders, sigimage, ..) 
 * @param inputStream the stream to the input pdf file
 * @param outputStream the stream to the output pdf file
 * @return hash value with ocsp included
 * @throws IOException/*  w ww.jav a 2 s.  c  o m*/
 * @throws DocumentException
 * @throws GeneralSecurityException
 */
public byte[] prepareSign(InputStream inputStream, OutputStream outputStream)
        throws IOException, DocumentException, GeneralSecurityException {

    PdfReader reader = new PdfReader(inputStream);

    PdfStamper stp = PdfStamper.createSignature(reader, outputStream, '\0', null, true);

    PdfSignatureAppearance sap = stp.getSignatureAppearance();
    sap.setCrypto(null, getCertificateChain(), null, PdfSignatureAppearance.WINCER_SIGNED);
    PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
    dic.setReason(siginfo.getSignatureReason());
    dic.setLocation(siginfo.getSignatureLocation());
    dic.setName(siginfo.getSignatureName());
    dic.setDate(new PdfDate(sap.getSignDate()));
    sap.setCryptoDictionary(dic);

    // get the selected rectangle and pagenumber for visible signature
    Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left, siginfo.getSignatureRect().bottom,
            siginfo.getSignatureRect().right, siginfo.getSignatureRect().top);
    int pageNumber = siginfo.getPageNumber();
    sap.setVisibleSignature(signatureRect, pageNumber, null);

    // set signature picture, if there is one
    if (siginfo.getSignatureType() == SignatureType.PICTURE) {
        Image obj_pic = Image.getInstance(siginfo.getImagePath());
        sap.setImage(obj_pic);
    }

    // preserve some space for the contents
    HashMap<PdfName, Integer> exc = new HashMap<PdfName, Integer>();
    exc.put(PdfName.CONTENTS, new Integer(SIGNATURE_MAX_SIZE * 2 + 2));
    sap.preClose(exc);

    // Save placeholder which will be replaced with actual signature later
    byte[] placeHolder = getPlaceHolderArr(SIGNATURE_MAX_SIZE * 2);
    // Replace the contents
    PdfDictionary dic2 = new PdfDictionary();
    dic2.put(PdfName.CONTENTS, new PdfString(placeHolder).setHexWriting(true));
    sap.close(dic2);

    // Calculate the digest
    InputStream data = sap.getRangeStream();

    MessageDigest messageDigest = MessageDigest.getInstance("SHA-256");
    byte buf[] = new byte[8192];
    int n;
    while ((n = data.read(buf)) > 0) {
        messageDigest.update(buf, 0, n);
    }

    hash = messageDigest.digest();

    calendar = Calendar.getInstance();
    ocsp = ocspRequest(cert, issuerCert);
    System.out.println("Got OCSP response, length = " + ocsp.length);

    // Calculate another digest over authenticatedAttributes
    PdfPKCS7 sgn = new PdfPKCS7(null, getCertificateChain(), null, hashAlgo, null, true);
    byte[] sh = sgn.getAuthenticatedAttributeBytes(hash, calendar, ocsp);

    return sh;
}

From source file:androidGLUESigner.pdf.PDFSignerEngine.java

License:Open Source License

/**
 * Simple Sign method to create a signature without Online Timestamp (needed if device
 * has no internet connection)/*www  .  java 2s . c o  m*/
 * 
 * @param inputfile the inputfile
 * @param outputfile the outpuftile
 * @param connection the IConnection Object
 */
public void simpleSign(String inputfile, String outputfile, IConnection connection)
        throws IOException, DocumentException, CertificateException, InvalidKeyException,
        NoSuchAlgorithmException, SignatureException, ReaderException {
    try {
        SignatureInfo sigInfo = getSiginfo();
        PdfReader reader = new PdfReader(inputfile);
        FileOutputStream fout = new FileOutputStream(outputfile);
        PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0', null, true);
        PdfSignatureAppearance sap = stp.getSignatureAppearance();
        sap.setCrypto(null, new Certificate[] { getCertificateChain()[0] }, null,
                PdfSignatureAppearance.SELF_SIGNED);
        sap.setReason(sigInfo.getSignatureReason());
        sap.setLocation(sigInfo.getSignatureLocation());

        // get the selected rectangle and pagenumber for visible signature
        Rectangle signatureRect = new Rectangle(siginfo.getSignatureRect().left,
                siginfo.getSignatureRect().bottom, siginfo.getSignatureRect().right,
                siginfo.getSignatureRect().top);
        int pageNumber = siginfo.getPageNumber();
        sap.setVisibleSignature(signatureRect, pageNumber, null);
        // set signature picture, if there is one
        if (siginfo.getSignatureType() == SignatureType.PICTURE) {
            Image obj_pic = Image.getInstance(siginfo.getImagePath());
            sap.setImage(obj_pic);
        }

        sap.setExternalDigest(new byte[256], new byte[20], null);
        sap.preClose();

        java.io.InputStream inp = sap.getRangeStream();
        byte bytesToHash[] = IOUtils.toByteArray(inp);

        // sign the hash value
        byte[] signed = connection.sign(bytesToHash);

        PdfPKCS7 pdfSignature = sap.getSigStandard().getSigner();
        pdfSignature.setExternalDigest(signed, null, "RSA");

        PdfDictionary dic = new PdfDictionary();
        dic.put(PdfName.CONTENTS, new PdfString(pdfSignature.getEncodedPKCS1()).setHexWriting(true));
        sap.close(dic);
    } catch (Exception e) {
        Logger.toConsole(e);
    }
}

From source file:appli_etudiants.ExportPDF.java

public static void main(Etudiants etudiant)
        throws SQLException, FileNotFoundException, BadElementException, IOException {
    try {/*from w  w  w. j  a  va  2s .c  o m*/
        Document document = new Document(PageSize.A4);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("c:/tesPDF.pdf"));
        document.open();
        PdfContentByte canvas = writer.getDirectContentUnder();
        Image image = Image.getInstance("c:/fond_cv.jpg");
        image.setAbsolutePosition(0, 80);
        canvas.saveState();
        PdfGState state = new PdfGState();
        state.setFillOpacity(0.6f);
        canvas.setGState(state);
        canvas.addImage(image);
        canvas.restoreState();

        LineSeparator lineSepa = new LineSeparator();
        lineSepa.setLineColor(new Color(21, 96, 189));
        Paragraph para1 = new Paragraph();
        Paragraph para2 = new Paragraph(etudiant.getAdresse_rue());
        Paragraph para3 = new Paragraph(etudiant.getAdresse_cp() + " " + etudiant.getAdresse_ville());
        Paragraph para4 = new Paragraph(etudiant.getCourriel(),
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189)));
        Paragraph para5 = new Paragraph(etudiant.getTel_personnel());
        Paragraph para6 = new Paragraph(etudiant.getTel_professionnel());
        Paragraph para7 = new Paragraph(etudiant.getSite_web());
        para1.add(new Chunk(etudiant.getPrenom(),
                FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD, new Color(21, 96, 189))));
        para1.add(
                new Chunk(" " + etudiant.getNom(), FontFactory.getFont(FontFactory.HELVETICA, 20, Font.BOLD)));

        Image image1 = Image.getInstance(DaoS4.getPhoto());
        image1.scalePercent(50);
        image1.setAlignment(Image.RIGHT | Image.TEXTWRAP);
        image1.scaleAbsolute(94, 94);
        document.add(image1);

        document.add(para1);
        document.add(para2);
        document.add(para3);
        document.add(para4);
        document.add(para5);
        document.add(para6);
        para7.setSpacingAfter(25f);
        document.add(para7);
        Paragraph para8 = new Paragraph(DaoS4.getLibelleTitre());
        para8.setSpacingBefore(25f);
        para8.setSpacingAfter(20f);
        document.add(para8);

        Paragraph para9 = new Paragraph(new Chunk("EXPERIENCE PROFESSIONELLE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para9.setSpacingBefore(15f);
        para9.setSpacingAfter(15f);
        document.add(para9);
        document.add(lineSepa);
        Paragraph para10 = new Paragraph(DaoS4.getLibelleExpPro());
        para10.setSpacingAfter(15f);
        document.add(para10);

        Paragraph para11 = new Paragraph(new Chunk("FORMATION",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para11.setSpacingBefore(15f);
        para11.setSpacingAfter(15f);
        document.add(para11);
        document.add(lineSepa);
        Paragraph para12 = new Paragraph(DaoS4.getLibelleFormation());
        para12.setSpacingAfter(15f);
        document.add(para12);

        Paragraph para13 = new Paragraph(new Chunk("INFORMATIQUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para13.setSpacingBefore(15f);
        para13.setSpacingAfter(15f);
        document.add(para13);
        document.add(lineSepa);
        Paragraph para14 = new Paragraph(DaoS4.getLibelleInformatique());
        para14.setSpacingAfter(15f);
        document.add(para14);

        Paragraph para15 = new Paragraph(new Chunk("LANGUE",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para15.setSpacingBefore(15f);
        para15.setSpacingAfter(15f);
        document.add(para15);
        document.add(lineSepa);
        Paragraph para16 = new Paragraph(DaoS4.getLibelleLangue());
        para16.setSpacingAfter(15f);
        document.add(para16);

        Paragraph para17 = new Paragraph(new Chunk("CENTRES D'INTERET",
                FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(21, 96, 189))));
        para17.setSpacingBefore(15f);
        para17.setSpacingAfter(15f);
        document.add(para17);
        document.add(lineSepa);
        Paragraph para18 = new Paragraph(DaoS4.getLibelleInteret());
        para18.setSpacingAfter(15f);
        document.add(para18);

        document.close();
    } catch (DocumentException ex) {
        Logger.getLogger(ExportPDF.class.getName()).log(Level.SEVERE, null, ex);
    }
}

From source file:at.reppeitsolutions.formbuilder.components.pdf.formbuilder.PdfFormBuilderImage.java

License:Open Source License

@Override
public Element render() {
    try {//from ww  w . j  a v a  2s. c  om
        Image image = Image.getInstance(properties.getFile().getFile());
        return image;
    } catch (BadElementException ex) {
        Logger.getLogger(PdfFormBuilderImage.class.getName()).log(Level.SEVERE, null, ex);
    } catch (MalformedURLException ex) {
        Logger.getLogger(PdfFormBuilderImage.class.getName()).log(Level.SEVERE, null, ex);
    } catch (IOException ex) {
        Logger.getLogger(PdfFormBuilderImage.class.getName()).log(Level.SEVERE, null, ex);
    }
    return new ITextParagraph("ERROR: Unable to load image.");
}

From source file:at.tugraz.sss.serv.SSPDFFromXHTMLImageEmbedder.java

License:Apache License

@Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox blockBox,
        UserAgentCallback uac, int cssWidth, int cssHeight) {

    Element element = blockBox.getElement();

    if (element == null) {
        return null;
    }//from  w  ww. j av  a  2 s  .  c  o  m

    String nodeName = element.getNodeName();
    String className = element.getAttribute("class");
    String src = element.getAttribute("src");

    if (!"img".equals(nodeName) || !className.contains("xmyImagex") || src == null) {

        return superFactory.createReplacedElement(layoutContext, blockBox, uac, cssWidth, cssHeight);
    }

    InputStream in = null;

    try {

        try {
            in = new FileInputStream(src);
        } catch (Exception error) {
            throw error;
        }

        final byte[] bytes = IOUtils.toByteArray(in);
        final Image image = Image.getInstance(bytes);
        final FSImage fsImage = new ITextFSImage(image);

        fsImage.scale(cssWidth, cssHeight);

        return new ITextImageElement(fsImage);
    } catch (Exception error) {

        return superFactory.createReplacedElement(layoutContext, blockBox, uac, cssWidth, cssHeight);
    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:at.tugraz.sss.serv.util.SSPDFFromXHTMLImageEmbedder.java

License:Apache License

@Override
public ReplacedElement createReplacedElement(LayoutContext layoutContext, BlockBox blockBox,
        UserAgentCallback uac, int cssWidth, int cssHeight) {

    Element element = blockBox.getElement();

    if (element == null) {
        return null;
    }// ww w  .  ja  va 2 s . c o  m

    String nodeName = element.getNodeName();
    String className = element.getAttribute("class");
    String src = element.getAttribute("src");

    if (!"img".equals(nodeName) || !className.contains("xmyImagex") || src == null) {

        return superFactory.createReplacedElement(layoutContext, blockBox, uac, cssWidth, cssHeight);
    }

    InputStream in = null;

    try {

        try {
            in = new FileInputStream(src);
        } catch (Exception error) {
            throw error;
        }

        final byte[] bytes = IOUtils.toByteArray(in);
        final Image image = Image.getInstance(bytes);
        final FSImage fsImage = new ITextFSImage(image);

        fsImage.scale(cssWidth, cssHeight);

        return new ITextImageElement(fsImage);
    } catch (Exception error) {

        SSLogU.debug(error);

        return superFactory.createReplacedElement(layoutContext, blockBox, uac, cssWidth, cssHeight);

    } finally {
        IOUtils.closeQuietly(in);
    }
}

From source file:be.fedict.eid.applet.service.impl.PdfGenerator.java

License:Open Source License

/**
 * Create a PDF image from eID photo/*w  w w.j  a  v a2s .c  o  m*/
 *
 * @param photoData raw bytes
 * @return PDF image
 * @throws IOException
 * @throws BadElementException
 */
private Image createImageFromPhoto(byte[] photoData) throws IOException, BadElementException {
    Image image = Image.getInstance(photoData);
    image.setAlt("Photo");
    image.setAlignment(Element.ALIGN_CENTER);
    image.setSpacingAfter(20);

    return image;
}