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:org.com.controller.ProductController.java

@RequestMapping(value = "/repProduct", method = RequestMethod.GET)
public void productReport(Model m, HttpServletResponse response, HttpServletRequest request,
        OutputStream outputStream) throws Exception {
    String name = "ProductReport-";
    Date d = new Date();
    name = name + d.toString() + ".pdf";
    response.setContentType("application/pdf");
    response.setHeader("Content-Disposition", "attachment; filename=" + name);
    Rectangle pagesize = new Rectangle(216f, 720f);
    Document document = new Document(PageSize.A4);
    PdfWriter.getInstance(document, outputStream);
    document.open();//from w  ww .  ja v a2s .  c o m
    document.addTitle("PRODUCT DETAILSA REPORT");
    document.add(new Paragraph("PRODUCT DETAILSA REPORT ",
            FontFactory.getFont(FontFactory.HELVETICA, 28, BaseColor.CYAN)));
    document.add(new Paragraph("DATE: " + new Date()));
    document.add(new Paragraph("-------------------------------------------------------- "));
    document.add(new Paragraph(" "));
    ProductDaoImpl pdi = new ProductDaoImpl();
    PdfPTable table = new PdfPTable(4);
    table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
    table.addCell("ID");
    table.addCell("TITLE");
    table.addCell("PUBLISHER");
    table.addCell("PRICE");
    ArrayList<ProductTable> list = pdi.getAllProduct();
    for (ProductTable u : list) {
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(u.getPid().toString());
        table.getDefaultCell().setBackgroundColor(BaseColor.GRAY);
        table.addCell(u.getPname());
        table.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
        table.addCell(u.getPublisher());
        table.getDefaultCell().setBackgroundColor(BaseColor.GRAY);
        table.addCell(u.getSprice().toString());
    }
    document.add(table);
    document.close();

}

From source file:org.fhaes.fhsamplesize.view.SSIZCurveChart.java

License:Open Source License

/**
 * Save chart as PDF file. Requires iText library.
 * // w  ww .j  av a 2s.  c o  m
 * @param chart JFreeChart to save.
 * @param fileName Name of file to save chart in.
 * @param width Width of chart graphic.
 * @param height Height of chart graphic.
 * @throws Exception if failed.
 * @see <a href="http://www.lowagie.com/iText">iText</a>
 */
@SuppressWarnings("deprecation")
public static void writeAsPDF(File fileToSave, int width, int height) throws Exception {

    if (chart != null) {
        BufferedOutputStream out = null;
        try {
            out = new BufferedOutputStream(new FileOutputStream(fileToSave.getAbsolutePath()));

            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            Document document = new Document(pagesize, 50, 50, 50, 50);
            try {
                PdfWriter writer = PdfWriter.getInstance(document, out);
                document.addAuthor("JFreeChart");
                document.open();

                PdfContentByte cb = writer.getDirectContent();
                PdfTemplate tp = cb.createTemplate(width, height);
                Graphics2D g2 = tp.createGraphics(width, height, new DefaultFontMapper());

                Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
                chart.draw(g2, r2D, null);
                g2.dispose();
                cb.addTemplate(tp, 0, 0);
            } finally {
                document.close();
            }
        } finally {
            if (out != null)
                out.close();
        }
    }
}

From source file:org.fhaes.neofhchart.PDFExportOptionsDialog.java

License:Open Source License

/**
 * Performs the export operation using the currentChart as the source.
 * /*from   w  w  w  .  ja v  a2s  . c  om*/
 * @return true if the operation completed successfully, false otherwise
 */
