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:de.fub.maps.project.snapshot.impl.PdfSnapShotExporter.java

License:Apache License

private void handleExport(final File selectedFile, final Component component) {
    RequestProcessor.getDefault().post(new Runnable() {
        @Override//from ww  w  .jav  a 2s . c  o m
        public void run() {
            SwingUtilities.invokeLater(new Runnable() {
                @Override
                public void run() {

                    if (component != null) {
                        PdfGraphics2D pdfGraphics2D = null;
                        try {
                            Dimension preferredSize = component.getSize();
                            Dimension dimension = preferredSize; //DimensionUtil.computeToA4Pdf(preferredSize);
                            // step 1
                            Document document = new Document(new Rectangle(dimension.width, dimension.height));
                            // step 2
                            PdfWriter writer = PdfWriter.getInstance(document,
                                    new FileOutputStream(selectedFile));
                            // step 3
                            document.open();
                            //                                document.newPage();
                            // step 4
                            PdfContentByte cb = writer.getDirectContent();
                            //                                PdfTemplate map = cb.createTemplate(dimension.width * 10, dimension.height * 10);
                            pdfGraphics2D = new PdfGraphics2D(cb, dimension.width, dimension.height);
                            //                                component.setPreferredSize(dimension);
                            //                                component.setSize(dimension);
                            //                                component.revalidate();
                            //                                component.repaint();
                            // paintAll must be called, a simple paint does
                            //not change the size of the component
                            component.printAll(pdfGraphics2D);
                            //                                component.setPreferredSize(preferredSize);
                            //                                component.setSize(preferredSize);
                            //                                component.revalidate();
                            //                                component.repaint();

                            pdfGraphics2D.dispose();
                            //                                cb.addTemplate(map, 0, 0);
                            // step 5
                            document.close();
                        } catch (FileNotFoundException ex) {
                            Exceptions.printStackTrace(ex);
                        } catch (DocumentException ex) {
                            Exceptions.printStackTrace(ex);
                        } finally {
                            if (pdfGraphics2D != null) {
                                pdfGraphics2D.dispose();
                            }
                        }
                    }
                }
            });
        }
    });
}

From source file:de.mat.utils.pdftools.PdfResize.java

License:Mozilla Public License

/**
/**//from w w  w. j a  va  2s. c o  m
 * <h4>FeatureDomain:</h4>
 *     PublishingTools
 * <h4>FeatureDescription:</h4>
 *     scales and move comntents of the pdf pages from fileSrc and output to
 *     fileNew
 * <h4>FeatureResult:</h4>
 *   <ul>
 *     <li>create PDF - fileNew
 *   </ul> 
 * <h4>FeatureKeywords:</h4>
 *     PDF Publishing
 * @param fileSrc - source-pdf
 * @param fileNew - scaled dest-pdf
 * @param factorX - scaling x
 * @param factorY - scaling y
 * @param pixelLeft - move right
 * @param pixelTop - move down
 * @throws Exception
 */
public static void resizePdf(String fileSrc, String fileNew, float factorX, float factorY, float pixelLeft,
        float pixelTop) throws Exception {

    // open reader
    PdfReader reader = new PdfReader(fileSrc);

    // get pagebasedata
    int pageCount = reader.getNumberOfPages();
    Rectangle psize = reader.getPageSize(1);
    float width = psize.getHeight();
    float height = psize.getWidth();

    // open writer
    Document documentNew = new Document(new Rectangle(height * factorY, width * factorX));
    PdfWriter writerNew = PdfWriter.getInstance(documentNew, new FileOutputStream(fileNew));
    documentNew.open();
    PdfContentByte cb = writerNew.getDirectContent();

    // iterate pages
    int i = 0;
    while (i < pageCount) {
        i++;
        // imoport page from reader and scale it to writer
        documentNew.newPage();
        PdfImportedPage page = writerNew.getImportedPage(reader, i);
        cb.addTemplate(page, factorX, 0, 0, factorY, pixelLeft, pixelTop);

        if (LOGGER.isInfoEnabled())
            LOGGER.info("AddPage " + i + " from:" + fileSrc + " to:" + fileNew);
    }

    documentNew.close();
    writerNew.close();
}

From source file:edu.fullerton.viewerplugin.PluginSupport.java

License:Open Source License

