Example usage for com.lowagie.text Document newPage

List of usage examples for com.lowagie.text Document newPage

Introduction

In this page you can find the example usage for com.lowagie.text Document newPage.

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:jm.Reporte.java

License:GNU General Public License

public void RPLiquidacionIndividual(HttpServletResponse response, ResultSet rsRolPago, DataBase objDB,
        Sucursal objSucursal) {//from  www.  j  a  v a2  s.  co m
    /* inicio PDF */
    Rectangle orientacion = (this.vertical) ? PageSize.A4 : PageSize.A4.rotate();
    Document document = new Document(orientacion);// paso 1
    document.setMargins(0, 0, 50, 80); /*Izquierda, derecha, tope, pie */
    try {
        PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream()); // paso 2
        writer.setPageEvent(new Reporte(this.vertical, this.logo, this.titulo, this.ruc, this.subtitulo,
                this.direccion, this.sucursal, this.rep_pie));

        document.open(); // paso 3

        /* todo el cuerpo del doc es el paso 4 */

        String id_sucursal = "";
        String dni = "";
        String id_empleado = "";
        String empleado = "";
        String periodo = "";
        String departamento = "";
        String rol = "";
        String dias_laborados = "";
        String num_horas_50 = "";
        String num_horas_100 = "";
        String sbu = "";
        String ing_total_50 = "";
        String ing_total_100 = "";
        String total_ingreso = "";
        String egr_iess = "";
        String total_egreso = "";
        String total_pagar = "";
        try {
            boolean ban = false;
            while (rsRolPago.next()) {
                if (ban) {
                    document.newPage();
                }
                ban = true;

                id_sucursal = (rsRolPago.getString("id_sucursal") != null) ? rsRolPago.getString("id_sucursal")
                        : "";
                dni = (rsRolPago.getString("dni") != null) ? rsRolPago.getString("dni") : "";
                id_empleado = (rsRolPago.getString("id_empleado") != null) ? rsRolPago.getString("id_empleado")
                        : "";
                empleado = (rsRolPago.getString("empleado") != null) ? rsRolPago.getString("empleado") : "";
                periodo = (rsRolPago.getString("periodo_sql") != null) ? rsRolPago.getString("periodo_sql")
                        : "";
                departamento = (rsRolPago.getString("departamento") != null)
                        ? Fecha.ISOaSQL(rsRolPago.getString("departamento"))
                        : "";
                rol = (rsRolPago.getString("rol") != null) ? rsRolPago.getString("rol") : "";
                dias_laborados = (rsRolPago.getString("dias_laborados") != null)
                        ? rsRolPago.getString("dias_laborados")
                        : "";
                num_horas_50 = (rsRolPago.getString("num_horas_50") != null)
                        ? rsRolPago.getString("num_horas_50")
                        : "";
                num_horas_100 = (rsRolPago.getString("num_horas_100") != null)
                        ? rsRolPago.getString("num_horas_100")
                        : "";
                sbu = (rsRolPago.getString("sbu") != null) ? rsRolPago.getString("sbu") : "";
                ing_total_50 = (rsRolPago.getString("ing_total_50") != null)
                        ? rsRolPago.getString("ing_total_50")
                        : "";
                ing_total_100 = (rsRolPago.getString("ing_total_100") != null)
                        ? rsRolPago.getString("ing_total_100")
                        : "";
                total_ingreso = (rsRolPago.getString("total_ingreso") != null)
                        ? rsRolPago.getString("total_ingreso")
                        : "";
                egr_iess = (rsRolPago.getString("egr_iess") != null) ? rsRolPago.getString("egr_iess") : "";
                total_egreso = (rsRolPago.getString("total_egreso") != null)
                        ? rsRolPago.getString("total_egreso")
                        : "";
                total_pagar = (rsRolPago.getString("total_pagar") != null) ? rsRolPago.getString("total_pagar")
                        : "";
                int anio = Fecha.datePart("anio", periodo);
                int mes = Fecha.datePart("mes", periodo);
                String fecha_ini = anio + "-" + mes + "-01";
                String fecha_fin = anio + "-" + mes + "-" + Fecha.getUltimoDiaMes(anio, mes);

                /* MAESTRO */
                PdfPTable tbl_maestro = new PdfPTable(3);

                tbl_maestro.addCell(Addons.setCeldaPDF(this.titulo, Font.TIMES_ROMAN, 10, Font.BOLD,
                        Element.ALIGN_CENTER, 0, 5, 3));

                tbl_maestro.addCell(Addons.setCeldaPDF("Rol de Pago: Liquidacin individual", Font.TIMES_ROMAN,
                        8, Font.NORMAL, Element.ALIGN_LEFT, 0, 3, 3));

                tbl_maestro.addCell(Addons.setCeldaPDF("Nombres: " + empleado, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0, 3, 2));
                tbl_maestro.addCell(Addons.setCeldaPDF("Perodo: " + periodo, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));

                tbl_maestro.addCell(Addons.setCeldaPDF("Sucursal: " + objSucursal.getNombre(id_sucursal),
                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_LEFT, 0));
                tbl_maestro.addCell(Addons.setCeldaPDF("Departamento: " + departamento, Font.TIMES_ROMAN, 8,
                        Font.NORMAL, Element.ALIGN_LEFT, 0));
                tbl_maestro.addCell(Addons.setCeldaPDF("Cargo: " + rol, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));

                tbl_maestro.addCell(Addons.setCeldaPDF("Tiempo laborado: " + dias_laborados, Font.TIMES_ROMAN,
                        8, Font.NORMAL, Element.ALIGN_LEFT, 0));
                tbl_maestro.addCell(Addons.setCeldaPDF("H.E. 50%: " + num_horas_50, Font.TIMES_ROMAN, 8,
                        Font.NORMAL, Element.ALIGN_LEFT, 0));
                tbl_maestro.addCell(Addons.setCeldaPDF("H.E. 100%: " + num_horas_100, Font.TIMES_ROMAN, 8,
                        Font.NORMAL, Element.ALIGN_LEFT, 0));

                tbl_maestro.addCell(
                        Addons.setCeldaPDF(" ", Font.TIMES_ROMAN, 6, Font.NORMAL, Element.ALIGN_LEFT, 0, 1, 3));
                document.add(tbl_maestro);

                /* DETALLE */

                /* ingresos  */
                PdfPTable tbl_ingresos = new PdfPTable(new float[] { 3, 1 });
                tbl_ingresos.addCell(Addons.setCeldaPDF("INGRESOS", Font.TIMES_ROMAN, 8, Font.BOLD,
                        Element.ALIGN_CENTER, 1));
                tbl_ingresos.addCell(
                        Addons.setCeldaPDF("VALOR", Font.TIMES_ROMAN, 8, Font.BOLD, Element.ALIGN_CENTER, 1));

                tbl_ingresos.addCell(Addons.setCeldaPDF("Sueldo bsico unificado", Font.TIMES_ROMAN, 8,
                        Font.NORMAL, Element.ALIGN_LEFT, 1));
                tbl_ingresos.addCell(Addons.setCeldaPDF("+" + sbu, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 1));

                tbl_ingresos.addCell(Addons.setCeldaPDF("Horas extras 50%", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 1));
                tbl_ingresos.addCell(Addons.setCeldaPDF("+" + ing_total_50, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 1));

                tbl_ingresos.addCell(Addons.setCeldaPDF("Horas extras 100%", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 1));
                tbl_ingresos.addCell(Addons.setCeldaPDF("+" + ing_total_100, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 1));
                try {
                    ResultSet rsIngresosEmpleado = objDB.consulta(
                            "SELECT * FROM vta_rol_pago_rubro_empleado where tipo=true and anulado=false and id_empleado="
                                    + id_empleado + " and periodo between '" + fecha_ini + "' and '" + fecha_fin
                                    + "';");
                    while (rsIngresosEmpleado.next()) {
                        tbl_ingresos
                                .addCell(Addons.setCeldaPDF(
                                        ((rsIngresosEmpleado.getString("rubro") != null)
                                                ? rsIngresosEmpleado.getString("rubro")
                                                : ""),
                                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_LEFT, 1));
                        tbl_ingresos
                                .addCell(Addons.setCeldaPDF(
                                        "+" + ((rsIngresosEmpleado.getString("valor") != null)
                                                ? rsIngresosEmpleado.getString("valor")
                                                : "0.00"),
                                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_RIGHT, 1));
                    }
                    rsIngresosEmpleado.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                /* egresos  */
                PdfPTable tbl_egresos = new PdfPTable(new float[] { 3, 1 });
                tbl_egresos.addCell(
                        Addons.setCeldaPDF("EGRESOS", Font.TIMES_ROMAN, 8, Font.BOLD, Element.ALIGN_CENTER, 1));
                tbl_egresos.addCell(
                        Addons.setCeldaPDF("VALOR", Font.TIMES_ROMAN, 8, Font.BOLD, Element.ALIGN_CENTER, 1));

                tbl_egresos.addCell(Addons.setCeldaPDF("Aporte IESS", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 1));
                tbl_egresos.addCell(Addons.setCeldaPDF("-" + egr_iess, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 1));
                try {
                    ResultSet rsIngresosEmpleado = objDB.consulta(
                            "SELECT * FROM vta_rol_pago_rubro_empleado where tipo=false and anulado=false and id_empleado="
                                    + id_empleado + " and periodo between '" + fecha_ini + "' and '" + fecha_fin
                                    + "';");
                    while (rsIngresosEmpleado.next()) {
                        tbl_egresos
                                .addCell(Addons.setCeldaPDF(
                                        ((rsIngresosEmpleado.getString("rubro") != null)
                                                ? rsIngresosEmpleado.getString("rubro")
                                                : ""),
                                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_LEFT, 1));
                        tbl_egresos
                                .addCell(Addons.setCeldaPDF(
                                        "-" + ((rsIngresosEmpleado.getString("valor") != null)
                                                ? rsIngresosEmpleado.getString("valor")
                                                : "0.00"),
                                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_RIGHT, 1));
                    }
                    rsIngresosEmpleado.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }

                PdfPTable tbl_totales = new PdfPTable(new float[] { 3, 1, 3, 1 });
                tbl_totales.addCell(Addons.setCeldaPDF("TOTAL INGRESOS", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));
                tbl_totales.addCell(Addons.setCeldaPDF("$ " + total_ingreso, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 0));
                tbl_totales.addCell(Addons.setCeldaPDF("TOTAL EGRESOS", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));
                tbl_totales.addCell(Addons.setCeldaPDF("$ " + total_egreso, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_RIGHT, 0));

                tbl_totales.addCell(Addons.setCeldaPDF("VALOR A RECIBIR:     $ " + total_pagar,
                        Font.TIMES_ROMAN, 8, Font.NORMAL, Element.ALIGN_LEFT, 0, 3, 4));

                PdfPTable tbl_det = new PdfPTable(2);
                tbl_det.addCell(Addons.setCeldaPDF(tbl_ingresos, Element.ALIGN_LEFT, 0));
                tbl_det.addCell(Addons.setCeldaPDF(tbl_egresos, Element.ALIGN_LEFT, 0));
                document.add(tbl_det);

                document.add(tbl_totales);

                document.add(new Paragraph(" "));
                document.add(new Paragraph(" "));

                PdfPTable tbl_firma = new PdfPTable(1);
                tbl_firma.addCell(Addons.setCeldaPDF("______________________", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));
                tbl_firma.addCell(Addons.setCeldaPDF("Recib conforme", Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));
                tbl_firma.addCell(Addons.setCeldaPDF("C.C.  " + dni, Font.TIMES_ROMAN, 8, Font.NORMAL,
                        Element.ALIGN_LEFT, 0));
                document.add(tbl_firma);
            }

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

    } catch (IllegalStateException ie) {
        ie.printStackTrace();
    } catch (DocumentException e) {
        e.printStackTrace();
    } catch (Exception e) {
        e.printStackTrace();
    }

    document.close(); // paso 5
    /* fin PDF */
}

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Write single file report.//from   w  ww .jav a2  s .  c o  m
 *
 * @param frameList the frame list
 * @param path the path
 * @param page the page
 * @return the runnable
 */
public Runnable writeSingleFileReport(final BeadFrameList frameList, final String path, int page) {
    return new Runnable() {
        public void run() {

            Document document = null;
            PdfWriter writer = null;

            if (FileUtils.folderExists(path))
                FileUtils.deleteFile(path);

            try {
                document = new Document();

                writer = PdfWriter.getInstance(document, new FileOutputStream(path));
                document.open();
            } catch (FileNotFoundException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (DocumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            if (writer == null || document == null)
                return;

            for (BeadFrame frame : frameList) {

                //System.out.println("profile : " + frame);
                fillReport(document, writer, frame, frame.getId());
                document.newPage();
                incrementCount();
            }
            document.close();
            writer.close();
        }
    };

}

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Export bead image list./*from  w  w  w  . j a  va2 s .  c o  m*/
 *
 * @param imageList the image list
 * @param path the path
 */
public void exportBeadImageList(BeadFrameList imageList, String path) {
    Document document = new Document();
    try {

        int i = 0;
        int max = imageList.size();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(path)));
        document.open();
        for (BeadFrame frame : imageList) {
            fillReport(document, writer, frame, frame.getId());

            setChanged();
            Integer progress = new Integer(100 * i++ / max);
            if (progress == 0)
                progress = 1;
            notifyObservers(new Message(this, "progress changed",
                    String.format("Generating bead PDF reports : %d/%d", i, max), progress));
            document.newPage();
        }

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

        sendFinishMessage("Done.");

    } catch (FileNotFoundException e) {

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

        e.printStackTrace();
        setChanged();
        notifyObservers(new Message("this", "error", "Error when generating PDF."));
    }
}

From source file:knop.psfj.exporter.PDFExporter.java

License:Open Source License

/**
 * Fill report./*from ww w .  j  av  a2s.c o m*/
 *
 * @param report the report
 * @param writer the writer
 * @param bead the bead
 * @param id the id
 */
public static void fillReport(Document report, PdfWriter writer, BeadFrame bead, int id) {

    Microscope microscope = bead.getSource().getMicroscope();
    ReportSections rs = new ReportSections();

    writer.setStrictImageSequence(true);

    try {
        /*
         * report.add(rs.bigTitle("Bead " + id));
         * report.add(rs.littleNote(microscope.date)); /*
         * report.add(rs.title("Profile view:")); ImagePlus img; try { img =
         * svg.getPanelView(pp.getImagePlus(), SideViewGenerator.MAX_METHOD,
         * true, true, 5, false, null, 0); } catch (NullPointerException e)
         * { e.printStackTrace(); return; } float zoom2scaleTo256pxMax =
         * 25600 / Math.max(img.getWidth(), img.getHeight());
         * report.add(rs.imagePlus(img, zoom2scaleTo256pxMax));
         * 
         * report.add(rs.title("Microscope infos:"));
         * report.add(rs.paragraph(microscope.getMicroscopeHeader()));
         */

        id = bead.getId();
        String suffix = "";
        if (bead.isValid() == false)
            suffix = " (Rejected)";

        if (bead.isValid() && bead.getInvalidityReason() != null) {
            suffix = " (Rejected from the pair analysis)";
        }

        // Image logo = loadImage("knoplablogo.png");

        // report.add();
        // currentDocument.add(rs.littleNote(FileUtils.getTodayDate()));

        double[] resolutions = bead.getResolutions();

        // the resolutions extracted from the Bead Spread function are
        // assigned to
        // individual variables
        String resolutionX = microscope.formatDouble(bead.getResolution(0));
        String resolutionY = microscope.formatDouble(bead.getResolution(1));
        String resolutionZ = microscope.formatDouble(bead.getResolution(2));

        // the corrected resolution are calculated by the Microscope Object
        // (it holds
        // all the experiment data).
        String correctedResolutionX = microscope.formatDouble(bead.getCorrectionResolution(Microscope.X));
        String correctedResolutionY = microscope.formatDouble(bead.getCorrectionResolution(Microscope.Y));
        String correctedResolutionZ = microscope.formatDouble(bead.getCorrectionResolution(Microscope.Z));

        String asymmetry = MathUtils.roundToString(bead.getAsymetry(), 3);

        String theta = MathUtils.roundToString(bead.getThetaInDegrees(), 1) + MathUtils.DEGREE_SYMBOL;

        String[][] content = { { "FWHM", "min", "max", "z", "Asymmetry", "Theta" },
                { "Non corrected", resolutionX, resolutionY, resolutionZ, asymmetry, theta },

                { "Corrected", correctedResolutionX, correctedResolutionY, correctedResolutionZ, "", ""

                },
                { "Theoretical", microscope.formatDouble(microscope.getXYTheoreticalResolution()),
                        microscope.formatDouble(microscope.getXYTheoreticalResolution()),
                        microscope.formatDouble(microscope.getZTheoreticalResolution()), "", "" } };

        Paragraph header = new Paragraph();

        Image sideView = rs.imagePlus(bead.getSideViewImage(), 100);
        sideView.setAlignment(Image.ALIGN_RIGHT | Image.TEXTWRAP);
        report.add(sideView);
        String microscopeId = bead.getSource().getMicroscope().getIdentifier();
        if (microscopeId.equals("") == false)
            microscopeId = String.format(" ( %s )", microscopeId);
        String date = "Date : " + FileUtils.getTodayDate();
        String origin = String.format("\n Origin : %s %s\n Frame size : %d pixels\n",
                bead.getSource().getImageName(), microscopeId, bead.getWidth());
        String shift;
        String correspondingBead = "\nCorresponding bead : " + ((bead.getAlterEgo() == null) ? "Not found"
                : "Number " + bead.getAlterEgo().getId() + " in "
                        + bead.getAlterEgo().getSource().getImageName());
        String coordinates = "\nCoordinates : " + microscope.formatDouble(bead.getFovX()) + " (x), "
                + microscope.formatDouble(bead.getFovY()) + " (y), "
                + microscope.formatDouble(bead.getCentroidZ() * microscope.getCalibration().pixelDepth)
                + " (z)";
        String rejectionReason = (bead.getInvalidityReason() == null ? ""
                : "\nReason of rejection : " + bead.getInvalidityReason());

        if (bead.getAlterEgo() != null) {
            shift = "\nShift : ";
            shift += microscope.formatDouble(bead.getDeltaX());
            shift += " x " + microscope.formatDouble(bead.getDeltaY());
            shift += " x " + microscope.formatDouble(bead.getDeltaZ());
        } else {
            shift = "";
        }

        report.add(rs.title("Bead " + id + suffix));
        report.add(rs.paragraph(date + origin + coordinates + correspondingBead + shift + rejectionReason));
        // report.add(rs.subtitle("Resolution table:"));

        report.add(rs.table(content, 100));

        int height = 130;

        ImagePlus xPlot;
        ImagePlus yPlot;

        if (bead instanceof BeadFrame2D) {
            BeadFrame2D bead2D = (BeadFrame2D) bead;
            xPlot = new ImagePlus("", bead2D.getOverlayWithTheoretical());
            yPlot = xPlot;
            report.add(rs.subtitle("XY profile & fitting parameters : "));
            report.add(rs.littleNote("(red : the orignal data, green : the fit, yellow : the two merged)",
                    Paragraph.ALIGN_LEFT));

        } else {
            xPlot = bead.getXplot().getImagePlus();
            yPlot = bead.getYplot().getImagePlus();
            report.add(rs.subtitle("X profile & fitting parameters:"));
        }

        Image image = rs.imagePlus(xPlot, height);
        image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
        report.add(image);
        report.add(rs.paragraph(bead.getXParams()));

        if (bead instanceof BeadFrame2D == false) {
            report.add(rs.subtitle("Y profile & fitting parameters:"));
            image = rs.imagePlus(yPlot, height);
            image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
            report.add(image);
            report.add(rs.paragraph(bead.getYParams()));
        }
        report.add(rs.subtitle("Z profile & fitting parameters:"));
        image = rs.imagePlus(bead.getZplot().getImagePlus(), height);
        image.setAlignment(Image.ALIGN_LEFT | Image.TEXTWRAP);
        report.add(image);
        report.add(rs.paragraph(bead.getZParams()));

        if (!microscope.sampleInfos.equals("") || !microscope.comments.equals(""))
            report.newPage();

        if (!microscope.sampleInfos.equals("")) {
            report.add(rs.title("Sample infos:"));
            report.add(rs.paragraph(microscope.sampleInfos));
        }

        if (!microscope.comments.equals("")) {
            report.add(rs.title("Comments:"));
            report.add(rs.paragraph(microscope.comments));
        }

        // logo.setAlignment(Image.ALIGN_RIGHT | Image.TEXTWRAP);
        // logo.scalePercent(10);

        // currentDocument.add(logo);

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

    System.gc();

}

From source file:managedbean.aas.reportController.java

public static void concatPDFs(List<InputStream> streamOfPDFFiles, OutputStream outputStream, boolean paginate) {

    Document document = new Document();
    try {//from  ww  w  . j  a v a2  s. com
        List<InputStream> pdfs = streamOfPDFFiles;
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        // Create Readers for the pdfs.
        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }
        // Create a writer for the outputstream            
        PdfWriter writer = PdfWriter.getInstance(document, outputStream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent(); // Holds the PDF
        // data

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

                // Code for pagination.
                if (paginate) {
                    cb.beginText();
                    cb.setFontAndSize(bf, 9);
                    cb.showTextAligned(PdfContentByte.ALIGN_CENTER,
                            "" + currentPageNumber + " of " + totalPages, 520, 5, 0);
                    cb.endText();
                }
            }
            pageOfCurrentReaderPDF = 0;
        }
        outputStream.flush();
        document.close();
        outputStream.close();
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        if (document.isOpen()) {
            document.close();
        }
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (IOException ioe) {
            ioe.printStackTrace();
        }
    }
}

