Example usage for com.itextpdf.text Image getScaledHeight

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

Introduction

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

Prototype

public float getScaledHeight() 

Source Link

Document

Gets the scaled height of the image.

Usage

From source file:objects.manipulate.java

public static void createPDF(String filename, String[] RESOURCES)
        throws DocumentException, FileNotFoundException, IOException {
    Document document = new Document();
    document.setMargins(0, 0, 0, 0);/*from w  w w  .j a v  a 2  s . c o  m*/
    Rectangle rectangle = new Rectangle(0, 0, 742, 960);
    document.setPageSize(rectangle);
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filename));
    document.open();

    Image img;
    for (int i = 0; i < RESOURCES.length; i++) {
        //img = Image.getInstance(String.format("resources/img/%s", RESOURCES[i]));
        img = Image.getInstance(RESOURCES[i]);
        if (img.getScaledWidth() > 742 || img.getScaledHeight() > 960) {
            img.scaleToFit(742, 960);
        }

        document.add(img);
    }

    document.close();
}

From source file:org.alex73.skarynka.scan.process.pdf.PdfCreator.java

License:Open Source License

public static void create(File outFile, File[] jpegs) throws Exception {
    Document pdf = new Document();
    pdf.setMargins(0, 0, 0, 0);/*from  w  ww  .  ja  v a2s.  c  o  m*/

    Image image0 = Jpeg.getInstance(jpegs[0].getPath());
    pdf.setPageSize(new Rectangle(0, 0, image0.getScaledWidth(), image0.getScaledHeight()));

    PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(outFile));

    pdf.open();
    float minWidth = Float.MAX_VALUE, maxWidth = Float.MIN_VALUE, minHeight = Float.MAX_VALUE,
            maxHeight = Float.MIN_VALUE;
    for (File jpeg : jpegs) {

        Image image = Jpeg.getInstance(jpeg.getPath());

        float width, height;

        width = image.getScaledWidth();
        height = image.getScaledHeight();
        minWidth = Math.min(minWidth, width);
        maxWidth = Math.max(maxWidth, width);
        minHeight = Math.min(minHeight, height);
        maxHeight = Math.max(maxHeight, height);

        pdf.setPageSize(new Rectangle(0, 0, width, height));
        pdf.newPage();
        pdf.add(image);
    }

    pdf.close();
    writer.flush();
    writer.close();
}

From source file:org.dspace.disseminate.CitationDocument.java

/**
 * Attempts to add a Logo to the document from the given resource. Returns
 * true on success and false on failure.
 *
 * @param doc The document to add the logo to. (Added to the top right
 * corner of the first page./*from w ww  .ja  v a 2  s . c  om*/
 * @param writer The writer associated with the given Document.
 * @param res The resource/path to the logo file. This file can be any of
 * the following formats:
 *  GIF, PNG, JPEG, PDF
 *
 * @return Succesfully added logo to document.
 */
private boolean addLogoToDocument(Document doc, PdfWriter writer, String res) {
    boolean ret = false;
    try {
        //First we try to get the logo as if it is a Java Resource
        URL logoURL = this.getClass().getResource(res);
        log.debug(res + " -> " + logoURL.toString());
        if (logoURL == null) {
            logoURL = new URL(res);
        }

        if (logoURL != null) {
            String mtype = URLConnection.guessContentTypeFromStream(logoURL.openStream());
            if (mtype == null) {
                mtype = URLConnection.guessContentTypeFromName(res);
            }
            log.debug("Determined MIMETYPE of logo: " + mtype);
            if (PDF_MIMES.contains(mtype)) {
                //Handle pdf logos.
                PdfReader reader = new PdfReader(logoURL);
                PdfImportedPage logoPage = writer.getImportedPage(reader, 1);
                Image logo = Image.getInstance(logoPage);
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                doc.add(logo);
                ret = true;
            } else if (RASTER_MIMES.contains(mtype)) {
                //Use iText's Image class
                Image logo = Image.getInstance(logoURL);

                //Determine the position of the logo (upper-right corner) and
                //place it there.
                float x = doc.getPageSize().getWidth() - doc.rightMargin() - logo.getScaledWidth();
                float y = doc.getPageSize().getHeight() - doc.topMargin() - logo.getScaledHeight();
                logo.setAbsolutePosition(x, y);
                writer.getDirectContent().addImage(logo);
                ret = true;
            } else if (SVG_MIMES.contains(mtype)) {
                //Handle SVG Logos
                log.error("SVG Logos are not supported yet.");
            } else {
                //Cannot use other mimetypes
                log.debug("Logo MIMETYPE is not supported.");
            }
        } else {
            log.debug("Could not create URL to Logo resource: " + res);
        }
    } catch (Exception e) {
        log.error("Could not add logo (" + res + ") to cited document: " + e.getMessage());
        ret = false;
    }
    return ret;
}