private boolean doExportToPDF() {

    boolean completedSuccessfully = false;

    if (currentChart != null) {
        log.debug("Exporting to PDF...");
        Document document = null;

        if (cboPaperSize.getSelectedItem() instanceof Rectangle) {
            Rectangle rect = (Rectangle) cboPaperSize.getSelectedItem();

            if (radLandscape.isSelected()) {
                rect = rect.rotate();
            }

            document = new Document(rect, 10, 10, 10, 10);
        } else {
            Rectangle rect = new Rectangle(currentChart.getTotalWidth(), currentChart.getTotalHeight());
            document = new Document(rect, 10, 10, 10, 10);
        }

        try {
            currentChart.setVisibilityOfNoExportElements(false);

            PdfWriter writer = PdfWriter.getInstance(document,
                    new FileOutputStream(outputFile.getAbsolutePath()));
            document.open();

            int width = (int) document.getPageSize().getWidth();
            int height = (int) document.getPageSize().getHeight();

            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate template = cb.createTemplate(width, height);

            @SuppressWarnings("deprecation")
            Graphics2D g2 = template.createGraphics(width, height);

            PrintTranscoder prm = new PrintTranscoder();
            TranscoderInput ti = new TranscoderInput(currentChart.getSVGDocument());
            prm.transcode(ti, null);

            PageFormat pg = new PageFormat();
            Paper pp = new Paper();
            pp.setSize(width, height);
            pp.setImageableArea(0, 0, width, height);
            pg.setPaper(pp);
            prm.print(g2, pg, 0);
            g2.dispose();

            ImgTemplate img = new ImgTemplate(template);
            document.add(img);

            completedSuccessfully = true;
        } catch (DocumentException e) {
            System.err.println(e);
        } catch (IOException e) {
            System.err.println(e);
        } finally {
            currentChart.setVisibilityOfNoExportElements(true);
        }

        document.close();
    }

    return completedSuccessfully;
}

From source file:org.gephi.ui.exporter.preview.UIExporterPDFPanel.java

License:Open Source License

public void unsetup(PDFExporter pdfExporter) {
    if (pageSizeCombo.getSelectedItem() == customSizeString) {
        double width = pdfExporter.getPageSize().getWidth();
        double height = pdfExporter.getPageSize().getHeight();
        try {/*from ww  w  .j  a  va2  s. c o  m*/
            width = sizeFormatter.parse(widthTextField.getText()).doubleValue();
        } catch (ParseException ex) {
        }
        try {
            height = sizeFormatter.parse(heightTextField.getText()).doubleValue();
        } catch (ParseException ex) {
        }

        if (millimeter) {
            width *= MM;
            height *= MM;
        } else {
            width *= INCH;
            height *= INCH;
        }
        float w = (float) width;
        float h = (float) height;
        Rectangle rect = new Rectangle(w, h);
        pdfExporter.setPageSize(rect);
    } else {
        pdfExporter.setPageSize(((PageSizeItem) pageSizeCombo.getSelectedItem()).getPageSize());
    }

    pdfExporter.setLandscape(landscapeRadio.isSelected());

    double top = pdfExporter.getMarginTop();
    double bottom = pdfExporter.getMarginBottom();
    double left = pdfExporter.getMarginLeft();
    double right = pdfExporter.getMarginRight();
    try {
        top = marginFormatter.parse(topMarginTextField.getText()).doubleValue();
    } catch (ParseException ex) {
    }
    try {
        bottom = marginFormatter.parse(bottomMarginTextField.getText()).doubleValue();
    } catch (ParseException ex) {
    }
    try {
        left = marginFormatter.parse(leftMarginTextField.getText()).doubleValue();
    } catch (ParseException ex) {
    }
    try {
        right = marginFormatter.parse(rightMargintextField.getText()).doubleValue();
    } catch (ParseException ex) {
    }
    if (millimeter) {
        top *= MM;
        bottom *= MM;
        left *= MM;
        right *= MM;
    } else {
        top *= INCH;
        bottom *= INCH;
        left *= INCH;
        right *= INCH;
    }
    pdfExporter.setMarginTop((float) top);
    pdfExporter.setMarginBottom((float) bottom);
    pdfExporter.setMarginLeft((float) left);
    pdfExporter.setMarginRight((float) right);

    savePreferences();
}

From source file:org.gmdev.pdftrick.engine.MergeFiles.java

License:Open Source License

/**
 * Materially multiple pdf files are written merged file on a disk 
 * @param list//from ww  w .  j  a  v  a2s.  c  o m
 * @param outputStream
 * @throws DocumentException
 * @throws IOException
 */
