Example usage for com.itextpdf.text Image getInstance

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

Introduction

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

Prototype

public static Image getInstance(final Image image) 

Source Link

Document

gets an instance of an Image

Usage

From source file:com.semfapp.adamdilger.semf.ImageFile.java

License:Open Source License

public Image getImage() {

    if (image == null) {
        try {/*from ww  w.j a  v a  2s  .c o m*/
            String path = imageFile.getPath();

            Bitmap bmp = getBitmapForPdf(500, 500);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
            byte[] byteArray = stream.toByteArray();

            image = Image.getInstance(byteArray);
            //                image = Image.getInstance(path);
        } catch (Exception e) {
        }
    }

    return image;
}

From source file:com.semfapp.adamdilger.semf.Pdf.java

License:Open Source License

private void createPDFNew(String filePath, String htmlString, @Nullable ArrayList<ImageFile> images) {

    File file = null;//  www  . j a  va2  s  .co m
    try {
        file = new File(filePath);

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        // step 4

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(activity.getAssets().open("styles.css"));
        cssResolver.addCss(cssFile);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // Pipelines

        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        Drawable d = activity.getResources().getDrawable(R.drawable.logo_icon);
        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

        Image image = Image.getInstance(bitmapData);
        image.setAbsolutePosition(35, 763);
        image.scalePercent(12);
        document.add(image);

        p.parse(new ByteArrayInputStream(htmlString.getBytes(StandardCharsets.UTF_8)));

        if (images != null) {
            System.out.println("Adding IMage");

            for (int x = 0; x < images.size(); x++) {
                Image cursor = images.get(x).getImage();

                float ratio = cursor.getPlainHeight() / cursor.getPlainWidth();

                float imgWidth = document.getPageSize().getWidth() - 100;
                float imgHeight = document.getPageSize().getHeight() - 100;

                cursor.scaleToFit(new Rectangle(imgWidth, imgHeight));

                document.add(cursor);
            }
        }

        // step 5
        document.close();

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

From source file:com.skatettoo.reportes.Generador.java

public String generarPDF() throws Exception {
    try {//from ww  w .j ava  2 s .co m
        String path = FacesContext.getCurrentInstance().getExternalContext().getRealPath("img");
        path = path.substring(0, path.indexOf("\\build"));
        path = path + "\\web\\img\\";
        Document doc = new Document(PageSize.A4, 36, 36, 10, 10);
        PdfPTable tabla = new PdfPTable(4);
        PdfWriter.getInstance(doc, new FileOutputStream(path + "\\archivo\\reporte.pdf\\"));
        doc.open();
        Image img = Image.getInstance(path + "Skatetoo4.png");
        img.scaleAbsolute(40, 40);
        img.setAlignment(Element.ALIGN_LEFT);
        doc.add(img);
        doc.addTitle(this.titulo);
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        doc.addAuthor("\n ");
        tabla.setWidthPercentage(100);
        tabla.setWidths(new float[] { 1.4f, 0.8f, 0.8f, 0.8f });
        Object font = new Font(Font.FontFamily.HELVETICA, 14, Font.BOLD, BaseColor.WHITE);
        PdfPCell cell = new PdfPCell(new Phrase("Reporte de tatuadores", (Font) font));
        cell.setColspan(4);
        cell.setHorizontalAlignment(Element.ALIGN_CENTER);
        cell.setPaddingTop(0f);
        cell.setPaddingBottom(7f);
        cell.setBackgroundColor(new BaseColor(0, 0, 0));
        cell.setBorder(0);
        cell.setBorderWidthBottom(2f);
        tabla.addCell(cell);
        tabla.addCell("Tatuador");
        tabla.addCell("Cantidad de diseos");
        tabla.addCell("Citas realizadas");
        tabla.addCell("Noticias publicadas");
        for (Usuario u : this.getUsu()) {
            tabla.addCell(u.getNombre() + " " + u.getApellido());
            tabla.addCell(String.valueOf(u.getDisenioList().size()));
            tabla.addCell(String.valueOf(u.getCitaList1().size()));
            tabla.addCell(String.valueOf(u.getNoticiaList().size()));
        }
        doc.add(tabla);
        doc.bottomMargin();
        /* doc.add(new Paragraph("Tatuador mas solicitado"));
         for(Usuario u : this.getUs()){
        doc.add(new Paragraph(u.getNombre() + " " + u.getApellido()));
         }*/
        doc.close();
        FacesContext context = FacesContext.getCurrentInstance();
        ExternalContext externalContext = context.getExternalContext();

        externalContext.responseReset();
        externalContext.setResponseContentType("application/pdf");
        externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");

        FileInputStream inputStream = new FileInputStream(new File(path + "\\archivo\\reporte.pdf\\"));
        OutputStream outputStream = externalContext.getResponseOutputStream();

        byte[] buffer = new byte[1024];
        int length;
        while ((length = inputStream.read(buffer)) > 0) {
            outputStream.write(buffer, 0, length);
        }

        inputStream.close();
        context.responseComplete();
    } catch (Exception e) {
        throw e;
    }
    return "";
}

From source file:com.softwaremagico.tm.pdf.complete.elements.BaseElement.java

License:Open Source License

public static PdfPCell createImageCell(String path) throws DocumentException, IOException {
    Image img = Image.getInstance(path);
    PdfPCell cell = new PdfPCell(img, true);
    setCellProperties(cell);/*from ww w. j  av a 2 s  .com*/
    return cell;
}

From source file:com.softwaremagico.tm.pdf.complete.elements.BaseElement.java

License:Open Source License

public static PdfPCell createLogoCell() throws DocumentException, IOException {
    Image image = Image.getInstance(
            CharacterBasicsCompleteTableFactory.class.getResource("/" + FadingSunsTheme.LOGO_IMAGE));
    PdfPCell cell = new PdfPCell(image, true);
    setCellProperties(cell);/*from  www .  j  a  v  a 2 s .  co m*/
    cell.setHorizontalAlignment(Element.ALIGN_CENTER);
    cell.setPaddingTop(10);
    return cell;
}

From source file:com.softwaremagico.tm.pdf.complete.events.SheetAlternatedBackgroundEvent.java

License:Open Source License

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    try {//from   w  w  w  .  ja  va  2  s  .c  om
        rightCorner = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.RIGHT_CORNER_IMAGE));
        rightCorner.setAbsolutePosition(document.getPageSize().getWidth() - IMAGE_WIDTH,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_TOP_BORDER);
        rightCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        leftCorner = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.LEFT_CORNER_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        leftCorner.setAbsolutePosition(IMAGE_BORDER,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_TOP_BORDER);
        leftCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitleRight = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        float barWidth = document.getPageSize().getWidth() - IMAGE_WIDTH - IMAGE_BORDER * 2;
        mainTitleRight.setAbsolutePosition(IMAGE_HEIGHT + IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_TOP_BORDER - 2);
        mainTitleRight.scaleAbsolute(barWidth, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitleLeft = Image.getInstance(
                SheetAlternatedBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        // leftCorner.setAbsolutePosition(IMAGE_BORDER,
        // document.getPageSize().getHeight() - IMAGE_HEIGHT -
        // IMAGE_BORDER);
        float barWidth = document.getPageSize().getWidth() - IMAGE_WIDTH - IMAGE_BORDER * 2;
        mainTitleLeft.setAbsolutePosition(IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_TOP_BORDER - 2);
        mainTitleLeft.scaleAbsolute(barWidth, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

}

From source file:com.softwaremagico.tm.pdf.complete.events.SheetBackgroundEvent.java

License:Open Source License

@Override
public void onOpenDocument(PdfWriter writer, Document document) {
    try {/*from   w w w  . j a v  a 2s.  co  m*/
        rightCorner = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.RIGHT_CORNER_IMAGE));
        rightCorner.setAbsolutePosition(document.getPageSize().getWidth() - IMAGE_WIDTH,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_BORDER);
        rightCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        leftCorner = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.LEFT_CORNER_IMAGE));
        leftCorner.setAbsolutePosition(IMAGE_BORDER,
                document.getPageSize().getHeight() - IMAGE_HEIGHT - IMAGE_BORDER);
        leftCorner.scaleToFit(IMAGE_WIDTH, IMAGE_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

    try {
        mainTitle = Image
                .getInstance(SheetBackgroundEvent.class.getResource("/" + FadingSunsTheme.MAIN_TITLE_IMAGE));
        float barWeight = document.getPageSize().getWidth() - IMAGE_WIDTH * 2;
        mainTitle.setAbsolutePosition(IMAGE_HEIGHT + IMAGE_BORDER * 2 + 3,
                document.getPageSize().getHeight() - BAR_HEIGHT - IMAGE_BORDER);
        mainTitle.scaleAbsolute(barWeight, BAR_HEIGHT);
    } catch (BadElementException | IOException e) {
        PdfExporterLog.errorMessage(this.getClass().getName(), e);
    }

}

From source file:com.sparksoftsolutions.com.pdfcreator.MainActivity.java

private File generatePDFFromImages(ArrayList<ImageItem> images) {
    Document document = new Document();

    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard, generateFileName());

    try {//from w  w  w  .j a v  a2  s.c om
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    } catch (Exception ex) {
        return null;
    }

    // document = new PdfDocument();
    Boolean opened = false;
    for (ImageItem img : images) {

        Bitmap bitmap = BitmapFactory.decodeFile(img.path);

        try {

            Image image = Image.getInstance(img.path);
            document.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));

            if (!opened) {
                document.open();
                opened = true;
            } else
                document.newPage();
            document.add(image);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    document.close();
    return file;
}

