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 java.awt.Image image, final java.awt.Color color)
        throws BadElementException, IOException 

Source Link

Document

Gets an instance of an Image from a java.awt.Image.

Usage

From source file:adams.gui.print.PDFWriter.java

License:Open Source License

/**
 * generates the actual output.//from  w w  w .  j  av  a2s  .c  o  m
 *
 * @throws Exception   if something goes wrong
 */
@Override
public void generateOutput() throws Exception {
    BufferedImage bi;
    Document doc;
    Image image;
    float scale;
    FileOutputStream fos;

    // render image
    bi = createBufferedImage();

    // generate PDF
    scale = (float) m_ImageScale;
    doc = new Document();
    fos = new FileOutputStream(getFile().getAbsoluteFile());
    PdfWriter.getInstance(doc, fos);
    doc.open();
    image = Image.getInstance(Toolkit.getDefaultToolkit().createImage(bi.getSource()), null);
    if (m_ImageRotation != 0) {
        image.setRotationDegrees(m_ImageRotation);
        image.rotate();
    }
    image.scaleToFit(doc.getPageSize().getWidth() * scale, doc.getPageSize().getHeight() * scale);
    doc.add(image);
    doc.close();
    FileUtils.closeQuietly(fos);
}

From source file:com.divudi.bean.BarcodeController.java

public byte[] getBarcodeBytes(String code) {
    Barcode39 code39 = new Barcode39();
    code39.setCode(code);/* w w  w.j  a v a 2s.c  om*/
    code39.setFont(null);
    code39.setExtended(true);
    Image image = null;
    try {
        image = Image.getInstance(code39.createAwtImage(Color.BLACK, Color.WHITE), null);
    } catch (BadElementException | IOException ex) {
        Logger.getLogger(BarcodeController.class.getName()).log(Level.SEVERE, null, ex);
    }
    return image.getRawData();
}

From source file:com.ostrichemulators.semtool.util.ExportUtility.java

License:Open Source License

public static void exportAsPdf(BufferedImage img, File pdf) throws IOException, DocumentException {
    final double MAX_DIM = 14400;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "PNG", baos);
    Image image1 = Image.getInstance(baos.toByteArray(), true);
    Rectangle r;//from ww w.j  a  va2  s .c  o m
    if (image1.getHeight() > MAX_DIM) {
        r = new Rectangle((int) image1.getWidth(), (int) MAX_DIM);
    } else if (image1.getWidth() > MAX_DIM) {
        r = new Rectangle((int) MAX_DIM, (int) image1.getHeight());
    } else {
        r = new Rectangle((int) image1.getWidth() + 20, (int) image1.getHeight() + 20);
    }
    Document document = new Document(r, 15, 25, 15, 25);
    PdfWriter.getInstance(document, new FileOutputStream(pdf));
    document.open();

    int pages = (int) Math.ceil((double) img.getHeight() / MAX_DIM);
    if (pages == 0) {
        pages = 1;
    }
    for (int i = 0; i < pages; i++) {
        BufferedImage temp;
        if (i < pages - 1) {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), (int) MAX_DIM);
        } else {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), img.getHeight() % (int) MAX_DIM);
        }
        File tempFile = new File(i + Constants.PNG);
        ImageIO.write(temp, Constants.PNG, tempFile);
        Image croppedImage = Image.getInstance(i + Constants.PNG);
        document.add(croppedImage);
        tempFile.delete();
        if (i < pages - 1) {
            document.newPage();
        }
    }

    document.close();
}

From source file:com.pablog178.pdfcreator.android.PdfcreatorModule.java

License:Open Source License