private void doMerge(List<StreamPwdContainer> list, OutputStream outputStream)
        throws DocumentException, IOException {
    HashMap<Integer, String> rotationFromPages = factory.getRotationFromPages();
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, outputStream);
    document.open();
    PdfContentByte cb = writer.getDirectContent();

    int z = 0;
    for (StreamPwdContainer boom : list) {

        InputStream in = boom.getIn();
        PdfReader reader = null;
        if (!boom.getPwd().equalsIgnoreCase("")) {
            reader = new PdfReader(in, boom.getPwd().getBytes());
        } else {
            reader = new PdfReader(in);
        }

        for (int i = 1; i <= reader.getNumberOfPages(); i++) {
            z++;
            int rotation = reader.getPageRotation(i);

            //set size
            Rectangle pageSize_ = reader.getPageSize(i);
            Rectangle pageSize = null;
            if (rotation == 270 || rotation == 90) {
                pageSize = new Rectangle(pageSize_.getHeight(), pageSize_.getWidth());
            } else {
                pageSize = pageSize_;
            }

            document.setPageSize(pageSize);
            writer.setCropBoxSize(pageSize);

            document.newPage();

            // import the page from source pdf
            PdfImportedPage page = writer.getImportedPage(reader, i);

            // add the page to the destination pdf
            if (rotation == 270) {
                cb.addTemplate(page, 0, 1.0f, -1.0f, 0, reader.getPageSizeWithRotation(i).getWidth(), 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 180) {
                cb.addTemplate(page, -1f, 0, 0, -1f, 0, 0);
                rotationFromPages.put(z, "" + rotation);
            } else if (rotation == 90) {
                cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(i).getHeight());
                rotationFromPages.put(z, "" + rotation);
            } else {
                cb.addTemplate(page, 1f, 0, 0, 1f, 0, 0);
            }
        }
        in.close();
    }
    outputStream.flush();
    document.close();
    outputStream.close();
}

From source file:org.javad.stamp.pdf.PdfGenerator.java

License:Apache License

public void generate(GenerateBean bean) throws Exception {
    long t = System.currentTimeMillis();
    config.parseSkipTerms(bean.getTags());
    Rectangle rect = new Rectangle(PdfUtil.convertFromMillimeters(config.getWidth()),
            PdfUtil.convertFromMillimeters(config.getHeight()));
    Document document = new Document(rect);
    PdfWriter writer = null;//  w  w  w.  j a  v a2s.  co m
    FileOutputStream fos = null;
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {
        boolean validName = bean.getInputFile().getName().toLowerCase().endsWith(".xml");
        writer = PdfWriter.getInstance(document, baos);

        if (validName) {
            setMargins(document);
            parseXMLDocument(bean, document, writer);
            baos.flush();
            fos = new FileOutputStream(bean.getOutputFile());
            fos.write(baos.toByteArray());
            fos.flush();
            baos.close();
        }

    } catch (Exception ex) {
        ex.printStackTrace();
    } finally {

        baos.close();
        if (writer != null) {
            writer.close();
        }
        if (fos != null) {
            fos.close();
        }
    }
    long delta = System.currentTimeMillis() - t;
    logger.log(Level.INFO, "Successful album page generation. (total execution time: " + delta + "ms)");
}

From source file:org.jfree.chart.swt.ChartPdf.java

License:Open Source License