public void saveImageAsPdfFile(JFreeChart chart, String filename) throws WebUtilException {
    try {//from   w  w w  .  j av  a 2  s . co  m
        OutputStream out = new BufferedOutputStream(new FileOutputStream(filename));
        Rectangle pagesize = new Rectangle(width, height);
        com.itextpdf.text.Document document;
        document = new com.itextpdf.text.Document(pagesize, 50, 50, 50, 50);
        try {
            PdfWriter writer = PdfWriter.getInstance(document, out);
            FontMapper mapper = new DefaultFontMapper();
            document.addAuthor("JFreeChart");
            document.addSubject("Demonstration");
            document.open();
            PdfContentByte cb = writer.getDirectContent();
            PdfTemplate tp = cb.createTemplate(width, height);
            Graphics2D g2 = tp.createGraphics(width, height, mapper);
            Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);
            chart.draw(g2, r2D);
            g2.dispose();
            cb.addTemplate(tp, 0, 0);
        } catch (DocumentException de) {
            throw new WebUtilException("Saving as pdf", de);
        }
        document.close();
    } catch (FileNotFoundException ex) {
        throw new WebUtilException("Saving plot as pdf: ", ex);
    }

}

From source file:edu.gcsc.vrl.jfreechart.JFExport.java

License:Open Source License

/**
 * Export jfreechart to image format. File must have an extension like jpg,
 * png, pdf, svg, eps. Otherwise export will fail.
 *
 * @param file Destination Filedescriptor
 * @param chart JFreechart//  w  w w.j  a v a2  s  .  c  o m
 * @throws Exception
 */
public boolean export(File file, JFreeChart chart) throws Exception {

    /*Get extension from file - File must have one extension of
     jpg,png,pdf,svg,eps. Otherwise the export will fail.
     */
    String ext = JFUtils.getExtension(file);

    //  TODO - Make x,y variable
    int x, y;
    // Set size for image (jpg)
    x = 550;
    y = 470;

    int found = 0;

    // JPEG
    if (ext.equalsIgnoreCase("jpg")) {
        ChartUtilities.saveChartAsJPEG(file, chart, x, y);
        found++;
    }
    // PNG
    if (ext.equalsIgnoreCase("png")) {
        ChartUtilities.saveChartAsPNG(file, chart, x, y);
        found++;
    }

    // PDF
    if (ext.equalsIgnoreCase("pdf")) {

        //JRAbstractRenderer jfcRenderer = new JFreeChartRenderer(chart);
        // Use here size of r2d2 (see below, Rectangel replaced by Rectangle2D !)
        Rectangle pagesize = new Rectangle(x, y);

        Document document = new Document(pagesize, 50, 50, 50, 50);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        PdfTemplate tp = cb.createTemplate(x, y);

        Graphics2D g2 = tp.createGraphics(x, y, new DefaultFontMapper());

        // Draw doesn't works with Rectangle argument - use rectangle2D instead !
        //chart.draw(g2, (java.awt.geom.Rectangle2D) new Rectangle(x,y));
        Rectangle2D r2d2 = new Rectangle2D.Double(0, 0, x, y);
        chart.draw(g2, r2d2);

        g2.dispose();
        cb.addTemplate(tp, 0, 0);
        document.close();

        found++;

    }

    // SVG
    if (ext.equalsIgnoreCase("svg")) {
        // When exporting to SVG don't forget this VERY important line:
        // svgGenerator.setSVGCanvasSize(new Dimension(width, height));
        // Otherwise renderers will not know the size of the image. It will be drawn to the correct rectangle, but the image will not have a correct default siz
        // Get a DOMImplementation
        DOMImplementation domImpl = SVGDOMImplementation.getDOMImplementation();
        org.w3c.dom.Document document = domImpl.createDocument(null, "svg", null);
        SVGGraphics2D svgGenerator = new SVGGraphics2D(document);
        //chart.draw(svgGenerator,new Rectangle(x,y));
        chart.draw(svgGenerator, new Rectangle2D.Double(0, 0, x, y));

        boolean useCSS = true; // we want to use CSS style attribute

        Writer out = new OutputStreamWriter(new FileOutputStream(file), "UTF-8");
        svgGenerator.stream(out, useCSS);
        out.close();
        found++;
    }

    if (ext.equalsIgnoreCase("eps")) {

        //Graphics2D g = new EpsGraphics2D();
        FileOutputStream out = new FileOutputStream(file);
        //Writer out=new FileWriter(file);
        Graphics2D g = new EpsGraphics(file.getName(), out, 0, 0, x, y, ColorMode.COLOR_RGB);

        chart.draw(g, new Rectangle2D.Double(0, 0, x, y));
        //Writer out=new FileWriter(file);
        out.write(g.toString().getBytes());
        out.close();
        found++;
    }

    if (found == 0) {
        throw new IllegalArgumentException("File format '" + ext + "' not supported!");
    }

    return true;

}

