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

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

Introduction

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

Prototype

@Override
    public int getHeight() 

Source Link

Usage

From source file:ch.dowa.jassturnier.pdf.PdfGenerator.java

public PDRectangle getImageSizePdf(PDImageXObject img) {

    float actImageWidth = img.getWidth();
    float actImageHeight = img.getHeight();
    float actRatio = actImageWidth / actImageHeight;

    float imageWidth = 0F;
    float imageHeight = 0F;

    if (maxRatio() < actRatio) {
        imageWidth = imgMaxWidth();/* w w w. j av  a 2  s . c  om*/
        imageHeight = imageWidth / actRatio;
    } else if (1 < actRatio && actRatio <= maxRatio()) {
        imageHeight = imgMaxHeight();
        imageWidth = imageHeight * actRatio;
    } else if (actRatio <= 1) {
        imageHeight = imgMaxHeight();
        imageWidth = imageHeight * actRatio;
    }

    return new PDRectangle(imageWidth, imageHeight);
}

From source file:com.baseprogramming.pdwriter.PdWriter.java

License:Apache License

/**
 * Draw an image on the current page.//from   w ww.  j av  a2 s  .  c  om
 * @param imageFile File containing image.
 * @param style paragraph style to use
 * @param width image width. Uses image actual width if argument is less than or equal to 0
 * @param height image height. Uses image actual height if argument is less than or equal to 0
 * @throws RuntimeException 
 */
public void drawImage(File imageFile, PdParagraph style, float width, float height) {
    try {
        PDImageXObject imageObject = PDImageXObject.createFromFileByContent(imageFile, document);

        float actualWidth = (width <= 0) ? imageObject.getWidth() : width;
        float actualHeight = (height <= 0) ? imageObject.getHeight() : height;
        yPosition -= actualHeight;
        if (yPosition <= meta.getLowerLeftY()) {
            createNewPage();
            yPosition -= actualHeight;
            if (yPosition < meta.getLowerLeftY()) {
                yPosition = meta.getLowerLeftY();
            }
        }
        try (final PDPageContentStream stream = createStream()) {
            stream.drawImage(imageObject, style.getLeftX(), yPosition, actualWidth, actualHeight);
            yPosition -= style.getLineHeight();
        }
    } catch (IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
}

From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java

License:Open Source License

/**
 * Prints the current page to a pdf file
 *
 * @throws IOException if the file cannot be found or the pdf cannot be created
 *//* ww  w. ja  v  a  2  s  . com*/
protected void printCurrentPageToPdf() throws IOException {
    io.clearActivePoints();
    ddf.updateAll(io.getActivePoints());
    String fileName = DBMenuBar.cleanseFileName(
            Main.getState().getCurrentFileName().substring(0, Main.getState().getCurrentFileName().length() - 6)
                    + ": " + Main.getCurrentPage().toDisplayString().replaceAll("\\|", "-"));
    File f = new File(Main.getFilePath());
    f.mkdirs();
    f = new File(Main.getFilePath() + fileName + ".pdf");

    BufferedImage bi = new BufferedImage(getSize().width, getSize().height, BufferedImage.TYPE_INT_ARGB);
    Graphics g = bi.createGraphics();
    paintComponent(g);
    g.dispose();

    PDDocument doc = null;

    try {
        doc = new PDDocument();
        boolean crop = true;
        State.print(field);
        for (Point p : Main.getCurrentPage().getDots().keySet())
            if (p.getX() < field.getWidth() * 0.1 + field.getX()
                    || p.getX() > field.getWidth() * 0.9 + field.getX()) {
                crop = false;
                break;
            }
        if (Main.getCurrentPage().getTextPoint().getX() < field.getWidth() * 0.1 + field.getX()
                || Main.getCurrentPage().getTextPoint().getX() + 100 > field.getWidth() * 0.9 + field.getX())
            crop = false;

        float scale = 1.0f;
        if (crop)
            scale = 0.8f;

        PDPage page = new PDPage(new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight()));
        doc.addPage(page);
        PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi);
        PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

        contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()),
                -1 * field.y, pdImage.getWidth(), pdImage.getHeight());

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

From source file:com.evanbelcher.DrillBook.display.DBDesktopPane.java

License:Open Source License

/**
 * Prints every page to a pdf file//from  w  w  w.jav a 2 s .  com
 *
 * @throws IOException if the file cannot be found or the pdf cannot be created
 */
