Example usage for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject getWidth

List of usage examples for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject getWidth

Introduction

In this page you can find the example usage for org.apache.pdfbox.pdmodel.graphics.image PDImageXObject getWidth.

Prototype

@Override
    public int getWidth() 

Source Link

Usage

From source file:gov.samhsa.c2s.common.pdfbox.enhance.HexPdf.java

License:Apache License

/**
 * Draw an image starting at current cursor location. If no flags are given,
 * the top-left corner of the image is positioned at the current cursor
 * position. If one of the flags// w w w.  j  a  v  a  2 s  .com
 * <code>HexPdf.LEFT | HexPdf.CENTER | HexPdf.RIGHT</code> is set, the image
 * is adjusted between <code>leftMargin, rightMargin</code> accordingly. The
 * cursor location is kept unchanged unless the flag
 * <code>HexPdf.NEWLINE</code> is set. This is useful for adding pictures as
 * layers. If <code>HexPdf.NEWLINE</code> is set, the cursor is positioned
 * at <code>leftMargin</code> immediately below the image.
 *
 * @param image the image to be added
 * @param flags see description
 */
public void drawImage(BufferedImage image, int flags) {
    PDImageXObject ximage = null;
    float imW = 0;
    float imH = 0;
    try {
        ximage = JPEGFactory.createFromImage(this, image);
        imW = ximage.getWidth();
        imH = ximage.getHeight();
    } catch (IOException ex) {
        Logger.getLogger(HexPdf.class.getName()).log(Level.SEVERE, null, ex);
    }
    // newpage if image cannot fit on rest of current page
    if ((cursorY - imH) < contentEndY) {
        newPage();
    }
    float imgX = cursorX;
    float imgY = cursorY - imH;
    if ((flags & HexPdf.CENTER) > 0) {
        imgX = contentStartX + ((contentWidth - imW) / 2);
    } else if ((flags & HexPdf.LEFT) > 0) {
        imgX = contentStartX;
    } else if ((flags & HexPdf.RIGHT) > 0) {
        imgX = contentEndX - imW;
    }

    try {
        cs.drawXObject(ximage, imgX, imgY, imW, imH);
    } catch (IOException ex) {
        Logger.getLogger(HexPdf.class.getName()).log(Level.SEVERE, null, ex);
    }

    if ((flags & HexPdf.NEWLINE) > 0) {
        setCursor(contentStartX, imgY - lineSep);
    }
}

From source file:model.objects.Project.java

License:Apache License

/**
 * // w ww .j  a  v a 2 s  . co m
 * @param _doc
 * @param _bi
 * @param _pageindex       index of page to which the BufferedImage is 
 *                      inserted.
 *                      If it is equal to -1, new page is created.
 *                   
 */
