Example usage for com.itextpdf.text Rectangle Rectangle

List of usage examples for com.itextpdf.text Rectangle Rectangle

Introduction

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

Prototype

public Rectangle(final float urx, final float ury) 

Source Link

Document

Constructs a Rectangle -object starting from the origin (0, 0).

Usage

From source file:com.mim.servlet.ReportGen.java

public String buildReport(HttpServletResponse response) {

    System.out.println("orden No. " + ordenId);

    FacesContext context = FacesContext.getCurrentInstance();

    //response.setContentType("application/pdf");
    //response.setHeader("Content-disposition", "inline=filename=file.pdf");

    // Get the text that will be added to the PDF
    current = ordenFacade.find(Integer.parseInt(ordenId));
    System.out.println("equipo: " + current.getEquipoIdequipo().getLugarIdlugar().getNombre());
    // step 1//from w  w w . ja  va2 s . c o m
    Document document = new Document(new Rectangle(800, 700), 7f, 7f, 50f, 7f);

    if (ordenId.equals("n/a")) {
        current.setNumeroOrden(current.getActividad());
    }

    equipo = current.getEquipoIdequipo();
    Lugar lugar = equipo.getLugarIdlugar();

    //PdfWriter.getInstance(document, new FileOutputStream(orden.getNumeroOrden() + ".pdf"));
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        PdfWriter.getInstance(document, baos);

        document.open();
        ordenReport(document, lugar);
        //document.add(new Paragraph("dsadasdas"));
        document.close();

        // step 2
        // setting some response headers
        response.setHeader("Content-disposition", "attachment; filename=" + current.getNumeroOrden() + ".pdf");// esto hizo que fuera descarga directa
        //response.setHeader("Expires", "0");
        //response.setHeader("Cache-Control",
        //        "must-revalidate, post-check=0, pre-check=0");
        //response.setHeader("Pragma", "public");
        // setting the content type
        response.setContentType("application/pdf");
        // the contentlength
        response.setContentLength(baos.size());
        try ( // write ByteArrayOutputStream to the ServletOutputStream
                OutputStream os = response.getOutputStream()) {
            baos.writeTo(os);
            os.flush();
        }
    } catch (DocumentException | IOException ex) {
        Logger.getLogger(HomeCtrl.class.getName()).log(Level.SEVERE, null, ex);
    }

    context.responseComplete();
    return null;

}

From source file:com.ostrichemulators.semtool.util.ExportUtility.java

License:Open Source License

public static void exportAsPdf(BufferedImage img, File pdf) throws IOException, DocumentException {
    final double MAX_DIM = 14400;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(img, "PNG", baos);
    Image image1 = Image.getInstance(baos.toByteArray(), true);
    Rectangle r;/*  w w  w  . j  a va  2 s.  c om*/
    if (image1.getHeight() > MAX_DIM) {
        r = new Rectangle((int) image1.getWidth(), (int) MAX_DIM);
    } else if (image1.getWidth() > MAX_DIM) {
        r = new Rectangle((int) MAX_DIM, (int) image1.getHeight());
    } else {
        r = new Rectangle((int) image1.getWidth() + 20, (int) image1.getHeight() + 20);
    }
    Document document = new Document(r, 15, 25, 15, 25);
    PdfWriter.getInstance(document, new FileOutputStream(pdf));
    document.open();

    int pages = (int) Math.ceil((double) img.getHeight() / MAX_DIM);
    if (pages == 0) {
        pages = 1;
    }
    for (int i = 0; i < pages; i++) {
        BufferedImage temp;
        if (i < pages - 1) {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), (int) MAX_DIM);
        } else {
            temp = img.getSubimage(0, i * (int) MAX_DIM, img.getWidth(), img.getHeight() % (int) MAX_DIM);
        }
        File tempFile = new File(i + Constants.PNG);
        ImageIO.write(temp, Constants.PNG, tempFile);
        Image croppedImage = Image.getInstance(i + Constants.PNG);
        document.add(croppedImage);
        tempFile.delete();
        if (i < pages - 1) {
            document.newPage();
        }
    }

    document.close();
}

From source file:com.primeleaf.krystal.util.PDFConverter.java

License:Open Source License

