Example usage for com.itextpdf.text Image scaleToFit

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

Introduction

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

Prototype

public void scaleToFit(final float fitWidth, final float fitHeight) 

Source Link

Document

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

Usage

From source file:org.primaresearch.pdf.PageToPdfConverter.java

License:Apache License

/**
 * Adds the document page image to the current PDF page (spanning the whole page). 
 *//*from  w  ww  .  j a  v a  2  s.  co m*/
private void addImage(String filepath, PdfWriter writer, Document doc, Page page)
        throws MalformedURLException, IOException, DocumentException {

    PdfContentByte cb = writer.getDirectContentUnder();
    cb.saveState();

    Image img = Image.getInstance(filepath);
    img.setAbsolutePosition(0f, 0f);
    //if (img.getScaledWidth() > 300 || img.getScaledHeight() > 300) {
    //img.scaleToFit(300, 300);
    //}
    img.scaleToFit(page.getLayout().getWidth(), page.getLayout().getHeight());

    cb.addImage(img);

    cb.restoreState();

}

From source file:org.smap.sdal.managers.PDFSurveyManager.java

License:Open Source License

private void fillNonTemplateUserDetails(Document document, User user, String basePath)
        throws IOException, DocumentException {

    String settings = user.settings;
    Type type = new TypeToken<UserSettings>() {
    }.getType();/*from w  w  w . j a v  a  2s.  c  o  m*/
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    UserSettings us = gson.fromJson(settings, type);

    float indent = (float) 20.0;
    addValue(document, "Completed by:", (float) 0.0);
    if (user.signature != null && user.signature.trim().length() > 0) {
        String fileName = null;
        try {
            //fileName = basePath + user.signature;

            fileName = basePath + "/media/users/" + user.id + "/sig/" + user.signature;

            Image img = Image.getInstance(fileName);
            img.scaleToFit(200, 50);
            img.setIndentationLeft(indent);

            document.add(img);

        } catch (Exception e) {
            log.info(
                    "Error: Failed to add signature (non template) " + fileName + " to pdf: " + e.getMessage());
        }
    }
    addValue(document, user.name, indent);
    addValue(document, user.company_name, indent);
    if (us != null) {
        addValue(document, us.title, indent);
        addValue(document, us.license, indent);
    }

}

From source file:org.smap.sdal.managers.PDFTableManager.java

License:Open Source License

private void fillNonTemplateUserDetails(Document document, User user, String basePath)
        throws IOException, DocumentException {

    String settings = user.settings;
    Type type = new TypeToken<UserSettings>() {
    }.getType();//w w  w. j  av a  2 s.co m
    Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create();
    UserSettings us = gson.fromJson(settings, type);

    float indent = (float) 20.0;
    addValue(document, "Completed by:", (float) 0.0);
    if (user.signature != null && user.signature.trim().length() > 0) {
        String fileName = null;
        try {
            fileName = basePath + File.separator + user.signature;

            Image img = Image.getInstance(fileName);
            img.scaleToFit(200, 50);
            img.setIndentationLeft(indent);

            document.add(img);

        } catch (Exception e) {
            log.info("Error: Failed to add image " + fileName + " to pdf");
        }
    }
    addValue(document, user.name, indent);
    addValue(document, user.company_name, indent);
    if (us != null) {
        addValue(document, us.title, indent);
        addValue(document, us.license, indent);
    }

}

From source file:org.yale.cs.graphics.gephi.imagepreview.ImageNodes.java

License:Open Source License

public void renderImagePDF(ImageItem item, PDFTarget target, PreviewProperties properties, File directory) {

    Image image = item.renderPDF(directory);

    if (image == null) {
        logger.log(Level.WARNING, "Unable to load image: {0}", item.getSource());
        return;/*from ww  w.  j  av  a  2 s .  c om*/
    }

    Float x = item.getData(NodeItem.X);
    Float y = item.getData(NodeItem.Y);
    Float size = item.getData(NodeItem.SIZE);

    float alpha = properties.getFloatValue(IMAGE_OPACITY) / 100f;

    PdfContentByte cb = target.getContentByte();

    if (alpha < 1f) {
        cb.saveState();
        PdfGState gState = new PdfGState();
        gState.setFillOpacity(alpha);
        gState.setStrokeOpacity(alpha);
        cb.setGState(gState);
    }

    image.setAbsolutePosition(x - size / 2, -y - size / 2);
    image.scaleToFit(size, size);
    try {
        cb.addImage(image);
    } catch (DocumentException ex) {
        logger.log(Level.SEVERE, "Unable to add image to document: " + item.getSource(), ex);
    }

    if (alpha < 1f) {
        cb.restoreState();
    }
}

