Example usage for com.lowagie.text Image scaleToFit

List of usage examples for com.lowagie.text Image scaleToFit

Introduction

In this page you can find the example usage for com.lowagie.text Image scaleToFit.

Prototype

public void scaleToFit(float fitWidth, float fitHeight) 

Source Link

Document

Scales the image so that it fits a certain width and height.

Usage

From source file:org.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public void printPhotos(String contextPath, List<org.oscarehr.common.model.Document> photos)
        throws DocumentException {
    writer.setStrictImageSequence(true);

    if (photos.size() > 0) {
        Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);
        Paragraph p = new Paragraph();
        p.setAlignment(Paragraph.ALIGN_LEFT);
        Phrase phrase = new Phrase(LEADING, "\n\n", getFont());
        p.add(phrase);//from  ww w. j  a va  2 s.  c  om
        phrase = new Phrase(LEADING, "Photos:", obsfont);
        p.add(phrase);
        getDocument().add(p);
    }

    for (org.oscarehr.common.model.Document doc : photos) {
        Image img = null;
        try {
            //             String location = oscar.OscarProperties.getInstance().getProperty("DOCUMENT_DIR").trim() + doc.getDocfilename();
            String location = EDocUtil.getDocumentPath(doc.getDocfilename());
            logger.info("adding image " + location);
            img = Image.getInstance(location);
        } catch (IOException e) {
            MiscUtils.getLogger().error("error:", e);
            continue;
        }
        img.scaleToFit(getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());

        Chunk chunk = new Chunk(img, getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());

        Paragraph p = new Paragraph();
        p.add(img);
        p.add(new Phrase("Description:" + doc.getDocdesc(), getFont()));
        getDocument().add(p);

    }
}

From source file:org.oscarehr.common.service.PdfRecordPrinter.java

License:Open Source License

public void printDiagrams(List<EFormValue> diagrams) throws DocumentException {
    writer.setStrictImageSequence(true);

    EFormValueDao eFormValueDao = (EFormValueDao) SpringUtils.getBean("EFormValueDao");

    if (diagrams.size() > 0) {
        Font obsfont = new Font(getBaseFont(), FONTSIZE, Font.UNDERLINE);
        Paragraph p = new Paragraph();
        p.setAlignment(Paragraph.ALIGN_LEFT);
        Phrase phrase = new Phrase(LEADING, "\n\n", getFont());
        p.add(phrase);/*ww w .  jav  a  2s  .c o  m*/
        phrase = new Phrase(LEADING, "Diagrams:", obsfont);
        p.add(phrase);
        getDocument().add(p);
    }

    for (EFormValue value : diagrams) {
        //this is a form from our group, and our appt
        String imgPath = OscarProperties.getInstance().getProperty("eform_image");
        EFormValue imageName = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "image");
        EFormValue drawData = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "DrawData");
        EFormValue subject = eFormValueDao.findByFormDataIdAndKey(value.getFormDataId(), "subject");

        String image = imgPath + File.separator + imageName.getVarValue();
        logger.debug("image for eform is " + image);
        GraphicalCanvasToImage convert = new GraphicalCanvasToImage();
        File tempFile = null;
        try {
            tempFile = File.createTempFile("graphicImg", ".png");
            FileOutputStream fos = new FileOutputStream(tempFile);
            convert.convertToImage(image, drawData.getVarValue(), "PNG", fos);
            logger.debug("converted image is " + tempFile.getName());
            fos.close();
        } catch (IOException e) {
            logger.error("Error", e);
            if (tempFile != null) {
                tempFile.delete();
            }
            continue;
        }

        Image img = null;
        try {
            logger.info("adding diagram " + tempFile.getAbsolutePath());
            img = Image.getInstance(tempFile.getAbsolutePath());
        } catch (IOException e) {
            logger.error("error:", e);
            continue;
        }
        img.scaleToFit(getDocument().getPageSize().getWidth() - getDocument().leftMargin()
                - getDocument().rightMargin(), getDocument().getPageSize().getHeight());
        Paragraph p = new Paragraph();
        p.add(img);
        p.add(new Phrase("Subject:" + subject.getVarValue(), getFont()));
        getDocument().add(p);

        tempFile.deleteOnExit();
    }

}

From source file:org.oss.pdfreporter.pdf.Page.java

License:Open Source License