public static void saveChartAsPDF(File file, JFreeChart chart, int width, int height)
        throws DocumentException, FileNotFoundException, IOException {
    if (chart != null) {
        boolean success = false;
        String old = null;/*from w w w  . j ava 2s  .c om*/
        File oldFile = null;
        boolean append = file.exists();
        if (append) {
            old = file.getAbsolutePath() + ".old"; //$NON-NLS-1$
            oldFile = new File(old);
            oldFile.delete();
            file.renameTo(oldFile);
        }
        try (BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(file))) {
            // convert chart to PDF with iText:
            Rectangle pagesize = new Rectangle(width, height);
            if (append) {
                PdfReader reader = new PdfReader(old);
                PdfStamper stamper = new PdfStamper(reader, out);
                try {
                    int n = reader.getNumberOfPages() + 1;
                    stamper.insertPage(n, pagesize);
                    PdfContentByte overContent = stamper.getOverContent(n);
                    writeChart(chart, width, height, overContent);
                    ColumnText ct = new ColumnText(overContent);
                    ct.setSimpleColumn(width - 50, 50, width - 12, height, 150, Element.ALIGN_RIGHT);
                    Paragraph paragraph = new Paragraph(String.valueOf(n),
                            new Font(FontFamily.HELVETICA, 9, Font.NORMAL, BaseColor.DARK_GRAY));
                    paragraph.setAlignment(Element.ALIGN_RIGHT);
                    ct.addElement(paragraph);
                    ct.go();
                    success = true;
                } finally {
                    stamper.close();
                    reader.close();
                    oldFile.delete();
                }
            } else {
                Document document = new Document(pagesize, 50, 50, 50, 50);
                document.addCreationDate();
                document.addCreator(Constants.APPLICATION_NAME);
                document.addAuthor(System.getProperty("user.name")); //$NON-NLS-1$
                try {
                    PdfWriter writer = PdfWriter.getInstance(document, out);
                    document.open();
                    writeChart(chart, width, height, writer.getDirectContent());
                    success = true;
                } finally {
                    document.close();
                }
            }
        }
        if (!success) {
            file.delete();
            if (oldFile != null)
                oldFile.renameTo(file);
        }
    }
}

From source file:org.openscience.cdk.applications.taverna.basicutilities.ChartTool.java

License:Open Source License

/**
 * Writes given charts into target PDF file.
 * /* w ww.ja v  a 2s . co m*/
 * @param file
 * @param charts
 * @param annotations
 * @throws IOException
 */
public synchronized void writeChartAsPDF(File file, List<Object> chartObjects) throws IOException {
    Rectangle pagesize = new Rectangle(this.width, this.height);
    Document document = new Document(pagesize, 50, 50, 50, 50);
    try {
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.addAuthor("CDK-Taverna 2.0");
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        for (int i = 0; i < chartObjects.size(); i++) {
            Object obj = chartObjects.get(i);
            if (obj instanceof JFreeChart) {
                JFreeChart chart = (JFreeChart) obj;
                this.addChartPageToPDF(chart, cb);
            } else if (obj instanceof String) {
                String annotation = (String) obj;
                this.addAnnotationToPDF(annotation, document);
            }
            document.newPage();
        }
    } catch (DocumentException e) {
        ErrorLogger.getInstance().writeError(CDKTavernaException.CANT_CREATE_PDF_FILE + file.getPath(),
                this.getClass().getSimpleName(), e);
    }
    document.close();
}

From source file:org.orbisgis.core_export.GeoSpatialPDF.java

License:Open Source License

/**
 * Create the PDF document and a the geospatial tags
 *
 * @param out//  w w  w  . j a  v a2s  . com
 * @param mt
 * @param pm
 * @throws IOException
 */
public void createPDF(OutputStream out, MapTransform mt, ProgressMonitor pm) throws IOException {
    Document document = new Document(new Rectangle(width, height));
    try {
        PdfWriter writer = PdfWriter.getInstance(document, out);
        writer.setTagged();
        writer.setUserProperties(true);
        document.open();

        PdfContentByte cb = writer.getDirectContent();

        int numLayers = rootLayer.getLayerCount();
        for (int i = numLayers - 1; i >= 0; i--) {
            ILayer layer = rootLayer.getLayer(i);
            processSubLayer(layer, mt, writer, cb, pm, null);
        }
        georefPdf(writer, mt);

    } catch (DocumentException ex) {
        throw new IOException("Cannot create the pdf", ex);
    }
    document.close();
}

From source file:org.orbisgis.mapcomposer.controller.utils.exportThreads.ExportPDFThread.java

License:Open Source License