From source file:com.systemevent.jsfclass.util.FormatoPDF.java

/**
 * Constructor de la clase, inicializa la imagen que se utilizara en el membrete
 *///from  w  ww  . ja  v  a2s.  com
public FormatoPDF(String nombre) {
    try {
        PdfPCell celda1 = new PdfPCell(new Phrase("Nombre Cliente"));
        PdfPCell celda2 = new PdfPCell(new Phrase(nombre));

        imagen = Image.getInstance(
                "C:\\Users\\Jose_Gascon\\Documents\\ProyectoSystemEvent\\sysevent\\src\\main\\webapp\\resources\\imagenes\\logoconstruccion.jpg");
        imagen.setAbsolutePosition(30, 720f);
        imagen.scaleAbsolute(100, 100);
        celda1.setBorder(Rectangle.BOTTOM);
        celda2.setBorder(Rectangle.BOTTOM);
        celda2.setBorder(Rectangle.BOTTOM | Rectangle.RIGHT);

        table.addCell(celda1);
        table.addCell(celda2);

        table.setTotalWidth(350f);

    } catch (Exception r) {
        System.err.println("Error al leer la imagen");
    }
}

From source file:com.tommontom.pdfsplitter.PdfMerge.java

public static void doMerge(java.util.List<InputStream> list, String[] imageList, String[] listWordExcels,
        OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    writer.setFullCompression();// w w w.  j a  va2s. c om
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Image img;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }

    }
    for (int i = 0; i < imageList.length; i++) {
        document.newPage();
        if (imageList[i] != null) {
            img = Image.getInstance(String.format("%s", imageList[i]));
            Rectangle one = new Rectangle(img.getPlainWidth(), img.getPlainHeight());
            document.setPageSize(one);
            if (img.getScaledWidth() > img.getScaledHeight()) {
                img.rotate();
            }
            if (img.getScaledWidth() > 792 || img.getScaledHeight() > 792) {
                img.scaleToFit(792, 792);

            }
            img.setDpi(150, 150);
            document.add(img);
        }
    }
    for (int i = 0; i < listWordExcels.length; i++) {
        if (imageList[i] != null) {
            File input = new File(listWordExcels[i]);
            File output = new File(listWordExcels[i] + ".pdf");
            String outputS = listWordExcels[i] + ".pdf";
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(input, output);
            PdfReader readerWord = new PdfReader(outputS);
            PdfImportedPage page = writer.getImportedPage(readerWord, readerWord.getNumberOfPages());
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}