public void attatchToPDF(final PDDocument _doc, final BufferedImage _bi, final int _pageindex) {
    PDPage page = null;
    try {
        if (_pageindex == -1) {
            page = new PDPage(new PDRectangle(State.getImageSize().width, State.getImageSize().height));

            _doc.addPage(page);
        } else {
            page = _doc.getPage(_pageindex);
            //             page.setCropBox(new PDRectangle(State.getImageSize().width , 
            //                   State.getImageSize().height ));

        }

        int width = (int) page.getCropBox().getWidth();
        int height = (int) page.getCropBox().getHeight();

        PDImageXObject ximage = LosslessFactory.createFromImage(_doc,
                //                 _bi);
                Utils.resizeImage(width, height, _bi));

        PDPageContentStream content = new PDPageContentStream(_doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        content.drawImage(ximage, 20, 20, ximage.getWidth() * scale, ximage.getHeight() * scale);

        content.close();
        //  LosslessFactory.createFromImage(doc, bim)
        //              content.drawImage(ximage, 0, 0);
        //              content.close();
    } catch (IOException ie) {
        //handle exception
    }
}

From source file:model.util.pdf.PDFUtils.java

License:Apache License

/**
 * Test: Create pdf from image and pdf file.
 *
 * @param _inputFile    pdf input//from  w  w w.j av a  2s . com
 * @param _imagePath    image input
 * @param _outputFile    pdf output
 *
 * @throws IOException occurs if reading the data fails.
 */
public void saveAsPdf(String _imagePath, String _outputFile) throws IOException {

    PDDocument doc = null;
    try {

        // create new document and insert empty page to the document.
        doc = new PDDocument();
        PDPage page = new PDPage();
        doc.addPage(page);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage, 
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(_imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 1f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

        contentStream.close();
        doc.save(_outputFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:org.esteco.jira.pdf.AddImageToPDF.java

License:Apache License

/**
 * Add an image to an existing PDF document.
 *
 * @param inputFile  The input PDF to add the image to.
 * @param imagePath  The filename of the image to put in the PDF.
 * @param outputFile The file to write to the pdf to.
 * @throws IOException If there is an error writing the data.
 *///from   w  ww  .j  ava2s  . co  m
public void createPDFFromImage(String inputFile, String imagePath, String outputFile) throws IOException {
    // the document
    PDDocument doc = null;
    try {
        doc = PDDocument.load(new File(inputFile));

        //we will add the image to the first page.
        PDPage page = doc.getPage(0);
        //page.setRotation(90);

        // createFromFile is the easiest way with an image file
        // if you already have the image in a BufferedImage,
        // call LosslessFactory.createFromImage() instead
        PDImageXObject pdImage = PDImageXObject.createFromFile(imagePath, doc);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);

        // contentStream.drawImage(ximage, 20, 20 );
        // better method inspired by http://stackoverflow.com/a/22318681/535646
        // reduce this value if the image is too large
        float scale = 0.4f;
        contentStream.drawImage(pdImage, 20, 20, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

        contentStream.close();
        doc.save(outputFile);
    } finally {
        if (doc != null) {
            doc.close();
        }
    }
}

From source file:org.fit.pdfdom.PDFBoxTree.java

License:Open Source License

protected void processImageOperation(List<COSBase> arguments) throws IOException {
    COSName objectName = (COSName) arguments.get(0);
    PDXObject xobject = getResources().getXObject(objectName);
    if (xobject instanceof PDImageXObject) {
        PDImageXObject pdfImage = (PDImageXObject) xobject;
        BufferedImage outputImage = pdfImage.getImage();

        // x, y and size are handled by css attributes but still need to rotate the image so pulling
        // only rotation out of the matrix so no giant whitespace offset from translations
        Matrix ctm = getGraphicsState().getCurrentTransformationMatrix();
        AffineTransform tr = ctm.createAffineTransform();
        double rotate = Math.atan2(tr.getShearY(), tr.getScaleY()) - Math.toRadians(pdpage.getRotation());
        outputImage = ImageUtils.rotateImage(outputImage, rotate);
        byte[] imageData = getImageData(outputImage);

        Rectangle2D imageBounds = pdfImage.getImage().getRaster().getBounds();
        AffineTransform pageTransform = createCurrentPageTransformation();
        AffineTransform imageTransform = new AffineTransform(ctm.createAffineTransform());
        imageTransform.scale(1.0 / pdfImage.getWidth(), -1.0 / pdfImage.getHeight());
        imageTransform.translate(0, -pdfImage.getHeight());
        pageTransform.concatenate(imageTransform);
        Rectangle2D bounds = pageTransform.createTransformedShape(imageBounds).getBounds2D();

        float x = (float) bounds.getX();
        float y = (float) bounds.getY();

        renderImage(x, y, (float) bounds.getWidth(), (float) bounds.getHeight(), "image/png", imageData);
    }//  w w  w  .ja v  a2  s  . c  o m
}

From source file:uia.pdf.gridbag.model.ImageCell.java

License:Apache License

@Override
public void accept(ContentView cv, GridBagDrawer view, PDPageContentStream contentStream, Point bottomLeft,
        Map<String, Object> data) {
    PDImageXObject img = null;
    try {// www.  j a  v  a  2s  . c om
        img = PDImageXObject.createFromFile(this.fileName, cv.getDoc().getDocument());
        float pct = (float) getHeight() / (float) img.getHeight();
        contentStream.drawImage(img, bottomLeft.x, bottomLeft.y, img.getWidth() * pct, img.getHeight() * pct);
    } catch (Exception ex) {

    }
}

From source file:Utils.PDF.java

public static void print(String nFactura, Date fecha, String empleado, ClienteVO cliente,
        List<ProductosCanasta> productos, BigDecimal subtotal) throws IOException {
    DateFormat dateAnio = new SimpleDateFormat("yyyy");
    DateFormat dateMes = new SimpleDateFormat("MM");
    DateFormat dateDia = new SimpleDateFormat("dd");
    String direccion = "facturas" + "/" + dateAnio.format(fecha) + "/" + dateMes.format(fecha) + "/"
            + dateDia.format(fecha);/* ww w  . j a v  a2 s.c o m*/
    File dir = new File(direccion);
    if (dir.exists()) {
        System.out.println("Ya exitiste la carpeta");
    } else {
        dir.mkdirs();
    }
    DateFormat dateF = new SimpleDateFormat("kk-mm-ss_dd-MM-yyyy");
    String fileName = direccion + "/" + dateF.format(fecha) + ".pdf";
    String imagem = "bill-512.png";
    System.out.println("Se creo su factura");
    PDDocument doc = new PDDocument();
    PDPage page = new PDPage(PDRectangle.A4);
    PDPageContentStream content = new PDPageContentStream(doc, page);
    doc.addPage(page);

    PDImageXObject pdImage = null;
    try {
        pdImage = PDImageXObject.createFromFile(imagem, doc);
    } catch (IOException e1) {
        System.out.println("ERROR no cargo logo factura");
    }
    float scale = 0.2f;

    // Titulo factura     
    content.beginText();
    content.setFont(PDType1Font.HELVETICA, 26);
    content.setNonStrokingColor(Color.BLUE);
    content.newLineAtOffset(250, 785);
    content.showText("Factura Bazar A&J");
    content.endText();

    // Logo
    content.drawImage(pdImage, 30, 725, pdImage.getWidth() * scale, pdImage.getHeight() * scale);

    //Cuadro info empresa
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 700, 280, 1);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(304, 700, 1, -65);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 634, 280, 1);
    content.setNonStrokingColor(Color.BLACK);
    content.addRect(25, 700, 1, -65);
    content.fill();

    // Texto info empresa
    content.beginText();
    content.setLeading(15); // da el salto de pagina
    content.setFont(PDType1Font.COURIER, 10);
    content.newLineAtOffset(30, 685);
    content.showText("Direccion: " + "Coop. Universitaria Mz 258 Solar 9");
    content.newLine();
    content.showText("Ciudad   : " + "Guayaquil, Ecuador");
    content.newLine();
    content.showText("Telefono : " + "042937914");
    content.newLine();
    content.showText("RUC      : " + "1710034065");
    content.endText();

    //Cuadro datos factura
    content.setNonStrokingColor(Color.BLACK); //arriba
    content.addRect(380, 700, 200, 1);
    content.setNonStrokingColor(Color.BLACK); // derecha
    content.addRect(579, 700, 1, -65);
    content.setNonStrokingColor(Color.BLACK); // abajo
    content.addRect(380, 634, 200, 1);
    content.setNonStrokingColor(Color.BLACK); // izquierda
    content.addRect(380, 700, 1, -65);
    content.fill();

    DateFormat dateFormat = new SimpleDateFormat("dd - MM - yyyy");
    DateFormat dateFormath = new SimpleDateFormat("h:mm a");
    // Texto datos factura
    content.beginText();
    content.setLeading(15); // da el salto de pagina
    content.setFont(PDType1Font.COURIER, 10);
    content.newLineAtOffset(390, 685);
    content.showText("Factura N: " + nFactura);
    content.newLine();
    content.showText("Fecha    : " + dateFormat.format(fecha));
    content.newLine();
    content.showText("Hora     : " + dateFormath.format(fecha));
    content.newLine();
    content.showText("Empleado : " + empleado);
    content.endText();

    // Linea Divisoria
    content.setNonStrokingColor(Color.BLUE); // abajo
    content.addRect(0, 620, 595, 1);
    content.fill();

    // Datos Cliente
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER, 13);
    content.newLineAtOffset(30, 600);
    content.showText("Nombre   : " + cliente.getNombre_C() + cliente.getApellido_C());
    content.newLine();
    content.showText("Direcion : " + cliente.getDireccion_C());
    content.newLine();
    content.showText("Telefono : " + cliente.getConvencional_C());
    content.endText();

    content.setNonStrokingColor(Color.BLUE); // abajo
    content.addRect(0, 550, 595, 1);
    content.fill();

    content.setNonStrokingColor(Color.BLACK); // numero
    content.addRect(30, 510, 50, 15);
    content.fill();
    content.beginText();
    content.setLeading(0);
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(45, 515);
    content.showText("N.");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // cantidad
    content.addRect(90, 510, 40, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(94, 515);
    content.showText("Cant");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // Descripcion
    content.addRect(140, 510, 270, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(230, 515);
    content.showText("Descripcion");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // cantidad
    content.addRect(430, 510, 70, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(440, 515);
    content.showText("P.Unit");
    content.endText();

    content.setNonStrokingColor(Color.BLACK); // importe
    content.addRect(510, 510, 70, 15);
    content.fill();
    content.beginText();
    content.setLeading(18); // da el salto de pagina
    content.setNonStrokingColor(Color.WHITE);
    content.setFont(PDType1Font.COURIER_BOLD, 13);
    content.newLineAtOffset(515, 515);
    content.showText("Importe");
    content.endText();

    int cont = 1;
    int vertical = 490;
    // Productos
    for (ProductosCanasta p : productos) {
        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(45, vertical);
        content.showText("" + cont);
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(105, vertical);
        content.showText("" + p.getCantidad());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 11);
        content.newLineAtOffset(145, vertical);
        content.showText("" + p.getNombre());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(440, vertical);
        content.showText("" + p.getPrecio_venta());
        content.endText();

        content.beginText();
        content.setNonStrokingColor(Color.BLACK);
        content.setFont(PDType1Font.COURIER, 13);
        content.newLineAtOffset(520, vertical);
        content.showText("" + p.getPrecio_venta().multiply(new BigDecimal(p.getCantidad())));
        content.endText();

        cont++;
        vertical -= 20;
    }

    // max x pagina 595 x 841.8898
    content.setNonStrokingColor(Color.BLUE); // total
    content.addRect(0, 60, 595, 1);
    content.fill();

    /// TOTAL
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(500, 35);
    content.showText(subtotal.multiply(new BigDecimal(0.14)).add(subtotal).setScale(2, 3).toString());
    content.endText();

    content.beginText();
    content.newLineAtOffset(510, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("TOTAL");
    content.endText();

    // IVA
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(430, 35);
    content.showText("" + 14 + "%");
    content.endText();

    content.beginText();
    content.newLineAtOffset(430, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("IVA");
    content.endText();

    // Subtotal
    content.beginText();
    content.setNonStrokingColor(Color.BLACK);
    content.setFont(PDType1Font.COURIER_BOLD, 20);
    content.newLineAtOffset(300, 35);
    content.showText(subtotal.toString());
    content.endText();

    content.beginText();
    content.newLineAtOffset(300, 20);
    content.setFont(PDType1Font.COURIER_BOLD, 15);
    content.showText("SUBTOTAL");
    content.endText();

    content.close();
    doc.save(fileName);
    doc.close();
    Process p = Runtime.getRuntime().exec(new String[] { "xpdf", fileName });
    System.out.println("your file created in : " + System.getProperty("user.dir"));
}