From source file:mpv5.utils.export.Export.java

License:Open Source License

private static File mergeFiles(List<File> p) {

    Document document = new Document();
    try {//  w w  w  . j  ava2  s . co m
        List<InputStream> pdfs = new ArrayList<InputStream>();
        for (int i = 0; i < p.size(); i++) {
            File inputStream = p.get(i);
            pdfs.add(new FileInputStream(inputStream));
        }
        List<PdfReader> readers = new ArrayList<PdfReader>();
        int totalPages = 0;
        Iterator<InputStream> iteratorPDFs = pdfs.iterator();

        while (iteratorPDFs.hasNext()) {
            InputStream pdf = iteratorPDFs.next();
            PdfReader pdfReader = new PdfReader(pdf);
            readers.add(pdfReader);
            totalPages += pdfReader.getNumberOfPages();
        }

        File f = FileDirectoryHandler.getTempFile("pdf");
        FileOutputStream outputstream = new FileOutputStream(f);
        PdfWriter writer = PdfWriter.getInstance(document, outputstream);

        document.open();
        BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        PdfContentByte cb = writer.getDirectContent();

        PdfImportedPage page;
        int currentPageNumber = 0;
        int pageOfCurrentReaderPDF = 0;
        Iterator<PdfReader> iteratorPDFReader = readers.iterator();

        // Loop through the PDF files and add to the output.
        while (iteratorPDFReader.hasNext()) {
            PdfReader pdfReader = iteratorPDFReader.next();

            // Create a new page in the target for each source page.
            while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) {
                document.newPage();
                pageOfCurrentReaderPDF++;
                currentPageNumber++;
                page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF);
                cb.addTemplate(page, 0, 0);

            }
            pageOfCurrentReaderPDF = 0;
        }
        outputstream.flush();
        document.close();
        outputstream.close();

        return f;
    } catch (Exception e) {
        Log.Debug(e);
    } finally {
        if (document.isOpen()) {
            document.close();
        }
    }

    return null;
}