protected void printAllPagesToPdf() throws IOException {
    io.clearActivePoints();
    ddf.updateAll(io.getActivePoints());
    File f = new File(Main.getFilePath());
    f.mkdirs();
    String fileName = DBMenuBar.cleanseFileName(Main.getState().getCurrentFileName().substring(0,
            Main.getState().getCurrentFileName().length() - 6));

    f = new File(Main.getFilePath() + fileName + " full show" + ".pdf");

    boolean crop = true;
    a: for (int pageNum : Main.getPages().keySet()) {
        for (Point p : Main.getPages().get(pageNum).getDots().keySet()) {
            if (p.getX() < field.getWidth() * 0.1 + field.getX()
                    || p.getX() > field.getWidth() * 0.9 + field.getX()) {
                crop = false;
                break a;
            }
        }
        if (Main.getPages().get(pageNum).getTextPoint().getX() < field.getWidth() * 0.1 + field.getX()
                || Main.getPages().get(pageNum).getTextPoint().getX() + 100 > field.getWidth() * 0.9
                        + field.getX()) {
            crop = false;
            break;
        }
    }

    float scale = 1.0f;
    if (crop)
        scale = 0.8f;
    PDDocument doc = null;

    try {
        doc = new PDDocument();

        for (int i : Main.getPages().keySet()) {
            Main.setCurrentPage(i);

            BufferedImage bi = new BufferedImage(getSize().width, getSize().height,
                    BufferedImage.TYPE_INT_ARGB);
            Graphics g = bi.createGraphics();
            paintComponent(g);
            g.dispose();

            PDPage page = new PDPage(
                    new PDRectangle((float) field.getWidth() * scale, (float) field.getHeight()));
            doc.addPage(page);
            PDImageXObject pdImage = LosslessFactory.createFromImage(doc, bi);
            PDPageContentStream contentStream = new PDPageContentStream(doc, page, AppendMode.APPEND, true);

            contentStream.drawImage(pdImage, -1 * field.x - (float) (((1 - scale) / 2.0f) * field.getWidth()),
                    -1 * field.y, pdImage.getWidth(), pdImage.getHeight());

            contentStream.close();
        }
        doc.save(f);
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } finally {
        if (doc != null)
            doc.close();
        pdf.updateAfterPrintAll();
    }
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String//  www  .ja  v a2 s  .  c  om
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImage(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    if (imageFile != null) {
        imageFile.delete();
    }
    return pdfFile;
}

From source file:com.fileOperations.ImageToPDF.java

/**
 * create PDF from image and scales it accordingly to fit in a single page
 *
 * @param folderPath String/*from   ww  w . j  a  va  2 s . c o m*/
 * @param imageFileName String
 * @return String new filename
 */
public static String createPDFFromImageNoDelete(String folderPath, String imageFileName) {
    String pdfFile = FilenameUtils.removeExtension(imageFileName) + ".pdf";
    String image = folderPath + imageFileName;
    PDImageXObject pdImage = null;
    File imageFile = null;
    FileInputStream fileStream = null;
    BufferedImage bim = null;

    File attachmentLocation = new File(folderPath);
    if (!attachmentLocation.exists()) {
        attachmentLocation.mkdirs();
    }

    // the document
    PDDocument doc = null;
    PDPageContentStream contentStream = null;

    try {
        doc = new PDDocument();
        PDPage page = new PDPage(PDRectangle.LETTER);
        float margin = 72;
        float pageWidth = page.getMediaBox().getWidth() - 2 * margin;
        float pageHeight = page.getMediaBox().getHeight() - 2 * margin;

        if (image.toLowerCase().endsWith(".jpg")) {
            imageFile = new File(image);
            fileStream = new FileInputStream(image);
            pdImage = JPEGFactory.createFromStream(doc, fileStream);
            //            } else if ((image.toLowerCase().endsWith(".tif")
            //                    || image.toLowerCase().endsWith(".tiff"))
            //                    && TIFFCompression(image) == COMPRESSION_GROUP4) {
            //                imageFile = new File(image);
            //                pdImage = CCITTFactory.createFromFile(doc, imageFile);
        } else if (image.toLowerCase().endsWith(".gif") || image.toLowerCase().endsWith(".bmp")
                || image.toLowerCase().endsWith(".png")) {
            imageFile = new File(image);
            bim = ImageIO.read(imageFile);
            pdImage = LosslessFactory.createFromImage(doc, bim);
        }

        if (pdImage != null) {
            if (pdImage.getWidth() > pdImage.getHeight()) {
                page.setRotation(270);
                PDRectangle rotatedPage = new PDRectangle(page.getMediaBox().getHeight(),
                        page.getMediaBox().getWidth());
                page.setMediaBox(rotatedPage);
                pageWidth = page.getMediaBox().getWidth() - 2 * margin;
                pageHeight = page.getMediaBox().getHeight() - 2 * margin;
            }
            Dimension pageSize = new Dimension((int) pageWidth, (int) pageHeight);
            Dimension imageSize = new Dimension(pdImage.getWidth(), pdImage.getHeight());
            Dimension scaledDim = PDFBoxTools.getScaledDimension(imageSize, pageSize);
            float startX = page.getMediaBox().getLowerLeftX() + margin;
            float startY = page.getMediaBox().getUpperRightY() - margin - scaledDim.height;

            doc.addPage(page);
            contentStream = new PDPageContentStream(doc, page);
            contentStream.drawImage(pdImage, startX, startY, scaledDim.width, scaledDim.height);
            contentStream.close();
            doc.save(folderPath + pdfFile);
        }
    } catch (IOException ex) {
        ExceptionHandler.Handle(ex);
        return "";
    } finally {
        if (doc != null) {
            try {
                doc.close();
            } catch (IOException ex) {
                ExceptionHandler.Handle(ex);
                return "";
            }
        }
    }
    if (fileStream != null) {
        try {
            fileStream.close();
        } catch (IOException ex) {
            ExceptionHandler.Handle(ex);
            return "";
        }
    }
    if (bim != null) {
        bim.flush();
    }
    return pdfFile;
}

From source file:com.fngry.monk.biz.demo.pdf.pdfbox.PrintImageLocations.java

License:Apache License

/**
 * This is used to handle an operation.//  w  w w  .ja v  a 2s. c  om
 *
 * @param operator The operation to perform.
 * @param operands The list of arguments.
 *
 * @throws IOException If there is an error processing the operation.
 */
@Override
protected void processOperator(Operator operator, List<COSBase> operands) throws IOException {
    String operation = operator.getName();
    if ("Do".equals(operation)) {
        COSName objectName = (COSName) operands.get(0);
        PDXObject xobject = getResources().getXObject(objectName);
        if (xobject instanceof PDImageXObject) {
            PDImageXObject image = (PDImageXObject) xobject;

            if ("png".equals(image.getSuffix())) {
                return;
            }

            int imageWidth = image.getWidth();
            int imageHeight = image.getHeight();

            //                System.out.println("Found image [" + objectName.getName() + "]");

            Matrix ctmNew = getGraphicsState().getCurrentTransformationMatrix();
            float imageXScale = ctmNew.getScalingFactorX();
            float imageYScale = ctmNew.getScalingFactorY();

            // position in user space units. 1 unit = 1/72 inch at 72 dpi
            //                System.out.println("position in PDF = " + ctmNew.getTranslateX() + ", " + ctmNew.getTranslateY() + " in user space units");
            //                // raw size in pixels
            //                System.out.println("raw image size  = " + imageWidth + ", " + imageHeight + " in pixels");
            //                // displayed size in user space units
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in user space units");

            // displayed size in inches at 72 dpi rendering
            //                imageXScale /= 72;
            //                imageYScale /= 72;
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in inches at 72 dpi rendering");
            //                // displayed size in millimeters at 72 dpi rendering
            //                imageXScale *= 25.4;
            //                imageYScale *= 25.4;
            //                System.out.println("displayed size  = " + imageXScale + ", " + imageYScale + " in millimeters at 72 dpi rendering");
            System.out.println();

            //                BufferedImage bufferImage = image.getImage();
            //                ByteArrayOutputStream os = new ByteArrayOutputStream();
            //                ImageIO.write(bufferImage, image.getSuffix(), os);
            //
            //                String fileName = this.pageName + "_" + objectName.getName() + "." + image.getSuffix();
            //                Path outputFile = new File("/Users/gaorongyu/Downloads/temp/"
            //                        + this.pageName + "_" + objectName.getName() + "." + image.getSuffix()).toPath();

            ImageInfo imageInfo = new ImageInfo((int) ctmNew.getTranslateX(), (int) ctmNew.getTranslateY(),
                    (int) imageXScale, (int) imageYScale);
            imageInfo.setImage(image);
            imageInfo.setObjectName(objectName);

            imageInfoList.add(imageInfo);
            //                java.nio.file.Files.copy(new ByteArrayInputStream(os.toByteArray()), outputFile);

        } else if (xobject instanceof PDFormXObject) {
            PDFormXObject form = (PDFormXObject) xobject;
            showForm(form);
        }
    } else {
        super.processOperator(operator, operands);
    }
}

From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java

License:Open Source License

private static void centerImage(PDImageXObject image, PDPage page, PDDocument doc) throws IOException {

    centerImage(image, page, doc, image.getHeight(), image.getWidth());

}

From source file:com.github.gujou.deerbelling.sonarqube.service.PdfApplicationGenerator.java

License:Open Source License

private static void leftImage(PDImageXObject image, PDPage page, PDDocument doc) throws IOException {
    leftImage(image, page, doc, image.getHeight(), image.getWidth());
}

From source file:es.rickyepoderi.pdfimages.Converter.java

License:Open Source License

/**
 * Method that converts the images provides to pdf and writes to the target 
 * path specified.//from ww w  . j a va  2 s.  com
 *
 * @param output The file to write
 * @param bimages The buffered images to put in the pdf
 * @throws IOException Some error generating the PDF
 */
public void images2Pdf(File output, File... files) throws IOException {
    try (PDDocument pdDocument = new PDDocument()) {
        for (File file : files) {
            PDPage page = new PDPage();
            pdDocument.addPage(page);
            try (PDPageContentStream pageStream = new PDPageContentStream(pdDocument, page,
                    PDPageContentStream.AppendMode.APPEND, true, true)) {
                BufferedImage bimage = ImageIO.read(file);
                PDImageXObject img = LosslessFactory.createFromImage(pdDocument, bimage);
                Dimension scaledDim = getScaledDimension(new Dimension(img.getWidth(), img.getHeight()),
                        new Dimension((int) page.getMediaBox().getWidth(),
                                (int) page.getMediaBox().getHeight()));
                pageStream.drawImage(img, 0, 0, scaledDim.width, scaledDim.height);
            }
        }
        pdDocument.save(output);
    }
}