From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java

License:Open Source License

@SuppressWarnings("hiding")
public static boolean printList(ArrayList<ContainerLabel> containers) throws PrintFailedException {
    log.debug("Invoked printList ");
    boolean result = false;
    ContainerLabel label = new ContainerLabel();
    if (containers.isEmpty()) {
        log.debug("No labels to print.");
    } else {/*from  www.j av a2 s.  co m*/
        LabelDefinitionType printDefinition = null;
        LabelDefinitionListType printDefs = PreCaptureSingleton.getInstance().getPrintFormatDefinitionList();
        List<LabelDefinitionType> printDefList = printDefs.getLabelDefinition();
        Iterator<LabelDefinitionType> il = printDefList.iterator();
        while (il.hasNext()) {
            LabelDefinitionType def = il.next();
            if (def.getTitle().equals(PreCaptureSingleton.getInstance().getProperties().getProperties()
                    .getProperty(PreCaptureProperties.KEY_SELECTED_PRINT_DEFINITION))) {
                printDefinition = def;
            }
        }
        if (printDefinition == null) {
            log.error("No selected print format defintion found.");
            //TODO change from message to error handling dialog that allows picking a print format.
            JOptionPane.showMessageDialog(null, "Unable to print.  No print format is selected.");
        } else {

            log.debug(printDefinition.getTitle());
            log.debug(printDefinition.getTextOrentation().toString());

            LabelEncoder encoder = new LabelEncoder(containers.get(0));
            try {
                Image image = encoder.getImage();
                Document document = new Document();
                PdfWriter.getInstance(document, new FileOutputStream(PreCaptureSingleton.getInstance()
                        .getProperties().getProperties().getProperty(PreCaptureProperties.KEY_LABELPRINTFILE)));
                // Convert units in print definition to points (72 points/inch, 28.346456 points/cm)

                int paperWidthPoints = 612; // 8.5"
                int paperHeightPoints = 792; // 11"
                int marginsPoints = 36; // 0.5"
                int labelWidthPoints = 540; // 7.5" 
                int labelHeightPoints = 720; // 10"
                int numColumns = 1; // goes with above

                numColumns = printDefinition.getColumns();
                float relWidthTextCell = printDefinition.getRelWidthTextCell();
                float relWidthBarcodeCell = printDefinition.getRelWidthBarcodeCell();
                log.debug("relWidthTextCell = " + relWidthTextCell);
                log.debug("relWidthBarcodeCell = " + relWidthBarcodeCell);

                if (printDefinition.getUnits().toString().toLowerCase().equals("inches")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 72f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 72f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 72f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 72f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 72f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("cm")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 28.346456f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 28.346456f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 28.346456f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 28.346456f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 28.346456f);
                }
                if (printDefinition.getUnits().toString().toLowerCase().equals("points")) {
                    paperWidthPoints = (int) Math.floor(printDefinition.getPaperWidth() * 1f);
                    paperHeightPoints = (int) Math.floor(printDefinition.getPaperHeight() * 1f);
                    marginsPoints = (int) Math.floor(printDefinition.getMargins() * 1f);
                    labelWidthPoints = (int) Math.floor(printDefinition.getLabelWidth() * 1f);
                    labelHeightPoints = (int) Math.floor(printDefinition.getLabelHeight() * 1f);
                }

                if (paperWidthPoints == 612 && paperHeightPoints == 792) {
                    document.setPageSize(PageSize.LETTER);
                } else {
                    document.setPageSize(new Rectangle(paperWidthPoints, paperHeightPoints));
                }
                document.setMargins(marginsPoints, marginsPoints, marginsPoints, marginsPoints);
                document.open();

                // Sanity check
                if (paperWidthPoints <= 0) {
                    paperWidthPoints = 612;
                }
                if (paperHeightPoints <= 0) {
                    paperHeightPoints = 792;
                }
                if (marginsPoints < 0) {
                    marginsPoints = 0;
                }
                if (labelWidthPoints <= 0) {
                    labelWidthPoints = 540;
                }
                if (labelHeightPoints <= 0) {
                    labelHeightPoints = 720;
                }
                if (paperWidthPoints + (marginsPoints * 2) < labelWidthPoints) {
                    labelWidthPoints = paperWidthPoints + (marginsPoints * 2);
                    log.debug("Adjusting label width to fit printable page width");
                }
                if (paperHeightPoints + (marginsPoints * 2) < labelHeightPoints) {
                    labelHeightPoints = paperHeightPoints + (marginsPoints * 2);
                    log.debug("Adjusting label height to fit printable page height");
                }

                // calculate how many columns will fit on the paper.
                int columns = (int) Math.floor((paperWidthPoints - (marginsPoints * 2)) / labelWidthPoints);
                // if specified column count is smaller, use the specified.
                if (numColumns < columns) {
                    columns = numColumns;
                    log.debug(
                            "Fewer columns specified in definition than will fit on page, using specified column count of "
                                    + numColumns);
                }

                // define two table cells per column, one for text one for barcode.
                int subCellColumnCount = columns * 2;

                // set the table, with an absolute width and relative widths of the cells in the table;
                PdfPTable table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                // figure out the width of the cells containing the barcodes.
                float ratio = ((float) relWidthBarcodeCell)
                        / (((float) relWidthBarcodeCell) + ((float) relWidthTextCell));
                float barcodeCellWidthPoints = (float) Math.floor(labelWidthPoints * ratio);
                log.debug("Width of barcode cell in points: " + barcodeCellWidthPoints);

                //Rectangle pageSizeRectangle = new Rectangle(paperWidthPoints, paperHeightPoints);
                //table.setWidthPercentage(cellWidthsPoints, pageSizeRectangle);
                //table.setTotalWidth(cellWidthsPoints);

                // Calculate how many cells fit on a page (two cells per label).
                int labelsPerColumn = (int) Math
                        .floor((paperHeightPoints - (marginsPoints * 2)) / labelHeightPoints);
                int cellsPerPage = subCellColumnCount * labelsPerColumn;
                log.debug("Labels per column = " + labelsPerColumn);
                log.debug("Cells per page = " + cellsPerPage);

                Iterator<ContainerLabel> iterLabels = containers.iterator();

                int cellCounter = 0; // counts number of cells filled on a page.
                int counter = 0; // counts number of pre capture label data rows to print (each of which may request more than one copy).

                // TODO: Doesn't fit on page.

                while (iterLabels.hasNext()) {
                    // Loop through all of the container labels found to print 
                    label = iterLabels.next();
                    if (label != null) {
                        log.debug(label);
                        log.debug("Label: " + counter + " " + label.toString());
                        for (int toPrint = 0; toPrint < label.getNumberToPrint(); toPrint++) {
                            // For each container label, loop through the number of requested copies 
                            // Generate a text and a barcode cell for each, and add to array for page
                            int toPrintPlus = toPrint + 1; // for pretty counter in log.
                            log.debug("Copy " + toPrintPlus + " of " + label.getNumberToPrint());

                            PdfPCell cell = label.toPDFCell(printDefinition);
                            cell.setFixedHeight(labelHeightPoints);
                            // Colors to illustrate where the cells are on the layout
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell.setBackgroundColor(new BaseColor(255, 255, 30));
                            }

                            PdfPCell cell_barcode = new PdfPCell();
                            cell_barcode.setBorderColor(BaseColor.LIGHT_GRAY);
                            cell_barcode.disableBorderSide(PdfPCell.LEFT);
                            cell_barcode.setVerticalAlignment(PdfPCell.ALIGN_TOP);
                            cell_barcode.setHorizontalAlignment(Element.ALIGN_RIGHT);
                            cell_barcode.setFixedHeight(labelHeightPoints);
                            if (PreCaptureSingleton.getInstance().getProperties().getProperties()
                                    .getProperty(PreCaptureProperties.KEY_DEBUGLABEL).equals("true")) {
                                cell_barcode.setBackgroundColor(new BaseColor(255, 30, 255));
                            }

                            encoder = new LabelEncoder(label);
                            image = encoder.getImage();
                            image.setAlignment(Image.ALIGN_TOP);
                            //image.setAlignment(Image.ALIGN_LEFT);
                            image.setAlignment(Image.ALIGN_RIGHT);
                            image.scaleToFit(barcodeCellWidthPoints, labelHeightPoints);
                            cell_barcode.addElement(image);

                            table.addCell(cell);
                            table.addCell(cell_barcode);

                            cellCounter = cellCounter + 2; // we've added two cells to the page (two cells per label).
                            log.debug("Cells " + cellCounter + " of " + cellsPerPage + " cells per page.");

                            // If we have hit a full set of labels for the page, add them to the document
                            // in each column, filling left to right
                            if (cellCounter >= cellsPerPage - 1) {
                                log.debug("Page is full");
                                log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                                        + table.getRows().size() + " rows ");
                                // Reset to begin next page
                                cellCounter = 0;
                                table.setLockedWidth(true);
                                document.add(table);
                                log.debug("Adding new page");
                                document.newPage();
                                table = setupTable(paperWidthPoints, marginsPoints, labelWidthPoints, columns,
                                        subCellColumnCount, relWidthTextCell, relWidthBarcodeCell);
                                log.debug("Setup new table");
                            }
                        } // end loop through toPrint (for a taxon/precapture label data row)
                        counter++; // Increment number of pre capture label data rows.
                    } // end if not null label
                } // end while results has next (for all taxa requested)
                  // get any remaining cells in pairs
                if (cellCounter > 0) {
                    log.debug("Adding remaining cells in partial page");
                    if (cellCounter <= cellsPerPage) {
                        for (int i = cellCounter; i <= cellsPerPage; i++) {
                            PdfPCell emptyCell = new PdfPCell();
                            emptyCell.setBorder(PdfPCell.NO_BORDER);
                            table.addCell(emptyCell);
                        }
                    }
                    log.debug("Table has " + table.getNumberOfColumns() + " columns and "
                            + table.getRows().size() + " rows ");
                    table.setLockedWidth(true);
                    document.add(table);
                }
                document.close();

                // send to printer
                PrintingUtility.sendPDFToPrinter(printDefinition, paperWidthPoints, paperHeightPoints);

                // Check to see if there was content in the document.
                if (counter == 0) {
                    result = false;
                } else {
                    // Printed to pdf ok.
                    result = true;
                }
            } catch (FileNotFoundException e) {
                log.debug(e.getMessage(), e);
                throw new PrintFailedException("File not found.");
            } catch (DocumentException e) {
                log.error(e.getMessage(), e);
                throw new PrintFailedException("Error building/printing PDF document. " + e.getMessage());
            } catch (OutOfMemoryError e) {
                System.out.println("Out of memory error. " + e.getMessage());
                System.out.println("Failed.  Too many labels.");
                throw new PrintFailedException("Ran out of memory, too many labels at once.");
            } catch (BarcodeCreationException e) {
                System.out.println("BarcodeCreationException. " + e.getMessage());
                System.out.println("Failed.  Couldn't create barcode.");
                throw new PrintFailedException(
                        "Unable to create barcode.  Probably too many characters to encode. " + e.getMessage());
            }
        }
        log.debug("printList Done. Success = " + result);
    }
    return result;
}