From source file:mx.dr.util.report.impl.PdfService.java

License:Open Source License

/**
 * @see mx.dr.util.report.IPdfService#doMultiReport(List, OutputStream)
*//*from  w  ww.j  a  v a2s  .  c o m*/
public void doMultiReport(List<Object> lista, OutputStream out) throws Exception {
    DRPdfDocument anonDoc = null;
    for (Object o : lista) {
        anonDoc = o.getClass().getAnnotation(DRPdfDocument.class);
        break;
    }
    Document doc = null;
    if (anonDoc != null) {
        doc = new Document(new Rectangle(anonDoc.height(), anonDoc.width()), 0, 0, 0, 0);
    } else {
        doc = new Document(PageSize.LETTER, 0, 0, 0, 0);
    }
    PdfWriter.getInstance(doc, out);
    doc.open();
    Object dto;
    for (int i = 0; i < lista.size(); i++) {
        dto = lista.get(i);
        if (i > 0) {
            doc.newPage();
        }
        estampaEtiqueta(doc, dto, null, null);
    }

    doc.close();
}

From source file:net.filterlogic.util.imaging.ToPDF.java

License:Apache License

public static void FromTIFF(String[] files, String pdfOutFile) throws OpenCaptureImagingException {
    String tiff_file;/*from  w  w  w . ja va  2  s. c o m*/
    String pdf_file = pdfOutFile;

    try {

        Document document = new Document();

        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file));
        writer.setFullCompression();
        int pages = 0;
        document.open();
        PdfContentByte cb = writer.getDirectContent();
        RandomAccessFileOrArray ra = null;

        for (int i = 0; i < files.length; i++) {
            int comps = 0;
            tiff_file = files[i];

            try {
                ra = new RandomAccessFileOrArray(tiff_file);
                comps = TiffImage.getNumberOfPages(ra);
            } catch (Throwable e) {
                throw new Exception("Exception in " + tiff_file + " " + e.toString());
                //continue;
            }

            //System.out.println("Processing: " + tiff_file);

            for (int c = 0; c < comps; ++c) {
                try {
                    Image img = TiffImage.getTiffImage(ra, c + 1);
                    if (img != null) {
                        //System.out.println("page " + (c + 1));

                        img.scaleToFit(675, 775);
                        img.setAbsolutePosition(0, 50);
                        //                            document.add(new Paragraph(tiff_file + " - page " + (c + 1)));

                        cb.addImage(img);
                        document.newPage();
                        ++pages;
                    }
                } catch (Throwable e) {
                    throw new Exception("Exception " + tiff_file + " page " + (c + 1) + " " + e.getMessage());
                }
            }

            ra.close();
        }

        // close pdf
        document.close();

    } catch (Exception e) {
        throw new OpenCaptureImagingException("ToPDF exception: " + e.toString());
    }

}