From source file:org.h819.commons.file.MyPDFUtils.java

/**
 * ??/*w  w  w  . ja  v a  2s  .co  m*/
 *
 * @param srcPdf         ?
 * @param destPdf        
 * @param waterMarkText  ?
 * @param waterMarkImage ?
 */
public static void addWaterMarkFile(File srcPdf, File destPdf, String waterMarkText, File waterMarkImage)
        throws IOException, DocumentException {

    if (waterMarkText == null && waterMarkImage == null)
        throw new FileNotFoundException(waterMarkText + " " + waterMarkImage + " all null.");

    if (srcPdf == null || !srcPdf.exists() || !srcPdf.isFile())
        throw new FileNotFoundException("pdf file :  '" + srcPdf + "' does not exsit.");

    if (!FilenameUtils.getExtension(srcPdf.getAbsolutePath()).toLowerCase().equals("pdf"))
        return;

    if (waterMarkImage != null) {
        if (!waterMarkImage.exists() || !waterMarkImage.isFile())
            throw new FileNotFoundException("img file :  '" + srcPdf + "' does not exsit.");

        if (!FilenameUtils.getExtension(waterMarkImage.getAbsolutePath()).toLowerCase().equals("png"))
            throw new FileNotFoundException("image file '" + srcPdf
                    + "'  not png.(???? pdf )");
    }

    PdfReader reader = getPdfReader(srcPdf);

    int n = reader.getNumberOfPages();
    PdfStamper stamper = getPdfStamper(srcPdf, destPdf);

    //
    //        HashMap<String, String> moreInfo = new HashMap<String, String>();
    //        moreInfo.put("Author", "H819 create");
    //        moreInfo.put("Producer", "H819 Producer");
    //        Key = CreationDate, Value = D:20070425182920
    //        Key = Producer, Value = TH-OCR 2000 (C++/Win32)
    //        Key = Author, Value = TH-OCR 2000
    //        Key = Creator, Value = TH-OCR PDF Writer

    // stamp.setMoreInfo(moreInfo);

    // text
    Phrase text = null;
    if (waterMarkText != null) {
        //
        Font bfont = getPdfFont();
        bfont.setSize(35);
        bfont.setColor(new BaseColor(192, 192, 192));
        text = new Phrase(waterMarkText, bfont);
    }
    // image watermark
    Image img = null;
    float w = 0;
    float h = 0;
    if (waterMarkImage != null) {
        img = Image.getInstance(waterMarkImage.getAbsolutePath());
        w = img.getScaledWidth();
        h = img.getScaledHeight();
        //  img.
        img.setRotationDegrees(45);

    }

    // transparency
    PdfGState gs1 = new PdfGState();
    gs1.setFillOpacity(0.5f);
    // properties
    PdfContentByte over;
    Rectangle pageSize;
    float x, y;
    // loop over every page
    for (int i = 1; i <= n; i++) {
        pageSize = reader.getPageSizeWithRotation(i);
        x = (pageSize.getLeft() + pageSize.getRight()) / 2;
        y = (pageSize.getTop() + pageSize.getBottom()) / 2;
        //  pdf pdf ???
        over = stamper.getOverContent(i);
        // ?
        // over = stamp.getUnderContent(i);
        // ?? over.beginText(); over.endText(); ?
        // ,?,:????
        over.saveState(); //??
        over.setGState(gs1);

        if (waterMarkText != null && waterMarkImage != null) { // 
            if (i % 2 == 1) {
                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            } else
                over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        } else if (waterMarkText != null) { //?

            ColumnText.showTextAligned(over, Element.ALIGN_CENTER, text, x, y, 45);
            //?? ,?, :?????
            // ...

        } else { //?
            over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
        }

        over.restoreState();//???
    }

    stamper.close();
    reader.close();

}