@Override
public void draw(IImage image, float x, float y, float width, float height, ScaleMode mode)
        throws DocumentException {
    try {// ww w  .  ja va  2s  .  co  m
        Image pdfImage = null;
        switch (mode) {
        case NONE:
            pdfImage = getImage(image);
            PdfTemplate t = delegate.getPdfWriter().getDirectContent().createTemplate(width, height);
            t.addImage(pdfImage, pdfImage.getWidth(), 0, 0, pdfImage.getHeight(), 0,
                    height - pdfImage.getHeight());
            pdfImage = Image.getInstance(t);
            break;
        case SCALE:
            pdfImage = getImage(image);
            pdfImage.scaleAbsolute(width, height);
            break;
        case SIZE:
            pdfImage = getImage(image);
            pdfImage.scaleToFit(width, height);
            break;
        }
        pdfImage.setAbsolutePosition(x, y);
        delegate.addImage(pdfImage);
    } catch (Exception e) {
        throw new DocumentException(e);
    }

}

From source file:org.pentaho.reporting.engine.classic.core.modules.output.table.rtf.helper.RTFTextExtractor.java

License:Open Source License

protected void processRenderableContent(final RenderableReplacedContentBox node) {
    float targetWidth = (float) StrictGeomUtility.toExternalValue(node.getWidth());
    float targetHeight = (float) StrictGeomUtility.toExternalValue(node.getHeight());

    try {//from  w  w w .ja va  2  s.c  o m
        final RenderableReplacedContent rpc = node.getContent();
        final Object rawObject = rpc.getRawObject();
        if (rawObject instanceof ImageContainer) {
            final Image image = imageCache.getImage((ImageContainer) rawObject);
            if (image == null) {
                return;
            }
            final StyleContext currentContext = getCurrentContext();
            if (getTextLength() > 0) {
                currentContext.add(getText());
                clearText();
            }

            image.scaleToFit(targetWidth, targetHeight);
            currentContext.add(image);
        } else if (rawObject instanceof DrawableWrapper) {
            final StrictBounds rect = new StrictBounds(node.getX(), node.getY(), node.getWidth(),
                    node.getHeight());
            final ImageContainer ic = RenderUtility.createImageFromDrawable((DrawableWrapper) rawObject, rect,
                    node, metaData);
            if (ic == null) {
                return;
            }
            final Image image = imageCache.getImage(ic);
            if (image == null) {
                return;
            }

            final StyleContext currentContext = getCurrentContext();
            if (getTextLength() > 0) {
                currentContext.add(getText());
                clearText();
            }
            image.scaleToFit(targetWidth, targetHeight);
            currentContext.add(image);
        }
    } catch (DocumentException ioe) {
        throw new InvalidReportStateException("Failed to extract text", ioe);
    } catch (IOException e) {
        // double ignore ..
        throw new InvalidReportStateException("Failed to extract text", e);
    }

}

From source file:org.revager.export.PDFPageEventHelper.java

License:Open Source License