From source file:net.laubenberger.bogatyr.helper.HelperPdf.java

License:Open Source License

/**
 * Writes a PDF from multiple image files to a {@link File}.
 * /*from   ww w  . ja va2 s. c  o  m*/
 * @param pageSize
 *           of the PDF
 * @param scale
 *           images to fit the page size
 * @param file
 *           output as PDF
 * @param files
 *           for the PDF
 * @throws DocumentException
 * @throws IOException
 * @see File
 * @see Rectangle
 * @since 0.9.2
 */
public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file,
        final File... files) throws DocumentException, IOException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(pageSize, scale, file, files));
    if (null == pageSize) {
        throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$
    }
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }
    if (null == files) {
        throw new RuntimeExceptionIsNull("files"); //$NON-NLS-1$
    }
    if (!HelperArray.isValid(files)) {
        throw new RuntimeExceptionIsEmpty("files"); //$NON-NLS-1$
    }

    final Document document = new Document(pageSize);
    document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);
    final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));

    try {
        PdfWriter.getInstance(document, fos);
        document.open();

        for (final File inputFile : files) {
            if (null == inputFile) {
                throw new RuntimeExceptionIsNull("inputFile"); //$NON-NLS-1$
            }
            final Image image = Image.getInstance(inputFile.getAbsolutePath());

            if (scale) {
                image.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
            }
            document.add(image);
            document.newPage();
        }
    } finally {
        document.close();
        fos.close();
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}