From source file:org.inspira.condominio.pdf.DocumentoEstadoDeCuenta.java

private void bakeContent(String path, String imgResString) throws IOException, DocumentException {
    File outFile = new File(path);
    outFile.getParentFile().mkdirs();/*w w  w  .ja  v a 2 s  . c  om*/
    PdfWriter.getInstance(documento, new FileOutputStream(outFile));
    documento.open();
    documento.add(new Paragraph(
            "Ciudad de Mxico, "
                    + DateFormat.getDateInstance(DateFormat.MEDIUM, Locale.getDefault()).format(new Date()),
            new Font(FontFamily.HELVETICA, 18, Font.NORMAL, new BaseColor(0x000000))));
    Paragraph intro = new Paragraph(new Phrase("Comprobante de estado de cuenta", F_NORMAL));
    intro.setAlignment(Paragraph.ALIGN_RIGHT);
    intro.setSpacingBefore(10f);
    documento.add(intro);
    Image image = Image.getInstance(imgResString);
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(image.getScaledWidth());
    table.setLockedWidth(true);
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    //cell.setCellEvent(new ImageBackgroundEvent(image));
    cell.setFixedHeight(image.getScaledHeight());
    table.addCell(cell);
    documento.add(table);
    Paragraph p1 = new Paragraph("Estado de cuenta: ".concat(idEdoCta), F_NORMAL);
    p1.setSpacingBefore(5f);
    p1.setSpacingAfter(25f);
    p1.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(p1);
    documento.add(new Paragraph("Pagos", F_NORMAL));
    agregaTablaDePagos();
    Paragraph pNotas = new Paragraph("Notas: ".concat(notas), F_NORMAL);
    pNotas.setSpacingAfter(12f);
    pNotas.setSpacingAfter(2f);
    documento.add(pNotas);
    Paragraph pAdeudos = new Paragraph("Adeudos", F_NORMAL);
    pAdeudos.setSpacingBefore(25f);
    documento.add(pAdeudos);
    agregaTablaDeAdeudos();
    documento.add(new Paragraph(
            "Recuerde que puede consultar su estado de pagos y adeudos desde la aplicacin mvil o directamente con su administrador.",
            F_NORMAL));
    Paragraph hechoPor = new Paragraph("Elabor:", F_NORMAL);
    hechoPor.setSpacingBefore(30f);
    hechoPor.setSpacingAfter(15f);
    documento.add(hechoPor);
    Paragraph nombreDelAdmin = new Paragraph(admin, F_NORMAL);
    nombreDelAdmin.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDelAdmin);
    Paragraph nombreDeCondominio = new Paragraph(condominio, F_NORMAL);
    nombreDeCondominio.setAlignment(Paragraph.ALIGN_CENTER);
    documento.add(nombreDeCondominio);
}

From source file:org.inspira.condominio.pdf.DocumentoIngreso.java