From source file:emailworkshop.EmailWorkshop.java

public static void gerarPDF(String nome, int numCert) {
    Calendar data = Calendar.getInstance();

    // criao do objeto documento
    Document document = new Document() {
    };//from  ww  w.j  ava 2 s .  c om
    document.setPageSize(new Rectangle(800, 500));
    try {

        PdfWriter.getInstance(document, new FileOutputStream("Certificado.pdf"));
        document.open();

        // adicionando um pargrafo ao documento
        Image img = Image.getInstance("logo.png");

        img.scaleAbsoluteWidth(620);
        img.scaleAbsoluteHeight(130);
        Paragraph texto1 = new Paragraph("\n Conferimos o presente Certificado a " + nome + " por ter "
                + "participado do II Workshop de Inovao, com durao de 4 horas. Onde foram apresentadas as palestras: ");
        Paragraph texto2 = new Paragraph(
                "Economia compartilha & Inovao Disruptiva - Arthur Schuler da Igreja.\n"
                        + "Empreendedorismo: Um case de sucesso - Cludio Kopp.");
        Paragraph texto3 = new Paragraph(
                "\n\n\n\n\nRegistrado na UFPR Setor Palotina Livro 4 certificado Nr " + numCert + ".");

        Paragraph localData = new Paragraph("\nPalotina, " + new SimpleDateFormat("dd").format(data.getTime())
                + " de " + new SimpleDateFormat("MMMM").format(data.getTime()) + " de "
                + new SimpleDateFormat("yyyy").format(data.getTime()) + ".\n\n");

        texto1.setAlignment("center");
        texto2.setAlignment("center");
        texto3.setAlignment("right");
        localData.setAlignment("center");

        Image assinatura = Image.getInstance("assinatura.png");
        assinatura.scaleAbsoluteHeight(75);
        assinatura.scaleAbsoluteWidth(250);
        assinatura.setAbsolutePosition(275, 110);

        document.add(img);
        document.add(texto1);
        document.add(texto2);
        document.add(localData);

        document.add(assinatura);
        document.add(texto3);

        document.close();
    } catch (DocumentException | IOException de) {
        System.err.println(de.getMessage());
    }

}