public File getConvertedFile(DocumentRevision documentRevision, Document document, String password)
        throws Exception {
    File tempFile = documentRevision.getDocumentFile();
    if ("TIF".equalsIgnoreCase(document.getExtension()) || "TIFF".equalsIgnoreCase(document.getExtension())) {
        try {//from  w  w  w  . j  a va2 s .  c  om
            tempFile = File.createTempFile("temp", ".PDF");
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document();
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.setMargins(0, 0, 0, 0);
            FileInputStream fis = new FileInputStream(documentRevision.getDocumentFile());
            RandomAccessFileOrArray file = new RandomAccessFileOrArray(fis);
            int pages = TiffImage.getNumberOfPages(file);
            for (int page = 1; page <= pages; page++) {
                Image img = TiffImage.getTiffImage(file, page);
                img.setAbsolutePosition(0f, 0f);
                img.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                pdf.setMargins(0, 0, 0, 0);
                pdf.add(img);
                pdf.newPage();
            }
            fis.close();
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert TIFF Document to PDF");
        }
    } else if ("JPG".equalsIgnoreCase(document.getExtension())
            || "JPEG".equalsIgnoreCase(document.getExtension())
            || "PNG".equalsIgnoreCase(document.getExtension())
            || "BMP".equalsIgnoreCase(document.getExtension())
            || "GIF".equalsIgnoreCase(document.getExtension())) {
        try {
            tempFile = File.createTempFile("temp", ".PDF");
            Image img = Image.getInstance(documentRevision.getDocumentFile().getAbsolutePath());
            com.itextpdf.text.Document pdf = new com.itextpdf.text.Document(
                    new Rectangle(img.getWidth(), img.getHeight()), 0, 0, 0, 0);
            img.setAbsolutePosition(0f, 0f);
            PdfWriter.getInstance(pdf, new FileOutputStream(tempFile));
            pdf.open();
            pdf.add(img);
            pdf.close();
            document.setExtension("PDF");
        } catch (Exception e) {
            tempFile = documentRevision.getDocumentFile();
            throw new Exception("Unable to convert Image Document to PDF");
        }
    } else if ("PDF".equalsIgnoreCase(document.getExtension())) {
        tempFile = documentRevision.getDocumentFile();
    } else {
        String tempFilePath = "";
        String KRYSTAL_HOME = System.getProperty("krystal.home");
        if (KRYSTAL_HOME == null) {
            KRYSTAL_HOME = System.getProperty("user.dir");
            System.setProperty("krystal.home", KRYSTAL_HOME);
        }
        tempFilePath = KRYSTAL_HOME + File.separator + "/webapps/DMC/images/unsupport.pdf";
        tempFile = new File(tempFilePath);
    }
    return tempFile;
}

From source file:com.semfapp.adamdilger.semf.Pdf.java

License:Open Source License

private void createPDFNew(String filePath, String htmlString, @Nullable ArrayList<ImageFile> images) {

    File file = null;/*  w w w. j a va2  s .  c  o m*/
    try {
        file = new File(filePath);

        // step 1
        Document document = new Document();

        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        writer.setInitialLeading(12.5f);

        // step 3
        document.open();

        // step 4

        // CSS
        CSSResolver cssResolver = new StyleAttrCSSResolver();
        CssFile cssFile = XMLWorkerHelper.getCSS(activity.getAssets().open("styles.css"));
        cssResolver.addCss(cssFile);

        // HTML
        HtmlPipelineContext htmlContext = new HtmlPipelineContext(null);
        htmlContext.setTagFactory(Tags.getHtmlTagProcessorFactory());

        // Pipelines

        PdfWriterPipeline pdf = new PdfWriterPipeline(document, writer);
        HtmlPipeline html = new HtmlPipeline(htmlContext, pdf);
        CssResolverPipeline css = new CssResolverPipeline(cssResolver, html);

        // XML Worker
        XMLWorker worker = new XMLWorker(css, true);
        XMLParser p = new XMLParser(worker);

        Drawable d = activity.getResources().getDrawable(R.drawable.logo_icon);
        Bitmap bitmap = ((BitmapDrawable) d).getBitmap();
        ByteArrayOutputStream stream = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
        byte[] bitmapData = stream.toByteArray();

        Image image = Image.getInstance(bitmapData);
        image.setAbsolutePosition(35, 763);
        image.scalePercent(12);
        document.add(image);

        p.parse(new ByteArrayInputStream(htmlString.getBytes(StandardCharsets.UTF_8)));

        if (images != null) {
            System.out.println("Adding IMage");

            for (int x = 0; x < images.size(); x++) {
                Image cursor = images.get(x).getImage();

                float ratio = cursor.getPlainHeight() / cursor.getPlainWidth();

                float imgWidth = document.getPageSize().getWidth() - 100;
                float imgHeight = document.getPageSize().getHeight() - 100;

                cursor.scaleToFit(new Rectangle(imgWidth, imgHeight));

                document.add(cursor);
            }
        }

        // step 5
        document.close();

    } catch (Exception e) {
        e.printStackTrace();
    }
}