@Override
public void onEndPage(PdfWriter writer, Document document) {
    int columnNumber;

    try {/*  w ww .ja v a 2s.c om*/
        Rectangle page = document.getPageSize();
        float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin();

        /*
         * Write marks
         */
        setMarks(writer, document);

        /*
         * Define fonts
         */
        headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font headFont = new Font(headBaseFont, headFontSize);

        footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED);
        Font footFont = new Font(footBaseFont, footFontSize);

        /*
         * Cell fill for space between head/foot and content
         */
        PdfPCell cellFill = new PdfPCell();
        cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f));
        cellFill.setBorderWidth(0);

        /*
         * Write head
         */
        if (headLogoPath != null) {
            columnNumber = 2;
        } else {
            columnNumber = 1;
        }

        PdfPTable head = new PdfPTable(columnNumber);

        Phrase phraseTitle = new Phrase(headTitle, headFont);

        PdfPCell cellTitle = new PdfPCell(phraseTitle);
        cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT);
        cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM);
        cellTitle.setPaddingTop(0);
        cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f));
        cellTitle.setPaddingLeft(0);
        cellTitle.setPaddingRight(0);
        cellTitle.setBorderWidthTop(0);
        cellTitle.setBorderWidthBottom(0.5f);
        cellTitle.setBorderWidthLeft(0);
        cellTitle.setBorderWidthRight(0);

        head.addCell(cellTitle);

        if (headLogoPath != null) {
            Image headLogo = Image.getInstance(headLogoPath);
            headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f));

            PdfPCell cellLogo = new PdfPCell(headLogo);
            cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT);
            cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM);
            cellLogo.setPaddingTop(0);
            cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f));
            cellLogo.setPaddingLeft(0);
            cellLogo.setPaddingRight(0);
            cellLogo.setBorderWidthTop(0);
            cellLogo.setBorderWidthBottom(0.5f);
            cellLogo.setBorderWidthLeft(0);
            cellLogo.setBorderWidthRight(0);

            head.addCell(cellLogo);

            head.addCell(cellFill);
        }

        head.addCell(cellFill);

        head.setTotalWidth(pageWidth);
        head.writeSelectedRows(0, -1, document.leftMargin(),
                page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent());

        /*
         * Write foot
         */
        if (footText == null) {
            footText = " ";
        }

        PdfPTable foot = new PdfPTable(1);

        foot.addCell(cellFill);

        PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont));
        cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT);
        cellFootText.setVerticalAlignment(Element.ALIGN_TOP);
        cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f));
        cellFootText.setPaddingBottom(0);
        cellFootText.setPaddingLeft(0);
        cellFootText.setPaddingRight(0);
        cellFootText.setBorderWidthTop(0.5f);
        cellFootText.setBorderWidthBottom(0);
        cellFootText.setBorderWidthLeft(0);
        cellFootText.setBorderWidthRight(0);

        foot.addCell(cellFootText);

        /*
         * Print page numbers
         */
        PdfContentByte contentByte = writer.getDirectContent();
        contentByte.saveState();

        String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber());

        float textSize = footBaseFont.getWidthPoint(text, footFontSize);
        float textBase = document.bottom() - PDFTools.cmToPt(1.26f);
        contentByte.beginText();
        contentByte.setFontAndSize(footBaseFont, footFontSize);

        float adjust;
        if (footText.trim().equals("")) {
            adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize);
        } else {
            adjust = 0;
        }

        contentByte.setTextMatrix(document.left() + adjust, textBase);
        contentByte.showText(text);
        contentByte.endText();
        contentByte.addTemplate(template, document.left() + adjust + textSize, textBase);

        contentByte.stroke();
        contentByte.restoreState();

        foot.setTotalWidth(pageWidth);
        foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(),
                writer.getDirectContent());
    } catch (Exception e) {
        /*
         * Not part of unit testing because this exception is only thrown if
         * an internal error occurs.
         */
        throw new ExceptionConverter(e);
    }
}

From source file:org.tpspencer.tal.mvc.document.DocumentWriterImpl.java

License:Apache License

public void writeImage(String image, String legend, AppElement element) {
    Section section = sections.size() > 0 ? sections.peek() : chapter;

    URL url = this.getClass().getResource(image);
    if (url == null)
        return;/*  www  .  j a v  a2  s  . c o  m*/

    try {
        Image img = Image.getInstance(url);
        if (img != null) {
            img.scaleToFit(document.getPageSize().getWidth() - 100, document.getPageSize().getHeight() - 100);
            section.add(img);
            if (legend != null)
                writeParagraph(legend, element);
        }
    } catch (Exception e) {
        throw new IllegalArgumentException("Cannot add given image to document", e);
    }
}

From source file:org.unitime.timetable.export.rooms.RoomsExportPDF.java

License:Apache License