From source file:engine.Pdf.java

@Deprecated
public static void start(Vector<HoughLine> vectors, int width, int height) {
    try {/*from   w ww  .j a  v a2s. co m*/
        Rectangle size = new Rectangle(width, height);
        Document document = new Document(size);

        //            document.setPageSize(size);
        PdfWriter writer = PdfWriter.getInstance(document,
                new FileOutputStream(new File("source", "output.pdf")));
        writer.createXmpMetadata();
        document.open();
        addMetaData(document);
        //            addTitlePage(document);
        //            addContent(document);
        drawLines(vectors, writer);
        document.close();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    }
}

From source file:EplanPrinter.PDFPrint.java

License:Open Source License

public String blankPDF(String loc, String message) throws DocumentException, FileNotFoundException {
    Rectangle size = new Rectangle(1700f, 1200f);
    Document doc = new Document(size);
    PdfWriter.getInstance(doc, new FileOutputStream(loc));

    doc.open();/*  w  ww  .  java  2 s . c o  m*/
    doc.add(new Paragraph("PDF could not be found: " + message));
    doc.close();

    return "";
}

From source file:es.jscan.Pantallas.PantallaPrincipal.java

License:Apache License

@Action
public Boolean guardarPdf() {
    if (contimagen < 1) {
        return false;
    }//from   ww  w.  ja v  a 2 s.  c  o m

    final PantallaBarra pantbarra = new PantallaBarra(PantallaPrincipal.this, false);
    pantbarra.setTitle("Generando fichero de destino");
    pantbarra.botonParar.setVisible(false);
    errorpdf = false;

    new Thread() {
        @Override
        public void run() {
            Document pdfDocument = new Document();
            //                Document pdfDocument = new Document(PageSize.A4, 0, 0, 0, 0);
            Calendar cal = Calendar.getInstance();
            String anio = String.valueOf(cal.get(Calendar.YEAR));
            String mes = String.valueOf((cal.get(Calendar.MONTH) + 1)).length() == 1
                    ? "0" + String.valueOf((cal.get(Calendar.MONTH) + 1))
                    : String.valueOf((cal.get(Calendar.MONTH) + 1));
            String dia = String.valueOf(cal.get(Calendar.DAY_OF_MONTH)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.DAY_OF_MONTH))
                    : String.valueOf(cal.get(Calendar.DAY_OF_MONTH));
            String hora = String.valueOf(cal.get(Calendar.HOUR_OF_DAY)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.HOUR_OF_DAY))
                    : String.valueOf(cal.get(Calendar.HOUR_OF_DAY));
            String minuto = String.valueOf(cal.get(Calendar.MINUTE)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.MINUTE))
                    : String.valueOf(cal.get(Calendar.MINUTE));
            String segundo = String.valueOf(cal.get(Calendar.SECOND)).length() == 1
                    ? "0" + String.valueOf(cal.get(Calendar.SECOND))
                    : String.valueOf(cal.get(Calendar.SECOND));

            try {
                if (DEBUG) {
                    Utilidades.escribeLog("Generando PDFs -guardarPdf-");
                }
                if (contimagen < 2) {
                    pantbarra.barra.setMinimum(1);
                    pantbarra.barra.setMaximum(2);
                } else {
                    pantbarra.barra.setMinimum(1);
                    pantbarra.barra.setMaximum(rutaboton.length);
                }
                pantbarra.barra.setValue(1);
                pantbarra.setTitle(pantbarra.getTitle());
                pantbarra.validate();

                String nombrefichero = "Documentacion.pdf";
                String ruta = rutalote + separador + nombrefichero + ".pdf";

                if (!textoFichero.getText().isEmpty()) {
                    nombrefichero = textoFichero.getText() + ".pdf";
                }

                if (!textoDirectorio.getText().isEmpty()) {
                    ruta = textoDirectorio.getText();
                    ruta = ruta + separador + nombrefichero;
                }

                FileOutputStream ficheroPdf = new FileOutputStream(ruta);
                File filename = new File(rutaboton[0].toString());
                java.awt.image.BufferedImage imagen = javax.imageio.ImageIO.read(filename);
                com.itextpdf.text.Image imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null);
                pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight()));
                PdfWriter writer = PdfWriter.getInstance(pdfDocument, ficheroPdf);
                writer.open();
                pdfDocument.open();
                pdfDocument.addHeader("IP", lote.substring(16, 19) + "." + lote.substring(19, 22) + "."
                        + lote.substring(22, 25) + "." + lote.substring(25, 28));
                pdfDocument.addHeader("fechadigita",
                        lote.substring(6, 8) + "/" + lote.substring(4, 6) + "/" + lote.substring(0, 4) + " "
                                + lote.substring(9, 11) + ":" + lote.substring(11, 13) + ":"
                                + lote.substring(13, 15));
                pdfDocument.addHeader("fechacreacion",
                        dia + "/" + mes + "/" + anio + " " + hora + ":" + minuto + ":" + segundo);

                for (int i = 0; i < rutaboton.length; i++) {
                    filename = new File(rutaboton[i].toString());
                    imagen = javax.imageio.ImageIO.read(filename);
                    imagenpdf = com.itextpdf.text.Image.getInstance(imagen, null);
                    //                        imagenpdf.scaleToFit(PageSize.A4.getWidth(), PageSize.A4.getHeight());
                    //                        imagenpdf.setAlignment(com.itextpdf.text.Image.ALIGN_JUSTIFIED_ALL);
                    //                        com.itextpdf.text.Image instance = com.itextpdf.text.Image.getInstance(imagenpdf);
                    //                        pdfDocument.setPageSize(new com.itextpdf.text.Rectangle(PageSize.A4.getWidth(), PageSize.A4.getHeight()));
                    pantbarra.barra.setValue(i);
                    pantbarra.setTitle(titulo + "     " + (i + 1) + " de " + rutaboton.length);
                    pdfDocument.setPageSize(new Rectangle(imagenpdf.getWidth(), imagenpdf.getHeight()));
                    //                        pdfDocument.add(instance);
                    pdfDocument.add(imagenpdf);
                    pdfDocument.newPage();
                    pantbarra.validate();
                }
                pdfDocument.close();
                writer.close();
            } catch (Exception e) {
                Utilidades.escribeLog("Error Generando PDFs -guardarPdf- " + e.getMessage());
                errorpdf = true;
            }
            pantbarra.dispose();
        }
    }.start();
    pantbarra.setModalityType(Dialog.ModalityType.APPLICATION_MODAL);
    pantbarra.setVisible(false);
    pantbarra.setVisible(true);
    return !errorpdf;
}