From source file:com.sparksoftsolutions.com.pdfcreator.MainActivity.java

private File generatePDFFromImages(ArrayList<ImageItem> images) {
    Document document = new Document();

    File sdcard = Environment.getExternalStorageDirectory();
    File file = new File(sdcard, generateFileName());

    try {//w w w. j av  a 2s  .co  m
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
    } catch (Exception ex) {
        return null;
    }

    // document = new PdfDocument();
    Boolean opened = false;
    for (ImageItem img : images) {

        Bitmap bitmap = BitmapFactory.decodeFile(img.path);

        try {

            Image image = Image.getInstance(img.path);
            document.setPageSize(new Rectangle(image.getWidth(), image.getHeight()));

            if (!opened) {
                document.open();
                opened = true;
            } else
                document.newPage();
            document.add(image);

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    document.close();
    return file;
}

From source file:com.swayam.bhasha.engine.io.writers.impl.PDFGenerator.java

License:Apache License

private void makePDFPage(HTMLDocModel htmlDoc, String fileName) throws DocGenerationException {

    Rectangle pageSize = PageSize.A4;

    if (pageDim.height > pageSize.getHeight()) {
        pageSize = new Rectangle(pageDim.width, pageDim.height);
    }/* w  w w. j a  v  a  2s.  com*/

    Document pdfDoc = new Document(pageSize, MARGINS, MARGINS, MARGINS, MARGINS);

    FileOutputStream pdfStream = null;

    try {
        pdfStream = new FileOutputStream(fileName);

        PdfWriter.getInstance(pdfDoc, pdfStream);

        pdfDoc.addAuthor("Bhasha PDF Generator (Powered by IText)");

        pdfDoc.open();

        List<Para> paraList = htmlDoc.getParaList();

        for (Para para : paraList) {
            pdfDoc.add(getParagraph(para));
        }

        pdfDoc.close();

    } catch (Exception e) {
        throw new DocGenerationException(e);
    } finally {

        if (pdfStream != null) {
            try {
                pdfStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }

}

From source file:com.swayam.bhasha.engine.io.writers.impl.PDFImageGenerator.java

License:Apache License

private void makePDFPage(HTMLDocModel htmlDoc, String fileName) throws DocGenerationException, IOException {

    BufferedImage image = getImage(pageDim, htmlDoc);

    /*/*from  w  w  w  .  j a  v  a 2 s  .  c  o  m*/
     * ByteArrayOutputStream bos = new ByteArrayOutputStream();
     * 
     * ImageIO.write(image, "JPG", bos);
     * 
     * byte[] imageData = bos.toByteArray();
     * 
     * System.out.println("PDFImageGenerator.makePDFPage() " +
     * imageData.length);
     */

    Rectangle pageSize = PageSize.A4;

    if (image.getHeight() > pageSize.getHeight()) {
        pageSize = new Rectangle(image.getWidth(), image.getHeight());
    }

    Document pdfDoc = new Document(pageSize, MARGINS, MARGINS, MARGINS, MARGINS);

    FileOutputStream pdfStream = null;

    try {
        pdfStream = new FileOutputStream(fileName);

        PdfWriter pdfWriter = PdfWriter.getInstance(pdfDoc, pdfStream);

        pdfDoc.addAuthor("Bhasha PDF Generator (Powered by IText)");

        pdfDoc.open();

        PdfContentByte contentByte = pdfWriter.getDirectContent();

        Image pdfImage = Image.getInstance(image, null);

        pdfImage.setAbsolutePosition(0, 0);
        contentByte.addImage(pdfImage);

    } catch (Exception e) {
        throw new DocGenerationException(e);
    } finally {

        pdfDoc.close();

        if (pdfStream != null) {
            try {
                pdfStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}

From source file:com.tommontom.pdfsplitter.PdfMerge.java

public static void doMerge(java.util.List<InputStream> list, String[] imageList, String[] listWordExcels,
        OutputStream outputStream) throws DocumentException, IOException {
    Document document = new Document(PageSize.LETTER, 0, 0, 0, 0);
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    writer.setFullCompression();/*from  w  w  w. j  ava 2s .c om*/
    document.open();
    PdfContentByte cb = writer.getDirectContent();
    Image img;
    for (InputStream in : list) {
        PdfReader reader = new PdfReader(in);
        for (int i = 1; i <= reader.getNumberOfPages(); i++) {

            document.newPage();
            //import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);
            //add the page to the destination pdf
            cb.addTemplate(page, 0, 0);
        }

    }
    for (int i = 0; i < imageList.length; i++) {
        document.newPage();
        if (imageList[i] != null) {
            img = Image.getInstance(String.format("%s", imageList[i]));
            Rectangle one = new Rectangle(img.getPlainWidth(), img.getPlainHeight());
            document.setPageSize(one);
            if (img.getScaledWidth() > img.getScaledHeight()) {
                img.rotate();
            }
            if (img.getScaledWidth() > 792 || img.getScaledHeight() > 792) {
                img.scaleToFit(792, 792);

            }
            img.setDpi(150, 150);
            document.add(img);
        }
    }
    for (int i = 0; i < listWordExcels.length; i++) {
        if (imageList[i] != null) {
            File input = new File(listWordExcels[i]);
            File output = new File(listWordExcels[i] + ".pdf");
            String outputS = listWordExcels[i] + ".pdf";
            OpenOfficeConnection connection = new SocketOpenOfficeConnection(8100);
            connection.connect();
            DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
            converter.convert(input, output);
            PdfReader readerWord = new PdfReader(outputS);
            PdfImportedPage page = writer.getImportedPage(readerWord, readerWord.getNumberOfPages());
            cb.addTemplate(page, 0, 0);
        }
    }

    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:com.vectorprint.report.itext.BaseReportGenerator.java

License:Open Source License

/**
 * prepare the report, call {@link #continueOnDataCollectionMessages(com.vectorprint.report.data.DataCollectionMessages, com.itextpdf.text.Document)
 * }/*from   w ww . ja v a  2 s. c o m*/
 * and when this returns true call {@link #createReportBody(com.itextpdf.text.Document, com.vectorprint.report.data.ReportDataHolder, com.itextpdf.text.pdf.PdfWriter)
 * }. When a Runtime, VectorPrint, IO and DocumentException occurs {@link #handleException(java.lang.Exception, java.io.OutputStream)
 * } will be called.
 *
 * @param data
 * @param outputStream
 * @return 0 or {@link #ERRORINREPORT}
 * @throws com.vectorprint.VectorPrintException
 */
@Override
public final int generate(RD data, OutputStream out) throws VectorPrintException {
    try {
        DocumentStyler ds = stylerFactory.getDocumentStyler();
        ds.setReportDataHolder(data);

        wasDebug = getSettings().getBooleanProperty(Boolean.FALSE, DEBUG);
        if (ds.getValue(DocumentSettings.TOC, Boolean.class)) {
            out = new TocOutputStream(out, bufferSize, this);
            getSettings().put(DEBUG, Boolean.FALSE.toString());
        }

        if (ds.isParameterSet(DocumentSettings.KEYSTORE)) {
            out = new SigningOutputStream(out, bufferSize, this);
        }

        document = new VectorPrintDocument(eventHelper, stylerFactory, styleHelper);
        writer = PdfWriter.getInstance(document, out);
        styleHelper.setVpd((VectorPrintDocument) document);
        ((VectorPrintDocument) document).setWriter(writer);

        eventHelper.setReportDataHolder(data);
        writer.setPageEvent(eventHelper);
        stylerFactory.setDocument(document, writer);
        stylerFactory.setImageLoader(elementProducer);
        stylerFactory.setLayerManager(elementProducer);

        StylerFactoryHelper.initStylingObject(ds, writer, document, this, elementProducer, settings);
        ds.loadFonts();
        styleHelper.style(document, data, StyleHelper.toCollection(ds));
        document.open();
        if (ds.canStyle(document) && ds.shouldStyle(data, document)) {
            ds.styleAfterOpen(document, data);
        }

        // data from the data collection phase doesn't have to be present
        if (data == null || continueOnDataCollectionMessages(data.getMessages(), document)) {
            createReportBody(document, data, writer);
            /*
             * when using queueing we may have run into failures in the data collection thread
             */
            if (data != null && !data.getData().isEmpty()) {
                Object t = data.getData().poll();
                if (t instanceof Throwable) {
                    throw new VectorPrintException((Throwable) t);
                }
            }
        }
        eventHelper.setLastPage(writer.getCurrentPageNumber());

        if (getSettings().getBooleanProperty(false, DEBUG)) {
            eventHelper.setLastPage(writer.getCurrentPageNumber());
            document.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            document.setMargins(5, 5, 5, 5);
            document.newPage();
            eventHelper.setDebugHereAfter(true);
            if (!ds.getValue(DocumentSettings.TOC, Boolean.class)) {
                DebugHelper.appendDebugInfo(writer, document, settings, stylerFactory);
            }
        }

        document.close();
        writer.close();

        return 0;
    } catch (RuntimeException | DocumentException | VectorPrintException | IOException e) {
        return handleException(e, out);
    }
}

From source file:com.vectorprint.report.itext.BaseReportGenerator.java

License:Open Source License

/**
 * This method will be called when exceptions are thrown in
 * {@link #createReportBody(com.itextpdf.text.Document, com.vectorprint.report.data.ReportDataHolder)} or
 * {@link DebugHelper#appendDebugInfo(com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document, com.vectorprint.configuration.EnhancedMap, com.vectorprint.report.itext.style.StylerFactory) },
 * it will rethrow the exception by default. If you provide a property {@link ReportConstants#STOPONERROR} with a
 * value of false, the stacktrace will be appended to the pdf and the document and writer will be closed.
 *
 * @param ex// ww  w.ja v a2 s .  c  o m
 * @param output the pdf document output stream
 * @return 1
 */
protected int handleException(Exception ex, OutputStream output) throws VectorPrintRuntimeException {
    if (getSettings().getBooleanProperty(Boolean.TRUE, ReportConstants.STOPONERROR)) {
        throw (ex instanceof VectorPrintRuntimeException) ? (VectorPrintRuntimeException) ex
                : new VectorPrintRuntimeException("failed to generate the report: " + ex.getMessage(), ex);
    } else {
        PrintStream out;

        ByteArrayOutputStream bo = new ByteArrayOutputStream();

        out = new PrintStream(bo);
        ex.printStackTrace(out);
        out.close();

        try {
            Font f = FontFactory.getFont(FontFactory.COURIER, 8);

            f.setColor(itextHelper.fromColor(getSettings().getColorProperty(Color.MAGENTA, "debugcolor")));

            String s = getSettings().getProperty(bo.toString(), "renderfault");
            eventHelper.setLastPage(writer.getCurrentPageNumber());
            document.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            document.setMargins(5, 5, 5, 5);

            document.newPage();
            eventHelper.setFailuresHereAfter(true);

            document.add(
                    new Chunk("Below you find information that help solving the problems in this report.", f)
                            .setLocalDestination(FAILUREPAGE));
            newLine();
            document.add(new Paragraph(new Chunk(s, f)));
            document.newPage();
            DebugHelper.appendDebugInfo(writer, document, settings, stylerFactory);
        } catch (VectorPrintException | DocumentException e) {
            log.severe("Could not append to PDF:\n" + bo.toString());
            log.log(java.util.logging.Level.SEVERE, null, e);
        } finally {
            document.close();
            writer.close();
        }
    }

    return ERRORINREPORT;
}