From source file:Outras.GerarPdf.java

public GerarPdf(Os os) {
    //Criar um documento vazio
    Document documentoPDF = new Document();

    try {//from  w  w w .j ava2 s  . c o m
        //cria uma instancia do documento e da o nome dele na saida informada
        PdfWriter.getInstance(documentoPDF, new FileOutputStream("C:\\OrdensDeServico\\OS_" + os.getId()));

        //abertura do documento
        documentoPDF.open();

        //especificar o layout da pagina; j cria a primeria pagina
        documentoPDF.setPageSize(PageSize.A4);

        ////adicionando pargrafos na primeira folha
        //adicionando titulo
        documentoPDF.addTitle("Ordem de Servio");

        //adicionando imagens da OS e redimensionando
        Image imagem = Image.getInstance(
                "C:\\Users\\aluno\\Documents\\NetBeansProjects\\e-commerce\\src\\material\\imagemOs.png");
        imagem.scaleToFit(200, 200);
        documentoPDF.add(imagem);

        //adicionando o primeiro paragrafo
        documentoPDF.add(new Paragraph("ORDEM DE SERVIO EMITIDA PELO CARRINHO DO USUARIO: "
                + os.getEntrega().getEndereco().getUsuario().getNome()));

        documentoPDF
                .add(new Paragraph("Endereo de entrega: " + os.getEntrega().getEndereco().getLogradouro()));

        documentoPDF.add(new Paragraph("Entregador: " + os.getEntrega().getFuncionario().getNome()));

        documentoPDF.add(new Paragraph("Produtos: "));
        for (Produto p : os.getCarrinho().getProdutos()) {
            documentoPDF.add(new LineSeparator());
            documentoPDF.add(new Paragraph(p.getNome()));
        }
        documentoPDF.add(new LineSeparator());

    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + de.getMessage());
    } catch (IOException ioe) {
        JOptionPane.showMessageDialog(null, "Erro ao gerar o pdf" + ioe.getMessage());
    } finally {
        documentoPDF.close();
    }

}

From source file:pdf.watermark.java

License:Open Source License