protected A getCell(RoomDetailInterface room, Column column, ExportContext context) {
    switch (column.getColumn()) {
    case NAME://from   ww  w . j a  v a2  s  . c om
        A a = new A(room.hasDisplayName() ? MESSAGES.label(room.getLabel(), room.getDisplayName())
                : room.getLabel());
        for (DepartmentInterface d : room.getDepartments())
            if (d.getDeptCode().equals(context.getDepartment()) && d.getPreference() != null)
                a.setColor(d.getPreference().getColor());
        return a;

    case EXTERNAL_ID:
        return new A(room.hasExternalId() ? room.getExternalId() : "");

    case TYPE:
        return new A(room.getRoomType().getLabel());

    case CAPACITY:
        return new A(room.getCapacity() == null ? "0" : room.getCapacity().toString()).right();

    case EXAM_CAPACITY:
        return new A(room.getExamCapacity() == null ? "" : room.getExamCapacity().toString()).right();

    case AREA:
        return new A(room.getArea() == null ? "" : context.getAreaFormat().format(room.getArea())).right();

    case COORDINATES:
        return new A(
                room.hasCoordinates()
                        ? context.getCoordinateFormat().format(room.getX()) + ","
                                + context.getCoordinateFormat().format(room.getY())
                        : "");

    case ROOM_CHECK:
        return new A(room.isIgnoreRoomCheck() ? MESSAGES.exportFalse() : MESSAGES.exportTrue());

    case DISTANCE_CHECK:
        return new A(room.isIgnoreTooFar() ? MESSAGES.exportFalse() : MESSAGES.exportTrue());

    case PREFERENCE:
        if (!room.hasDepartments())
            return new A();
        a = new A();
        for (DepartmentInterface d : room.getDepartments()) {
            if (d.getPreference() == null)
                continue;
            a.add(new A(d.getPreference().getAbbv() + " " + context.dept2string(d, true))
                    .color(d.getPreference().getColor()));
        }
        return a;

    case MAP:
        if (room.hasMiniMapUrl()) {
            try {
                Image image = Image.getInstance(new URL(room.getMiniMapUrl()));
                image.scaleToFit(150f, 100f);
                image.setBorder(Rectangle.BOX);
                image.setBorderWidth(1f);
                image.setBorderColor(new Color(Integer.parseInt("9CB0CE", 16)));
                return new A(image);
            } catch (Exception e) {
                return new A();
            }
        } else {
            return new A();
        }

    case PICTURES:
        AttachmentTypeInterface type = (column.getIndex() == 0 ? null
                : context.getPictureTypes().get(column.getIndex() - 1));
        if (room.hasPictures(type)) {
            a = new A();
            for (RoomPictureInterface picture : room.getPictures(type)) {
                RoomPicture rp = RoomPictureDAO.getInstance().get(picture.getUniqueId());
                if (rp != null) {
                    try {
                        Image image = Image.getInstance(rp.getDataFile());
                        image.scaleToFit(150f, 100f);
                        image.setBorder(Rectangle.BOX);
                        image.setBorderWidth(1f);
                        image.setBorderColor(new Color(Integer.parseInt("9CB0CE", 16)));
                        a.add(new A(image));
                    } catch (Exception e) {
                    }
                }
            }
            return a;
        } else {
            return new A();
        }

    case AVAILABILITY:
        return availability(room, false, context);

    case DEPARTMENTS:
        if (!room.hasDepartments())
            return new A();
        if (context.isAllDepartments(room.getDepartments()))
            return new A(MESSAGES.departmentsAllLabel()).set(F.ITALIC);
        a = new A();
        for (DepartmentInterface d : room.getDepartments()) {
            A b = new A(context.dept2string(d, true)).color(d.getColor());
            if (d.equals(room.getControlDepartment()))
                b.underline();
            a.add(b);
        }
        return a;

    case CONTROL_DEPT:
        return new A(context.dept2string(room.getControlDepartment(), true))
                .color(room.getControlDepartment() == null ? null : room.getControlDepartment().getColor());

    case EXAM_TYPES:
        if (!room.hasExamTypes())
            return new A();
        a = new A();
        for (ExamTypeInterface t : room.getExamTypes()) {
            a.add(new A(t.getLabel()));
        }
        return a;

    case PERIOD_PREF:
        return periodPreferences(room, context);

    case EVENT_DEPARTMENT:
        return new A(context.dept2string(room.getEventDepartment(), false))
                .color(room.getEventDepartment() == null ? null : room.getEventDepartment().getColor());

    case EVENT_STATUS:
        return room.getEventStatus() != null ? new A(CONSTANTS.eventStatusAbbv()[room.getEventStatus()])
                : room.getDefaultEventStatus() != null
                        ? new A(CONSTANTS.eventStatusAbbv()[room.getDefaultEventStatus()]).italic()
                        : new A();

    case EVENT_AVAILABILITY:
        return availability(room, true, context);

    case EVENT_MESSAGE:
        return room.getEventNote() != null ? new A(room.getEventNote())
                : new A(room.getDefaultEventNote()).italic();

    case BREAK_TIME:
        return room.getBreakTime() != null ? new A(room.getBreakTime().toString())
                : room.getDefaultBreakTime() != null ? new A(room.getDefaultBreakTime().toString()).italic()
                        : new A();

    case GROUPS:
        if (!room.hasGroups())
            return new A();
        a = new A();
        for (GroupInterface g : room.getGroups()) {
            a.add(new A(g.getLabel() + (g.getDepartment() == null ? ""
                    : " (" + context.dept2string(g.getDepartment(), true) + ")"))
                            .color(g.getDepartment() == null ? null : g.getDepartment().getColor()));
        }
        return a;

    case FEATURES:
        if (column.getIndex() == 0)
            return features(room.getFeatures(), null, context);
        else
            return features(room.getFeatures(), context.getRoomFeatureTypes().get(column.getIndex() - 1),
                    context);

    default:
        return null;
    }
}

From source file:org.viafirma.util.QRCodeUtil.java

License:Apache License

/**
 * Genera un nuevo pdf con la imagen firmada y el pie de firma.
 * @param url Url desde la que se puede descargar el documeto
 *///from   w ww.j a v a2  s  .c  o m