private void addHousePicture(String imgResStr) throws BadElementException, IOException, DocumentException {
    Image image = Image.getInstance(imgResStr);
    PdfPTable table = new PdfPTable(1);
    table.setTotalWidth(image.getScaledWidth());
    table.setLockedWidth(true);//from   www .ja  v a2  s . com
    PdfPCell cell = new PdfPCell();
    cell.setBorder(0);
    //cell.setCellEvent(new ImageBackgroundEvent(image));
    cell.setFixedHeight(image.getScaledHeight());
    table.addCell(cell);
    table.setHorizontalAlignment(PdfPTable.ALIGN_RIGHT);
    documento.add(table);
}

From source file:org.obiba.mica.PdfUtils.java

License:Open Source License

public static void addImage(byte[] input, OutputStream output, Image image, String placeholder)
        throws IOException, DocumentException {
    try (PdfReaderAutoclosable pdfReader = new PdfReaderAutoclosable(input);
            PdfStamperAutoclosable pdfStamper = new PdfStamperAutoclosable(pdfReader, output)) {
        AcroFields form = pdfStamper.getAcroFields();
        List<AcroFields.FieldPosition> positions = form.getFieldPositions(placeholder);

        positions.forEach(p -> {/*  w w w  .j  a v  a 2  s  .  com*/
            image.scaleToFit(p.position.getWidth(), p.position.getHeight());
            image.setAbsolutePosition(
                    p.position.getLeft() + (p.position.getWidth() - image.getScaledWidth()) / 2,
                    p.position.getBottom() + (p.position.getHeight() - image.getScaledHeight()) / 2);
            PdfContentByte cb = pdfStamper.getOverContent(p.page);

            try {
                cb.addImage(image);
            } catch (DocumentException e) {
                throw Throwables.propagate(e);
            }
        });
    }
}

From source file:Tables.PrinterClass.java

public void footer(Document doc) throws DocumentException {
    Paragraph paragraph = new Paragraph("@" + this.companyName);
    doc.add(paragraph);//from  w w  w  .j av a  2  s  .c o m
    dNow = new Date();

    String prodDate;
    prodDate = "Created on the " + dateOnly.format(dNow) + " at " + timeOnly.format(dNow);

    //////////////////

    PdfPTable timeOfProduction = new PdfPTable(1);

    PdfPCell cell = new PdfPCell(new Phrase(prodDate.trim(), smallFooter));
    cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
    cell.setColspan(3);
    cell.setBorder(0);
    if (prodDate.trim().equalsIgnoreCase("")) {
        cell.setMinimumHeight(10f);
    }

    timeOfProduction.addCell(cell);
    doc.add(timeOfProduction);

    try {
        Image img = Image.getInstance(this.companyLogo);
        img.scaleAbsolute(20f, 20f);

        img.setAbsolutePosition((PageSize.A4.getWidth() - img.getScaledWidth()),
                (PageSize.A4.getHeight() - img.getScaledHeight())); //place the image at the bottom right position

        img.setAlt("Unity Systems");
    } catch (Exception ex) {

    }

}

From source file:utils.pdf.cv_templates.Template1.java

private void addImageBackgroundTop() throws DocumentException, IOException {
    Image back_img = Image.getInstance(BACK_IMAGE);
    back_img.setAbsolutePosition((PageSize.A4.getWidth() - back_img.getScaledWidth()) / 2,
            (PageSize.A4.getHeight() - back_img.getScaledHeight()) / 2);
    back_img.setAbsolutePosition(0, 823);
    document.add(back_img);/*  w ww  . ja v a2s  .  com*/
}

From source file:utils.pdf.cv_templates.Template1.java

private void addImageBackgroundBottom() throws DocumentException, IOException {
    Image back_img = Image.getInstance(BACK_IMAGE);
    back_img.setAbsolutePosition((PageSize.A4.getWidth() - back_img.getScaledWidth()) / 2,
            (PageSize.A4.getHeight() - back_img.getScaledHeight()) / 2);
    back_img.setAbsolutePosition(0, 0);/*from  ww  w .  ja v  a2s.c  o  m*/
    document.add(back_img);
}