public watermark() {
    try {/*w ww . ja  va  2  s.  c o  m*/
        PdfReader Read_PDF_To_Watermark = new PdfReader(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\test.pdf");
        int number_of_pages = Read_PDF_To_Watermark.getNumberOfPages();
        PdfStamper stamp = new PdfStamper(Read_PDF_To_Watermark, new FileOutputStream(
                "D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\New_PDF_With_Watermark_Image.pdf"));
        int i = 0;
        Image watermark_image = Image
                .getInstance("D:\\Dropbox\\Studium\\Bachelor Thesis\\Resourcen\\pdfexport\\xmltopdf\\desy.png");
        watermark_image.setAbsolutePosition(50, 150);
        watermark_image.scaleToFit(500, 500);
        PdfContentByte add_watermark;
        while (i < number_of_pages) {
            i++;
            add_watermark = stamp.getUnderContent(i);
            add_watermark.addImage(watermark_image);
        }
        stamp.close();
    } catch (IOException | DocumentException i1) {
        i1.printStackTrace();
    }
}

From source file:pdfcompressor.PDFCompressor.java

public void outputPDF(String pathToOutput)
        throws FileNotFoundException, DocumentException, BadElementException, IOException {
    com.itextpdf.text.Image itextImg;
    Document outDocument = new Document();
    outDocument.setMargins(0f, 0f, 0f, 0f);
    PdfWriter writer = PdfWriter.getInstance(outDocument, new FileOutputStream(pathToOutput));
    writer.setFullCompression();/*from w  w  w . ja v a 2  s  .  c  o m*/
    writer.open();
    outDocument.open();
    int progress = 0;
    for (java.awt.Image img : getBuffedImg()) {
        itextImg = Image.getInstance(getImageByteArray(img, compressRate));
        itextImg.scaleToFit(595f, 842f);
        outDocument.add(itextImg);

        for (ProgressListener listener : saveListener) {
            listener.haveProgress(++progress, numOfPages);
        }
    }
    outDocument.close();
    writer.close();
    for (ProgressListener listener : saveListener) {
        listener.finished();
    }
}

From source file:pdfcompressor.PDFCompressor.java

public void getFileSize() throws DocumentException, IOException {
    com.itextpdf.text.Image itextImg;
    Document outDocument = new Document();
    outDocument.setMargins(0f, 0f, 0f, 0f);
    ByteArrayOutputStream memoryOutput = new ByteArrayOutputStream();
    PdfWriter writer = PdfWriter.getInstance(outDocument, memoryOutput);
    writer.setFullCompression();//from   w w w  .  ja va2 s  .  co  m
    writer.open();
    outDocument.open();
    for (java.awt.Image img : getBuffedImg()) {
        itextImg = Image.getInstance(getImageByteArray(img, compressRate));
        itextImg.scaleToFit(595f, 842f);
        outDocument.add(itextImg);
    }
    outDocument.close();
    writer.close();
    for (ProgressListener listener : sizeEstimateListener) {
        listener.finished(memoryOutput.toByteArray().length);
    }
}

From source file:pl.marcinmilkowski.hocrtopdf.Main.java

License:Open Source License

/**
 * @param args// w  ww . j  a  va  2s  .  c om
 */
public static void main(String[] args) {
    try {
        if (args.length < 1 || args[0] == "--help" || args[0] == "-h") {
            System.out.print("Usage: java pl.marcinmilkowski.hocrtopdf.Main INPUTURL.html OUTPUTURL.pdf\n"
                    + "\n" + "Converts hOCR files into PDF\n" + "\n"
                    + "Example: java pl.marcinmilkowski.hocrtopdf.Main hocr.html output.pdf\n");
            if (args.length < 1)
                System.exit(-1);
            else
                System.exit(0);
        }
        URL inputHOCRFile = null;
        FileOutputStream outputPDFStream = null;
        try {
            File file = new File(args[0]);
            inputHOCRFile = file.toURI().toURL();
        } catch (MalformedURLException e) {
            System.out.println("The first parameter has to be a valid file.");
            System.out.println("We got an error: " + e.getMessage());
            System.exit(-1);
        }
        try {
            outputPDFStream = new FileOutputStream(args[1]);
        } catch (FileNotFoundException e) {
            System.out.println("The second parameter has to be a valid URL");
            System.exit(-1);
        }

        // The resolution of a PDF file (using iText) is 72pt per inch
        float pointsPerInch = 72.0f;

        // Using the jericho library to parse the HTML file
        Source source = new Source(inputHOCRFile);

        int pageCounter = 1;

        Document pdfDocument = null;
        PdfWriter pdfWriter = null;
        PdfContentByte cb = null;
        RandomAccessFileOrArray ra = null;

        // Find the tag of class ocr_page in order to load the scanned image
        StartTag pageTag = source.getNextStartTag(0, "class", OCRPAGE);
        while (pageTag != null) {
            int prevPos = pageTag.getEnd();
            Pattern imagePattern = Pattern.compile("image\\s+([^;]+)");
            Matcher imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title"));
            if (!imageMatcher.find()) {
                System.out.println("Could not find a tag of class \"ocr_page\", aborting.");
                System.exit(-1);
            }
            // Load the image
            Image pageImage = null;
            try {
                File file = new File(imageMatcher.group(1));
                pageImage = Image.getInstance(file.toURI().toURL());
            } catch (MalformedURLException e) {
                System.out.println("Could not load the scanned image from: " + "file://" + imageMatcher.group(1)
                        + ", aborting.");
                System.exit(-1);
            }
            if (pageImage.getOriginalType() == Image.ORIGINAL_TIFF) { // this might
                                                                      // be
                                                                      // multipage
                                                                      // tiff!
                File file = new File(imageMatcher.group(1));
                if (pageCounter == 1 || ra == null) {
                    ra = new RandomAccessFileOrArray(file.toURI().toURL());
                }
                int nPages = TiffImage.getNumberOfPages(ra);
                if (nPages > 0 && pageCounter <= nPages) {
                    pageImage = TiffImage.getTiffImage(ra, pageCounter);
                }
            }
            int dpiX = pageImage.getDpiX();
            if (dpiX == 0) { // for images that don't set the resolution we assume
                             // 300 dpi
                dpiX = 300;
            }
            int dpiY = pageImage.getDpiY();
            if (dpiY == 0) { // as above for dpiX
                dpiY = 300;
            }
            float dotsPerPointX = dpiX / pointsPerInch;
            float dotsPerPointY = dpiY / pointsPerInch;
            float pageImagePixelHeight = pageImage.getHeight();
            if (pdfDocument == null) {
                pdfDocument = new Document(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream);
                pdfDocument.open();
                // Put the text behind the picture (reverse for debugging)
                // cb = pdfWriter.getDirectContentUnder();
                cb = pdfWriter.getDirectContent();
            } else {
                pdfDocument.setPageSize(new Rectangle(pageImage.getWidth() / dotsPerPointX,
                        pageImage.getHeight() / dotsPerPointY));
                pdfDocument.newPage();
            }
            // first define a standard font for our text
            BaseFont base = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1250, BaseFont.EMBEDDED);
            Font defaultFont = new Font(base, 8);
            // FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD,
            // CMYKColor.BLACK);

            cb.setHorizontalScaling(1.0f);

            pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY);
            pageImage.setAbsolutePosition(0, 0);
            // Put the image in front of the text (reverse for debugging)
            // pdfWriter.getDirectContent().addImage(pageImage);
            pdfWriter.getDirectContentUnder().addImage(pageImage);

            // In order to place text behind the recognised text snippets we are
            // interested in the bbox property
            Pattern bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}");
            // This pattern separates the coordinates of the bbox property
            Pattern bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)");
            // Only tags of the ocr_line class are interesting
            StartTag ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            while (ocrTag != null) {
                prevPos = ocrTag.getEnd();
                if ("ocrx_word".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                    net.htmlparser.jericho.Element lineElement = ocrTag.getElement();
                    Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title"));
                    if (bboxMatcher.find()) {
                        // We found a tag of the ocr_line class containing a bbox property
                        Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group());
                        bboxCoordinateMatcher.find();
                        int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))),
                                Integer.parseInt((bboxCoordinateMatcher.group(2))),
                                Integer.parseInt((bboxCoordinateMatcher.group(3))),
                                Integer.parseInt((bboxCoordinateMatcher.group(4))) };
                        String line = lineElement.getContent().getTextExtractor().toString();
                        float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX;
                        float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY;

                        // Put the text into the PDF
                        cb.beginText();
                        // Comment the next line to debug the PDF output (visible Text)
                        cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE);
                        // height
                        cb.setFontAndSize(defaultFont.getBaseFont(), Math.max(Math.round(bboxHeightPt), 1));
                        // width
                        cb.setHorizontalScaling(bboxWidthPt / cb.getEffectiveStringWidth(line, false));
                        cb.moveText((coordinates[0] / dotsPerPointX),
                                ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY));
                        cb.showText(line);
                        cb.endText();
                        cb.setHorizontalScaling(1.0f);
                    }
                } else {
                    if ("ocr_page".equalsIgnoreCase(ocrTag.getAttributeValue("class"))) {
                        pageCounter++;
                        pageTag = ocrTag;
                        break;
                    }
                }
                ocrTag = source.getNextStartTag(prevPos, "class", OCRPAGEORLINE);
            }
            if (ocrTag == null) {
                pdfDocument.close();
                break;
            }
        }
    } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