private void generateiTextPDFfunction(HashMap args) {
    if (args.containsKey("fileName")) {
        Object fileName = args.get("fileName");
        if (fileName instanceof String) {
            this.fileName = (String) fileName;
            Log.i(PROXY_NAME, "fileName: " + this.fileName);
        }//  www . j  av a  2 s.co m
    } else
        return;

    if (args.containsKey("view")) {
        Object viewObject = args.get("view");
        if (viewObject instanceof TiViewProxy) {
            TiViewProxy viewProxy = (TiViewProxy) viewObject;
            this.view = viewProxy.getOrCreateView();
            if (this.view == null) {
                Log.e(PROXY_NAME, "NO VIEW was created!!");
                return;
            }
            Log.i(PROXY_NAME, "view: " + this.view.toString());
        }
    } else
        return;

    if (args.containsKey("quality")) {
        this.quality = TiConvert.toInt(args.get("quality"));
    }

    if (args.containsKey("pageSize")) {
        Object pageSize = args.get("pageSize");
        if (pageSize instanceof String) {
            if (pageSize.equals("letter")) {
                this.pageSize = PageSize.LETTER;
            } else if (pageSize.equals("A4")) {
                this.pageSize = PageSize.A4;
            } else {
                this.pageSize = PageSize.LETTER;
            }
        }
    }

    TiBaseFile file = TiFileFactory.createTitaniumFile(this.fileName, true);
    Log.i(PROXY_NAME, "file full path: " + file.nativePath());
    try {

        Resources appResources = app.getResources();
        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = this.pageSize.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = this.pageSize.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(this.pageSize, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.i(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.i(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) this.view.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.i(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.i(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / ((float) viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / ((float) viewHeight / PDF_HEIGHT);

        Log.i(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.i(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile();

        // ByteArrayOutputStream stream = new ByteArrayOutputStream(32);
        // viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, stream);
        viewBitmap.compress(Bitmap.CompressFormat.JPEG, this.quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        // ByteBuffer      buffer         = ByteBuffer.allocate(viewBitmap.getByteCount());
        // viewBitmap.copyPixelsToBuffer(buffer);

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.i(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent();

    } catch (Exception exception) {
        Log.e(PROXY_NAME, "Error: " + exception.toString());
        sendErrorEvent(exception.toString());
    }
}

From source file:com.propelics.pdfcreator.PdfcreatorModule.java

License:Open Source License

private void generateiTextPDFfunction(HashMap args) {
    Log.d(PROXY_NAME, "generateiTextPDFfunction()");

    String filename = "";
    TiUIView webview = null;/*from ww w  .  j av a2 s  .  co m*/
    int quality = 100;

    try {
        if (args.containsKey("filename")) {
            filename = (String) args.get("filename");
            Log.d(PROXY_NAME, "filename: " + filename);
        } else
            return;

        if (args.containsKey("webview")) {
            TiViewProxy viewProxy = (TiViewProxy) args.get("webview");
            webview = viewProxy.getOrCreateView();
            Log.d(PROXY_NAME, "webview: " + webview.toString());
        } else
            return;

        if (args.containsKey("quality")) {
            quality = TiConvert.toInt(args.get("quality"));
        }

        TiBaseFile file = TiFileFactory.createTitaniumFile(filename, true);
        Log.d(PROXY_NAME, "file full path: " + file.nativePath());

        OutputStream outputStream = file.getOutputStream();
        final int MARGIN = 0;
        final float PDF_WIDTH = PageSize.LETTER.getWidth() - MARGIN * 2; // A4: 595 //Letter: 612
        final float PDF_HEIGHT = PageSize.LETTER.getHeight() - MARGIN * 2; // A4: 842 //Letter: 792
        final int DEFAULT_VIEW_WIDTH = 980;
        final int DEFAULT_VIEW_HEIGHT = 1384;
        int viewWidth = DEFAULT_VIEW_WIDTH;
        int viewHeight = DEFAULT_VIEW_HEIGHT;

        Document pdfDocument = new Document(PageSize.LETTER, MARGIN, MARGIN, MARGIN, MARGIN);
        PdfWriter docWriter = PdfWriter.getInstance(pdfDocument, outputStream);

        Log.d(PROXY_NAME, "PDF_WIDTH: " + PDF_WIDTH);
        Log.d(PROXY_NAME, "PDF_HEIGHT: " + PDF_HEIGHT);

        WebView view = (WebView) webview.getNativeView();

        if (TiApplication.isUIThread()) {

            viewWidth = view.capturePicture().getWidth();
            viewHeight = view.capturePicture().getHeight();

            if (viewWidth <= 0) {
                viewWidth = DEFAULT_VIEW_WIDTH;
            }

            if (viewHeight <= 0) {
                viewHeight = DEFAULT_VIEW_HEIGHT;
            }

        } else {
            Log.e(PROXY_NAME, "NO UI THREAD");
            viewWidth = DEFAULT_VIEW_WIDTH;
            viewHeight = DEFAULT_VIEW_HEIGHT;
        }

        view.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
        Log.d(PROXY_NAME, "viewWidth: " + viewWidth);
        Log.d(PROXY_NAME, "viewHeight: " + viewHeight);

        float scaleFactorWidth = 1 / (viewWidth / PDF_WIDTH);
        float scaleFactorHeight = 1 / (viewHeight / PDF_HEIGHT);

        Log.d(PROXY_NAME, "scaleFactorWidth: " + scaleFactorWidth);
        Log.d(PROXY_NAME, "scaleFactorHeight: " + scaleFactorHeight);

        Bitmap viewBitmap = Bitmap.createBitmap(viewWidth, viewHeight, Bitmap.Config.ARGB_8888);
        Canvas viewCanvas = new Canvas(viewBitmap);

        // Paint paintAntialias = new Paint();
        // paintAntialias.setAntiAlias(true);
        // paintAntialias.setFilterBitmap(true);

        Drawable bgDrawable = view.getBackground();
        if (bgDrawable != null) {
            bgDrawable.draw(viewCanvas);
        } else {
            viewCanvas.drawColor(Color.WHITE);
        }
        view.draw(viewCanvas);

        TiBaseFile pdfImg = createTempFile(filename);

        viewBitmap.compress(Bitmap.CompressFormat.PNG, quality, pdfImg.getOutputStream());

        FileInputStream pdfImgInputStream = new FileInputStream(pdfImg.getNativeFile());
        byte[] pdfImgBytes = IOUtils.toByteArray(pdfImgInputStream);
        pdfImgInputStream.close();

        pdfDocument.open();
        float yFactor = viewHeight * scaleFactorWidth;
        int pageNumber = 1;

        do {
            if (pageNumber > 1) {
                pdfDocument.newPage();
            }
            pageNumber++;
            yFactor -= PDF_HEIGHT;

            Image pageImage = Image.getInstance(pdfImgBytes, true);
            // Image pageImage = Image.getInstance(buffer.array());
            pageImage.scalePercent(scaleFactorWidth * 100);
            pageImage.setAbsolutePosition(0f, -yFactor);
            pdfDocument.add(pageImage);

            Log.d(PROXY_NAME, "yFactor: " + yFactor);
        } while (yFactor > 0);

        pdfDocument.close();

        sendCompleteEvent(filename);

    } catch (Exception exception) {
        sendErrorEvent(exception);
    }
}

From source file:com.swayam.bhasha.engine.io.writers.impl.PDFImageGenerator.java

License:Apache License

private void makePDFPage(HTMLDocModel htmlDoc, String fileName) throws DocGenerationException, IOException {

    BufferedImage image = getImage(pageDim, htmlDoc);

    /*/*from  www . ja v  a2 s.com*/
     * ByteArrayOutputStream bos = new ByteArrayOutputStream();
     * 
     * ImageIO.write(image, "JPG", bos);
     * 
     * byte[] imageData = bos.toByteArray();
     * 
     * System.out.println("PDFImageGenerator.makePDFPage() " +
     * imageData.length);
     */

    Rectangle pageSize = PageSize.A4;

    if (image.getHeight() > pageSize.getHeight()) {
        pageSize = new Rectangle(image.getWidth(), image.getHeight());
    }

    Document pdfDoc = new Document(pageSize, MARGINS, MARGINS, MARGINS, MARGINS);

    FileOutputStream pdfStream = null;

    try {
        pdfStream = new FileOutputStream(fileName);

        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfStream);

        pdfDoc.addAuthor("Bhasha PDF Generator (Powered by IText)");

        pdfDoc.open();

        PdfContentByte contentByte = pdfWriter.getDirectContent();

        Image pdfImage = Image.getInstance(image, null);

        pdfImage.setAbsolutePosition(0, 0);
        contentByte.addImage(pdfImage);

    } catch (Exception e) {
        throw new DocGenerationException(e);
    } finally {

        pdfDoc.close();

        if (pdfStream != null) {
            try {
                pdfStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

/**
 * loads an image using {@link ImageIO }
 *
 * @param image/*from  w  w  w  . ja  va2s .  c  o  m*/
 * @param opacity the value of opacity
 * @throws VectorPrintException
 * @return the com.itextpdf.text.Image
 */
@Override
public Image loadImage(URL image, float opacity) throws VectorPrintException {
    try {
        if (log.isLoggable(Level.FINE)) {
            log.fine(String.format("loading image from %s", String.valueOf(image)));
        }
        BufferedImage awtim = null;
        if ("file".equals(image.getProtocol())) {
            awtim = makeImageTranslucent(ImageIO.read(new File(image.getFile())), opacity);
        } else {
            awtim = makeImageTranslucent(ImageIO.read(image), opacity);
        }
        return Image.getInstance(awtim, null);
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(String.format("unable to load image %s", image.toString()), ex);
    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

/**
 *
 * @param image the value of image//w ww  .  j  a  va 2  s. c  o m
 * @param opacity the value of opacity
 * @throws VectorPrintException
 */
@Override
public Image loadImage(InputStream image, float opacity) throws VectorPrintException {
    try {
        BufferedImage awtim = makeImageTranslucent(ImageIO.read(image), opacity);
        Image img = Image.getInstance(awtim, null);
        return img;
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(ex);
    }
}

From source file:com.vectorprint.report.itext.DefaultElementProducer.java

License:Open Source License

/**
 *
 * @param image the value of image/* w ww.jav  a2 s . c  o m*/
 * @param opacity the value of opacity
 * @throws VectorPrintException
 */
@Override
public Image loadImage(File image, float opacity) throws VectorPrintException {
    try {
        BufferedImage awtim = makeImageTranslucent(ImageIO.read(image), opacity);
        Image img = Image.getInstance(awtim, null);
        return img;
    } catch (BadElementException | IOException ex) {
        throw new VectorPrintException(ex);
    }
}

From source file:digilib.pdf.PDFStreamWorker.java

License:Open Source License

/**
 * adds an image to the document.//from  www.  j  a v  a 2 s .c o  m
 * 
 * @param doc
 * @param iji
 * @return
 * @throws InterruptedException
 * @throws ExecutionException
 * @throws IOException
 * @throws DocumentException
 */
public Document addImage(Document doc, ImageJobDescription iji)
        throws InterruptedException, ExecutionException, IOException, DocumentException {
    // create image worker
    ImageWorker job = new ImageWorker(dlConfig, iji);
    // submit
    Future<DocuImage> jobTicket = imageJobCenter.submit(job);
    // wait for result
    DocuImage img = jobTicket.get();
    // scale the image
    Image pdfimg = Image.getInstance(img.getAwtImage(), null);
    float docW = PageSize.A4.getWidth() - 2 * PageSize.A4.getBorder();
    float docH = PageSize.A4.getHeight() - 2 * PageSize.A4.getBorder();
    // TODO: do we really scale this again?
    pdfimg.scaleToFit(docW, docH);
    // add to PDF
    doc.add(pdfimg);
    return doc;
}