From source file:net.laubenberger.bogatyr.helper.HelperPdf.java

License:Open Source License

/**
 * Writes a PDF from multiple {@link java.awt.Image} to a {@link File}.
 * //from w w  w . j  a va  2  s.  c  o m
 * @param pageSize
 *           of the PDF
 * @param scale
 *           images to fit the page size
 * @param file
 *           output as PDF
 * @param images
 *           for the PDF
 * @throws DocumentException
 * @throws IOException
 * @see File
 * @see java.awt.Image
 * @see Rectangle
 * @since 0.9.2
 */
public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file,
        final java.awt.Image... images) throws DocumentException, IOException { // $JUnit$
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodStart(pageSize, scale, file, images));
    if (null == pageSize) {
        throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$
    }
    if (null == file) {
        throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$
    }
    if (null == images) {
        throw new RuntimeExceptionIsNull("images"); //$NON-NLS-1$
    }
    if (!HelperArray.isValid(images)) {
        throw new RuntimeExceptionIsEmpty("images"); //$NON-NLS-1$
    }

    final Document document = new Document(pageSize);
    document.setMargins(0.0F, 0.0F, 0.0F, 0.0F);

    final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file));

    try {
        PdfWriter.getInstance(document, fos);
        document.open();

        for (final java.awt.Image tempImage : images) {
            if (null == tempImage) {
                throw new RuntimeExceptionIsNull("tempImage"); //$NON-NLS-1$
            }
            final Image image = Image.getInstance(tempImage, null);

            if (scale) {
                image.scaleToFit(pageSize.getWidth(), pageSize.getHeight());
            }
            document.add(image);
            document.newPage();
        }
    } finally {
        document.close();
        fos.close();
    }
    if (log.isDebugEnabled())
        log.debug(HelperLog.methodExit());
}