@Override
public void run() {
    try {//from  w  w  w.  j av  a2 s.  c o  m
        Document pdfDocument = null;
        //Find the Document GE to create the BufferedImage where all the GE will be drawn
        for (GraphicalElement ge : geIsVectorMap.keySet()) {
            if (ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document) {
                pdfDocument = new Document(new Rectangle(ge.getWidth(), ge.getHeight()));
                height = ge.getHeight();
            }
        }
        //If no Document was created, throw an exception
        if (pdfDocument == null) {
            throw new IllegalArgumentException(i18n.tr(
                    "Error on export : The list of GraphicalElement to export does not contain any Document GE."));
        }
        //Open the document
        PdfWriter writer = PdfWriter.getInstance(pdfDocument, new FileOutputStream(path));
        writer.setUserProperties(true);
        writer.setRgbTransparencyBlending(true);
        writer.setTagged();
        pdfDocument.open();

        PdfContentByte cb = writer.getDirectContent();

        progressBar.setIndeterminate(true);
        progressBar.setStringPainted(true);
        progressBar.setString(i18n.tr("Exporting the document ..."));

        int geCount = 0;
        int numberOfGe[] = new int[geManager.getRegisteredGEClasses().size()];
        for (int i = 0; i < numberOfGe.length; i++) {
            numberOfGe[i] = 0;
        }
        //Draw each GraphicalElement in the BufferedImage
        for (GraphicalElement ge : geStack) {
            if ((ge instanceof org.orbisgis.mapcomposer.model.graphicalelement.element.Document))
                continue;

            double rad = Math.toRadians(ge.getRotation());
            double newHeight = Math.abs(sin(rad) * ge.getWidth()) + Math.abs(cos(rad) * ge.getHeight());
            double newWidth = Math.abs(sin(rad) * ge.getHeight()) + Math.abs(cos(rad) * ge.getWidth());

            int maxWidth = Math.max((int) newWidth, ge.getWidth());
            int maxHeight = Math.max((int) newHeight, ge.getHeight());

            String layerName = ge.getGEName()
                    + numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())];

            if (geIsVectorMap.get(ge)) {
                PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight);
                Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight);
                PdfLayer layer = new PdfLayer(layerName, writer);
                cb.beginLayer(layer);
                ((RendererVector) geManager.getRenderer(ge.getClass())).drawGE(g2dTemplate, ge);
                cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);
                g2dTemplate.dispose();
                cb.endLayer();
            }

            else {
                ByteArrayOutputStream baos = new ByteArrayOutputStream();
                BufferedImage bi = ((RendererRaster) geManager.getRenderer(ge.getClass())).createGEImage(ge,
                        null);
                ImageIO.write(bi, "png", baos);
                Image image = Image.getInstance(baos.toByteArray());
                image.setAbsolutePosition(ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);

                PdfTemplate pdfTemplate = cb.createTemplate(maxWidth, maxHeight);
                Graphics2D g2dTemplate = pdfTemplate.createGraphics(maxWidth, maxHeight);
                PdfLayer layer = new PdfLayer(layerName, writer);
                cb.beginLayer(layer);
                g2dTemplate.drawImage(bi, 0, 0, null);
                cb.addTemplate(pdfTemplate, ge.getX() + (ge.getWidth() - maxWidth) / 2,
                        -ge.getY() + height - ge.getHeight() + (ge.getHeight() - maxHeight) / 2);
                g2dTemplate.dispose();
                cb.endLayer();
            }
            numberOfGe[geManager.getRegisteredGEClasses().indexOf(ge.getClass())]++;

            progressBar.setIndeterminate(false);
            progressBar.setValue((geCount * 100) / geIsVectorMap.keySet().size());
            progressBar.revalidate();
            geCount++;
        }

        pdfDocument.close();
        //Wait a bit before erasing the progress bar
        progressBar.setValue(progressBar.getMaximum());
        progressBar.setString(i18n.tr("Document successfully exported."));
        try {
            Thread.sleep(1500);
        } catch (InterruptedException e) {
            LoggerFactory.getLogger(ExportPDFThread.class).error(e.getMessage());
        }
        progressBar.setValue(0);
        progressBar.setStringPainted(false);

    } catch (IllegalArgumentException | IOException | DocumentException ex) {
        LoggerFactory.getLogger(ExportPDFThread.class).error(ex.getMessage());
    }
}