From source file:es.jscan.Pantallas.PantallaPrincipal.java

License:Apache License

private void tiffToPdf(String origen, String destino) {
    try {//from  w ww.  ja va2s .  c o m
        //Read the Tiff File
        RandomAccessFileOrArray myTiffFile = new RandomAccessFileOrArray(origen);
        //Find number of images in Tiff file
        int numberOfPages = TiffImage.getNumberOfPages(myTiffFile);
        //  System.out.println("Number of Images in Tiff File" + numberOfPages);
        com.itextpdf.text.Image tempImage = TiffImage.getTiffImage(myTiffFile, 1);
        Document TifftoPDF = new Document();
        TifftoPDF.setPageSize(new Rectangle(tempImage.getWidth(), tempImage.getHeight()));
        PdfWriter.getInstance(TifftoPDF, new FileOutputStream(destino));
        TifftoPDF.open();
        for (int i = 1; i <= numberOfPages; i++) {
            tempImage = TiffImage.getTiffImage(myTiffFile, i);
            TifftoPDF.setPageSize(new Rectangle(tempImage.getWidth(), tempImage.getHeight()));
            TifftoPDF.add(tempImage);
        }
        TifftoPDF.close();
    } catch (Exception ex) {
        Utilidades.escribeLog("Error al convertir de Tiff a PDF -tiffToPdf- Error " + ex.getMessage());
    }

}