public void generarImagenPdf(byte[] input, String texto, String url, String textoQR, String codFirma,
        OutputStream out) throws ExcepcionErrorInterno {
    try {
        // Nuevo Documento PDF
        Document document = new Document();

        // Obtenemos el tamao de la pgina
        Rectangle pageSize = document.getPageSize();

        PdfWriter.getInstance(document, out);
        document.open();
        addContent(texto, url, textoQR, codFirma, document, pageSize, true, false);

        // Aadimos imagen original
        Image imagen = Image.getInstance(input);
        imagen.setBorder(10);
        imagen.scaleToFit(500, 500);
        imagen.setAbsolutePosition(50, pageSize.getHeight() - 400);
        document.add(imagen);

        // Cerramos el documento
        document.close();

    } catch (Exception e) {
        throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e);
    }

}

From source file:oscar.oscarEncounter.oscarConsultationRequest.pageUtil.ImagePDFCreator.java

License:Open Source License

/**
 * Prints the consultation request.//from  www  .  ja v  a  2  s. c o  m
 * @throws IOException when an error with the output stream occurs
 * @throws DocumentException when an error in document construction occurs
 */
public void printPdf() throws IOException, DocumentException {

    Image image;
    try {
        image = Image.getInstance((String) request.getAttribute("imagePath"));
    } catch (Exception e) {
        logger.error("Unexpected error:", e);
        throw new DocumentException(e);
    }

    // Create the document we are going to write to
    document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, os);

    document.setPageSize(PageSize.LETTER);
    ResourceBundle.getBundle("oscarResources", request.getLocale())
            .getString("oscarEncounter.oscarConsultationRequest.consultationFormPrint.msgImage");
    document.addCreator("OSCAR");
    document.open();

    int type = image.getOriginalType();
    if (type == Image.ORIGINAL_TIFF) {
        // The following is composed of code from com.lowagie.tools.plugins.Tiff2Pdf modified to create the 
        // PDF in memory instead of on disk
        RandomAccessFileOrArray ra = new RandomAccessFileOrArray((String) request.getAttribute("imagePath"));
        int comps = TiffImage.getNumberOfPages(ra);
        boolean adjustSize = false;
        PdfContentByte cb = writer.getDirectContent();
        for (int c = 0; c < comps; ++c) {
            Image img = TiffImage.getTiffImage(ra, c + 1);
            if (img != null) {
                if (adjustSize) {
                    document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
                    document.newPage();
                    img.setAbsolutePosition(0, 0);
                } else {
                    if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) {
                        img.scaleToFit(500, 700);
                    }
                    img.setAbsolutePosition(20, 20);
                    document.newPage();
                    document.add(
                            new Paragraph((String) request.getAttribute("imageTitle") + " - page " + (c + 1)));
                }
                cb.addImage(img);

            }
        }
        ra.close();
    } else {
        PdfContentByte cb = writer.getDirectContent();
        if (image.getScaledWidth() > 500 || image.getScaledHeight() > 700) {
            image.scaleToFit(500, 700);
        }
        image.setAbsolutePosition(20, 20);
        cb.addImage(image);
    }
    document.close();
}

From source file:questions.images.OverlappingImages.java

public static void main(String[] args) {
    // step 1: creation of a document-object
    Document document = new Document(PageSize.POSTCARD);
    try {/*from w  w w  .j  a  v  a  2  s.  co  m*/
        // step 2:
        // we create a writer
        PdfWriter.getInstance(
                // that listens to the document
                document,
                // and directs a PDF-stream to a file
                new FileOutputStream(RESULT));
        // step 3: we open the document
        document.open();
        // step 4: we add a paragraph to the document
        Image img1 = Image.getInstance(RESOURCE1);
        img1.scaleToFit(PageSize.POSTCARD.getWidth(), 10000);
        img1.setAbsolutePosition(0, 0);
        document.add(img1);
        Image img2 = Image.getInstance(RESOURCE2);
        img2.setTransparency(new int[] { 0x00, 0x10 });
        img2.setAbsolutePosition(PageSize.POSTCARD.getWidth() - img2.getScaledWidth(),
                PageSize.POSTCARD.getHeight() - img2.getScaledHeight());
        document.add(img2);
        Image img3 = Image.getInstance(RESOURCE3);
        img3.setTransparency(new int[] { 0xF0, 0xFF });
        img3.setAbsolutePosition((PageSize.POSTCARD.getWidth() - img3.getScaledWidth()) / 2,
                (PageSize.POSTCARD.getHeight() - img3.getScaledHeight()) / 2);
        document.add(img3);
    } catch (DocumentException de) {
        System.err.println(de.getMessage());
    } catch (IOException ioe) {
        System.err.println(ioe.getMessage());
    }

    // step 5: we close the document
    document.close();

}