From source file:Print.Print.java

private void printToPDF(BufferedImage bufferedImage) {
    // define pdfprinter and within try clause create
    for (int i = 0; i < quantity; i++) {
        PdfWriter writer = null;/* ww w.  ja va  2  s  .  com*/
        try {
            // define fileoutputstream and within try clause create
            FileOutputStream fos = null;

            document = new Document(PageSize.A4.rotate());
            fos = new FileOutputStream(output + photoID + "-" + Integer.toString(i + 1) + ".pdf");

            // create the writer object
            try {
                writer = PdfWriter.getInstance(document, fos);
            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            }

            // open the writer and the document and add the image into the document
            writer.open();
            document.open();
            try {
                PdfContentByte pdfCB = new PdfContentByte(writer);
                if (bufferedImage == null) {
                    Image image = Image.getInstance(input);
                    image.scaleToFit(640, 480);
                    document.add(image);
                } else {
                    Image image = Image.getInstance(pdfCB, bufferedImage, 1);
                    image.scaleToFit(640, 480);
                    document.add(Image.getInstance(image));
                }

            } catch (DocumentException ex) {
                System.out.println(ex.getMessage());
            } catch (IOException ex) {
                System.out.println(ex.getMessage());
            }
            // close the document and writer
            document.close();
            writer.close();

            System.out.println("Printer done.");

        } catch (Exception e) {
            System.out.println(e.getMessage());
        }
    }
}