Example usage for com.itextpdf.text Document newPage

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

Introduction

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

Prototype


public boolean newPage() 

Source Link

Document

Signals that an new page has to be started.

Usage

From source file:ro.ldir.chartpackage.GarbagePackageBuilder.java

License:Open Source License

public void writePDF(OutputStream out)
        throws DocumentException, MalformedURLException, XPathExpressionException, IOException {
    BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, "Cp1250", BaseFont.NOT_EMBEDDED);
    final Font hfFont = new Font(bf, 8, Font.NORMAL, BaseColor.GRAY);

    Document document = new Document(PageSize.A4, 50, 50, 50, 50);
    PdfWriter writer = PdfWriter.getInstance(document, out);
    writer.setBoxSize("art", new Rectangle(36, 54, 559, 788));

    writer.setPageEvent(new PdfPageEventHelper() {
        private int page = 0;

        @Override//from  w w w. ja  v  a2s .c  om
        public void onEndPage(PdfWriter writer, Document arg1) {
            page++;
            Rectangle rect = writer.getBoxSize("art");
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("Pachet mormane - \u00a9 Let's Do It, Romania!", hfFont),
                    (rect.getLeft() + rect.getRight()) / 2, rect.getTop() + 18, 0);
            ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER,
                    new Phrase("- " + page + " -", hfFont), (rect.getLeft() + rect.getRight()) / 2,
                    rect.getBottom() - 18, 0);
        }
    });

    document.open();
    document.addAuthor("Let's Do It, Romania!");
    document.addTitle("Pachet mormane");
    document.addCreationDate();

    Font titleFont = new Font(bf, 24, Font.BOLD);
    Font noteFont = new Font(bf, 12, Font.NORMAL, BaseColor.RED);
    Font headerFont = new Font(bf, 12, Font.BOLD);
    Font normalFont = new Font(bf, 11);
    Font defFont = new Font(bf, 11, Font.BOLD);
    Paragraph par;
    int page = 0;

    for (Garbage garbage : garbages) {
        par = new Paragraph();
        par.setAlignment(Element.ALIGN_CENTER);
        par.add(new Chunk("Morman " + garbage.getGarbageId() + "\n", titleFont));
        par.add(new Chunk("Citi\u0163i cu aten\u0163ie!", noteFont));
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("1. Date generale\n", headerFont));
        par.add(new Chunk("Jude\u0163ul: ", defFont));
        par.add(new Chunk(garbage.getCounty().getName() + "\n", normalFont));
        par.add(new Chunk("Comuna: ", defFont));
        par.add(new Chunk(garbage.getTown().getName() + "\n", normalFont));
        if (garbage.getChartedArea() != null) {
            par.add(new Chunk("Zona cartare: ", defFont));
            par.add(new Chunk(garbage.getChartedArea().getName() + "\n", normalFont));
        }
        par.add(new Chunk("Pozi\u0163ie: ", defFont));
        par.add(new Chunk(garbage.getY() + ", " + garbage.getX() + "\n", normalFont));
        par.add(new Chunk("Descriere:\n", defFont));
        par.add(new Phrase(garbage.getDescription() + "\n", normalFont));
        par.add(new Chunk("Componen\u0163\u0103 gunoi:\n", defFont));
        List list = new List();
        list.add(new ListItem(
                new Chunk("Procent plastic: " + garbage.getPercentagePlastic() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent sticl\u0103: " + garbage.getPercentageGlass() + "%", normalFont)));
        list.add(new ListItem(new Chunk("Procent metale: " + garbage.getPercentageMetal() + "%", normalFont)));
        list.add(new ListItem(
                new Chunk("Procent nereciclabile: " + garbage.getPercentageWaste() + "%", normalFont)));
        par.add(list);
        document.add(par);

        par = new Paragraph();
        par.setSpacingBefore(20);
        par.add(new Chunk("2. Indica\u0163ii rutiere\n", headerFont));
        Image img = Image.getInstance(getImage(garbage));
        img.scaleToFit((float) (PageSize.A4.getWidth() * .75), (float) (PageSize.A4.getHeight() * .75));
        img.setAlignment(Element.ALIGN_CENTER);
        par.add(img);
        document.add(par);

        if (page < garbages.size() - 1)
            document.newPage();
        page++;
    }

    document.close();
}

From source file:ru.trett.cis.services.PDFBuilderImpl.java

License:Open Source License

@Override
public String createPDF() throws IOException, DocumentException, ApplicationException {
    try {/*from   w  w w  . j a  v a 2 s .com*/
        String templatePath = servletContext.getRealPath("WEB-INF/resources/template-settings.xml");
        Map<String, List<String>> data = TemplateParser.parse(new File(templatePath));
        String regularFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Regular.ttf");
        if (regularFontPath == null)
            throw new ApplicationException("Regular Font file was not found");
        BaseFont bfr = BaseFont.createFont(regularFontPath, BaseFont.IDENTITY_H, true);
        String boldFontPath = servletContext.getRealPath("WEB-INF/resources/fonts/OpenSans-Bold.ttf");
        if (boldFontPath == null)
            throw new ApplicationException("Bold Font file was not found");
        BaseFont bfb = BaseFont.createFont(boldFontPath, BaseFont.IDENTITY_H, true);
        regularFont = new Font(bfr);
        regularFont.setSize(10);
        boldFont = new Font(bfb);
        boldFont.setSize(10);

        File file = File.createTempFile("order", ".pdf");
        Document doc = new Document(PageSize.A4);
        Chunk glue = new Chunk(new VerticalPositionMark());
        PdfWriter.getInstance(doc, new FileOutputStream(file));
        doc.open();
        doc.newPage();

        //title
        Paragraph p = new Paragraph(data.get("header").get(0), boldFont);
        p.setAlignment(Element.ALIGN_CENTER);
        doc.add(p);
        doc.add(Chunk.NEWLINE);

        //body
        for (String text : data.get("text")) {
            p = new Paragraph(text, regularFont);
            doc.add(p);
        }

        //table
        doc.add(Chunk.NEWLINE);
        List<String> cols = data.get("cols");
        PdfPTable table = new PdfPTable(cols.size());
        table.setWidthPercentage(100);

        cols.forEach(x -> table.addCell(getCell(x, PdfPCell.ALIGN_CENTER, boldFont)));

        for (Asset asset : assets) {
            table.addCell(getCell(String.format("%s %s %s", asset.getDeviceModel().getDeviceType().getType(),
                    asset.getDeviceModel().getDeviceBrand().getBrand(), asset.getDeviceModel().getModel()),
                    PdfPCell.ALIGN_CENTER, regularFont));
            table.addCell(getCell(asset.getSerialNumber(), PdfPCell.ALIGN_CENTER, regularFont));
            table.addCell(getCell(asset.getInventoryNumber(), PdfPCell.ALIGN_CENTER, regularFont));
        }

        table.getRows();
        doc.add(table);
        doc.add(Chunk.NEWLINE);
        doc.add(Chunk.NEWLINE);

        //signers
        Phrase phrase = new Phrase(new Chunk(data.get("signers").get(0) + " ", regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(issuer.getFirstName() + " " + issuer.getLastName() + "  \\__________________",
                regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(data.get("signers").get(1) + " ", regularFont));
        phrase.add(Chunk.NEWLINE);
        phrase.add(new Chunk(employee.getFirstName() + " " + employee.getLastName() + "  \\__________________",
                regularFont));
        doc.add(phrase);

        //date
        doc.add(Chunk.NEWLINE);
        doc.add(Chunk.NEWLINE);
        p = new Paragraph(data.get("place").get(0), regularFont);
        p.add(new Chunk(glue));
        p.add(date.format(dateFormat));
        doc.add(p);
        doc.close();
        return file.getPath();
    } catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

From source file:ryerson.daspub.artifact.PublishQRTagSheetTask.java

License:Open Source License

/**
 * Write artifact tag sheet to a file./*from w  w  w .  j av a  2 s .c o m*/
 * @param Output
 * @throws DocumentException
 * @throws FileNotFoundException
 * @throws BadElementException
 * @throws MalformedURLException
 * @throws IOException 
 */
public void writeTagSheet() throws DocumentException, FileNotFoundException, BadElementException,
        MalformedURLException, IOException {
    // get list of input files
    File[] files = inputDir.listFiles(new QRCodeImageFileFilter());
    if (files != null && files.length > 0) {
        // create a new PDF document
        logger.log(Level.INFO, "Writing tag sheet \"{0}\"", outputFile.getAbsolutePath());
        Document document = new Document(PageSize.LETTER);
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outputFile));
        document.addTitle("Artifact QR Code Labels");
        document.open();
        // generate page layouts with barcodes
        if (files != null) {
            int itemcount = 0;
            int pagecount = 1;
            for (int i = 0; i < files.length; i++) {
                if (itemcount == 0) {
                    drawPageLabels(writer, pagecount);
                }
                Point p = layout.get(itemcount);
                drawTag(writer, files[i], p);
                itemcount++;
                if (itemcount > ITEMS_PER_PAGE - 1) {
                    itemcount = 0;
                    pagecount++;
                    document.newPage();
                }
            }
        }
        document.close();
    }
}

From source file:sandbox.columntext.DropTablePart.java

public void createPdf(String dest) throws IOException, DocumentException {
    Document document = new Document();
    PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest));
    document.open();/*from w  w w .ja  v  a2 s  .c  om*/
    Rectangle column = new Rectangle(36, 36, 559, 806);
    ColumnText ct = new ColumnText(writer.getDirectContent());
    ct.setSimpleColumn(column);
    for (int i = 0; i < 4;) {
        PdfPTable table = new PdfPTable(new float[] { 0.25f, 0.25f, 0.25f, 0.25f });
        table.setHorizontalAlignment(Element.ALIGN_LEFT);
        table.setWidthPercentage(100);
        PdfPCell cell = new PdfPCell(new Phrase("inner table " + (++i)));
        cell.setColspan(4);
        table.addCell(cell);
        for (int j = 0; j < 18; j++) {
            table.addCell(new Phrase("test Data " + (j + 1) + ".1"));
            table.addCell(new Phrase("test Data " + (j + 1) + ".1"));
            table.addCell(new Phrase("test Data " + (j + 1) + ".1"));
            table.addCell(new Phrase("test Data " + (j + 1) + ".1"));
        }
        ct.addElement(table);
        if (ColumnText.hasMoreText(ct.go())) {
            document.newPage();
            ct = new ColumnText(writer.getDirectContent());
            ct.setSimpleColumn(column);
        }
    }
    document.close();
}

From source file:se.billes.pdf.renderer.process.NewPageRenderer.java

License:Open Source License

public void render(PdfWriter writer, Document document) throws PdfRenderException {
    writer.setPageEvent(page);/*from w w  w.  java2s  .  c o m*/
    if (page.getBlocks() == null || page.getBlocks().length == 0) {
        writer.setPageEmpty(false);
        writer.newPage();
    } else {
        document.newPage();
        PdfContentByte cb = writer.getDirectContent();
        for (BaseElement block : page.getBlocks()) {
            block.onRender(cb);
        }
    }
}

From source file:se.billes.pdf.renderer.process.TemplatePageRenderer.java

License:Open Source License

public void render(PdfWriter writer, Document document) throws PdfRenderException {
    writer.setPageEvent(page);/*from   ww w  . j a  v  a  2  s. c o m*/
    Template template = page.getTemplate();

    try {
        PdfReader reader = new PdfReader(template.getTemplatePath());
        PdfImportedPage pageImportedPage = writer.getImportedPage(reader, template.getPage());
        Image pdfMirror;

        float width = SizeFactory.CUT_MARK;
        float height = SizeFactory.CUT_MARK;

        pdfMirror = Image.getInstance(pageImportedPage);
        pdfMirror.setAbsolutePosition(SizeFactory.millimetersToPostscriptPoints(width),
                SizeFactory.millimetersToPostscriptPoints(height));
        document.newPage();
        ImageFactory.getInstances().add(new ImageInstance(pdfMirror, reader));
        PdfContentByte cb = writer.getDirectContent();
        try {
            cb.addImage(pdfMirror);
        } catch (DocumentException e) {
            e.printStackTrace();
        }
        if (page.getBlocks() != null) {
            for (BaseElement block : page.getBlocks()) {
                block.onRender(cb);
            }
        }

    } catch (BadElementException e) {
        e.printStackTrace();
        throw new PdfRenderException(e);
    } catch (IOException e) {
        throw new PdfRenderException(e);
    }

}

From source file:se.inera.intyg.rehabstod.service.export.pdf.PdfExportServiceImpl.java

License:Open Source License

@Override
public byte[] export(List<SjukfallEnhet> sjukfallList, PrintSjukfallRequest printSjukfallRequest,
        RehabstodUser user, int total) {

    ByteArrayOutputStream bos = new ByteArrayOutputStream();

    try {//from w  w w  .ja v a 2s . c o  m
        unicodeCapableFont = new Font(
                BaseFont.createFont(UNICODE_CAPABLE_FONT_PATH, BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 9,
                Font.NORMAL);

        Document document = new Document();
        document.setPageSize(PageSize.A4);
        document.setMargins(20, 20, 60, 20);

        PdfWriter writer = PdfWriter.getInstance(document, bos);
        // Add handlers for page events

        writer.setPageEvent(new HeaderEventHandler(
                Image.getInstance(
                        IOUtils.toByteArray(resourcePatternResolver.getResource(LOGO_PATH).getInputStream())),
                user.getNamn(), user.getValdVardenhet().getNamn()));
        writer.setPageEvent(new PageNumberingEventHandler());

        document.open();

        // Add the front page with meta info
        document.add(createFrontPage(printSjukfallRequest, user, sjukfallList.size(), total));

        // Switch to landscape mode
        document.setPageSize(PageSize.A4.rotate());
        document.newPage();

        // Add table with all sjukfall (could span several pages)
        document.add(createSjukfallTable(sjukfallList, user.getUrval(), printSjukfallRequest.isShowPatientId(),
                isSrsFeatureActive(user)));

        // Finish off by closing the document (will invoke the event handlers)
        document.close();

    } catch (DocumentException | IOException | RuntimeException e) {
        throw new PdfExportServiceException("Failed to create PDF export!", e);
    }

    return bos.toByteArray();
}

From source file:servlet.AdministrarRestriccion.java

public void genDocTren(HttpServletRequest request, HttpServletResponse response) throws Exception {

    int linea = Integer.parseInt(request.getParameter("idLinea"));
    //PrintWriter salida = response.getWriter();
    HttpSession session = request.getSession();
    // PrintWriter out = response.getWriter();
    Usuario usr = (Usuario) session.getAttribute("usuario");
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try {/*w  w  w  .ja  v a2  s  .co m*/

        String nota = new String(request.getParameter("nota").getBytes(), "UTF-8");
        String nota2 = new String(request.getParameter("nota2").getBytes(), "UTF-8");
        MaterialRodanteJpaController mrjc = new MaterialRodanteJpaController(Conex.getEmf());
        MaterialRodante mr = mrjc
                .findMaterialRodante(Integer.parseInt(request.getParameter("materialRodante")));
        String comunicaciones = new String(request.getParameter("comunicaciones").getBytes(), "UTF-8");
        String instrucciones = new String(request.getParameter("instrucciones").getBytes(), "UTF-8");
        String precauciones = new String(request.getParameter("precauciones").getBytes(), "UTF-8");
        String nombre = new String(request.getParameter("nombre").getBytes(), "UTF-8");
        String vigencia = request.getParameter("vigencia");

        String[] fecha = vigencia.split("-");

        LineaJpaController ljc = new LineaJpaController(Conex.getEmf());
        Linea l = ljc.findLinea(linea);

        Document documento = new Document(PageSize.A4);
        com.itextpdf.text.Font arialNegrita = FontFactory.getFont("arial", 9, Font.BOLD);
        com.itextpdf.text.Font arial = FontFactory.getFont("arial", 9, Font.PLAIN);
        com.itextpdf.text.Font saltoDeLinea = FontFactory.getFont("arial", 5, Font.BOLD);
        Paragraph parrafo = new Paragraph();
        int numResAs = 0;
        int numResDes = 0;
        RestriccionJpaController rjc = new RestriccionJpaController(Conex.getEmf());
        List<Restriccion> restDes = rjc.buscarIdLineaDescendenteDocTren(linea, l.getVelocidadLinea());
        List<Restriccion> restAsc = rjc.buscarIdLineaAscendenteDocTren(linea, l.getVelocidadLinea());
        int restAscTotal = restAsc.size() - 1;
        int restDescTotal = restDes.size() - 1;
        System.out.println(restAscTotal);
        System.out.println(restDescTotal);
        PdfWriter.getInstance(documento, baos);
        documento.open();

        do {

            try {
                URL url = getClass().getResource("/img/cintillo_s1.png");
                Image foto = Image.getInstance(url);
                foto.scaleToFit(500, 70);
                foto.setAlignment(Chunk.ALIGN_MIDDLE);
                documento.add(foto);
            } catch (Exception e) {
                e.printStackTrace();
            }
            documento.add(new Paragraph("DOCUMENTO DE TREN: " + nombre, arialNegrita));

            documento.add(new Paragraph(
                    "L?NEA: " + l.getNombreLinea() + " : Documento Vlido Para Todos Los Trenes",
                    arialNegrita));
            documento.add(new Paragraph(" ", saltoDeLinea));

            PdfPTable tabla = new PdfPTable(1);

            tabla.setHorizontalAlignment(10);
            tabla.setWidthPercentage(100f);
            tabla.addCell(new Paragraph("Operaciones Del Tren: circular a una velocidad no mayor de "
                    + l.getVelocidadLinea() + " Km/h", arial));
            tabla.addCell(new Paragraph("Nota: " + nota, arial));
            //tabla.getDefaultCell().setBorder(2);
            if (numResAs < restAscTotal) {
                tabla.getDefaultCell().setBorderWidthBottom(0);
                tabla.addCell(new Paragraph("Restricciones Ascendentes ", arialNegrita));
            }

            tabla.getDefaultCell().setBorderColorBottom(BaseColor.WHITE);

            int c = 0;
            for (int i = numResAs; i <= restAscTotal; i++) {
                if (c > 30) {
                    break;
                }
                //  System.out.println("imrimiento asc: "+numResAs);

                int pkI = (int) (restAsc.get(numResAs).getProgInicio() / 1000);
                int pkI1 = (int) (((restAsc.get(numResAs).getProgInicio() / 1000) - pkI) * 1000);
                int pkF = (int) (restAsc.get(numResAs).getProgFinal() / 1000);
                int pkF1 = (int) (((restAsc.get(numResAs).getProgFinal() / 1000) - pkF) * 1000);

                tabla.getDefaultCell().setBorder(14);
                tabla.getDefaultCell().setBorderWidthBottom(0);
                tabla.getDefaultCell().setBorderWidthTop(0);
                tabla.addCell(new Paragraph("*PK " + pkI + "+" + pkI1 + " al " + pkF + "+" + pkF1
                        + " circular a una velocidad no mayor de "
                        + restAsc.get(numResAs).getVelocidadMaxAscendente() + " "
                        + restAsc.get(numResAs).getObservacion(), arial));
                numResAs++;

                c++;
            }

            if (c < 30) {
                tabla.getDefaultCell().setBorderWidthBottom(1);
                tabla.getDefaultCell().setBorderWidthTop(1);
                tabla.getDefaultCell().setBorder(14);

                tabla.addCell(new Paragraph("Restricciones Descendentes ", arialNegrita));

            }
            int d = c;
            if (c < 30) {

                for (int i = numResDes; i <= restDescTotal; i++) {
                    if (d > 30) {
                        break;
                    }

                    tabla.getDefaultCell().setBorder(14);
                    tabla.getDefaultCell().setBorderWidthBottom(0);
                    tabla.getDefaultCell().setBorderWidthTop(0);

                    int pkI = (int) (restDes.get(numResDes).getProgFinal() / 1000);
                    int pkI1 = (int) (((restDes.get(numResDes).getProgFinal() / 1000) - pkI) * 1000);
                    int pkF = (int) (restDes.get(numResDes).getProgInicio() / 1000);
                    int pkF1 = (int) (((restDes.get(numResDes).getProgInicio() / 1000) - pkF) * 1000);

                    tabla.addCell(new Paragraph("*PK " + pkI + "+" + pkI1 + " al " + pkF + "+" + pkF1
                            + " circular a una velocidad no mayor de "
                            + restDes.get(numResDes).getVelocidadMaxDescendente() + " "
                            + restDes.get(numResDes).getObservacion(), arial));
                    numResDes++;
                    d++;

                }
            }

            int espacios = d;
            while (espacios < 30) {
                tabla.getDefaultCell().setBorderWidthBottom(0);
                tabla.getDefaultCell().setBorderWidthTop(0);
                tabla.addCell(new Paragraph(" ", arial));
                espacios++;

            }
            tabla.getDefaultCell().setBorder(15);
            tabla.getDefaultCell().setBorderWidthBottom(1);
            tabla.getDefaultCell().setBorderWidthTop(1);
            tabla.getDefaultCell().setMinimumHeight(50f);
            tabla.addCell(new Paragraph("Instrucciones: " + instrucciones, arial));
            tabla.addCell(new Paragraph("Comunicaciones: " + comunicaciones, arial));
            tabla.addCell(new Paragraph("Precauciones: " + precauciones, arial));
            tabla.getDefaultCell().setMinimumHeight(10f);
            tabla.addCell(new Paragraph("Vigencia A Partir De: " + fecha[0] + "/" + fecha[1] + "/" + fecha[2],
                    arial));
            tabla.getDefaultCell().setBorder(1);
            Paragraph preface = new Paragraph(Paragraph.ALIGN_CENTER,
                    "Realizado Por: " + usr.toString() + " - Gerencia de Gestin de Trfico", arialNegrita);
            preface.setAlignment(Element.ALIGN_CENTER);
            tabla.addCell(preface);
            tabla.getDefaultCell().setBorder(0);
            tabla.getDefaultCell().setVerticalAlignment(Element.ALIGN_CENTER);
            preface = new Paragraph(Paragraph.ALIGN_CENTER,
                    "EL NO CUMPLIR CON LAS LIMITACIONES PRESCRITAS EN ESTE"
                            + " DOCUMENTO VA EN CONTRA DE LA SEGURIDAD EN LA CIRCULACIN, POR LO TANTO SER?  MOTIVO DE SANCIN",
                    FontFactory.getFont("arial", 8f));
            tabla.addCell(preface);
            preface = new Paragraph(Paragraph.ALIGN_CENTER,
                    "Nota: Informacin sustentada con el informe tcnico "
                            + "de limitaciones de velocidad, emitido por el CCF (Centro de Control de Fallas)",
                    FontFactory.getFont("arial", 8f));
            tabla.addCell(preface);
            preface = new Paragraph(Paragraph.ALIGN_CENTER,
                    "Sentido Ascendente: Sentido en el cual aumenta la progresiva ej: 0+0 -> 41+000 -- Sentido Descendente: Sentido en el cual disminuye la progresiva ej: 41+000 -> 0+0 ",
                    FontFactory.getFont("arial", 6f));
            tabla.addCell(preface);
            preface = new Paragraph(Paragraph.ALIGN_CENTER,
                    "En la lnea Caracas-Cua el sentido ASCENDENTE corresponde a la V?A PAR y el DESCENDENTE a la V?A IMPAR",
                    FontFactory.getFont("arial", 6f));
            tabla.addCell(preface);

            documento.add(tabla);

            if (numResAs < restAscTotal || numResDes < restDescTotal) {
                documento.newPage();
            }
        } while (numResAs < restAscTotal || numResDes < restDescTotal);

        System.out.println("Termine");
        //CARACTER?STICAS DE MATERIAL RODANTE
        documento.newPage();

        try {
            URL url = getClass().getResource("/img/cintillo_s1.png");
            Image foto = Image.getInstance(url);
            foto.scaleToFit(500, 70);
            foto.setAlignment(Chunk.ALIGN_MIDDLE);
            documento.add(foto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        documento.add(new Paragraph("DOCUMENTO DE TREN: " + nombre, arialNegrita));

        documento.add(new Paragraph(
                "L?NEA: " + l.getNombreLinea() + " : Documento Vlido Para Todos Los Trenes", arialNegrita));
        documento.add(new Paragraph(" ", saltoDeLinea));

        documento.add(
                new Paragraph("CARACTER?STICAS DE LA UNIDAD: " + mr.getNombreMaterialRodante(), arialNegrita));
        documento.add(new Paragraph(" ", saltoDeLinea));

        PdfPTable tablaMT = new PdfPTable(2);
        tablaMT.addCell(new Paragraph("ITEM", arialNegrita));
        tablaMT.addCell(new Paragraph("DESCRIPCIN", arialNegrita));
        tablaMT.addCell(new Paragraph("Nmero de Unidades Remolque", arial));
        tablaMT.addCell(new Paragraph(mr.getNumeroRemolque() + " Unidades", arial));
        tablaMT.addCell(new Paragraph("Nmero de Unidades Motriz", arial));
        tablaMT.addCell(new Paragraph(mr.getNumeroMotriz() + " Unidades", arial));
        tablaMT.addCell(new Paragraph("Longitud Total", arial));
        tablaMT.addCell(new Paragraph(mr.getLongitudTotal() + " m", arial));
        tablaMT.addCell(new Paragraph("Longitud Coche Remolque", arial));
        tablaMT.addCell(new Paragraph(mr.getLongitudRemolque() + " m", arial));
        tablaMT.addCell(new Paragraph("Longitud Coche Motriz", arial));
        tablaMT.addCell(new Paragraph(mr.getLongitudMotriz() + " m", arial));
        tablaMT.addCell(new Paragraph("Alto x Ancho Coche Motriz", arial));
        tablaMT.addCell(new Paragraph(mr.getAltoXAnchoMotriz() + " m", arial));
        tablaMT.addCell(new Paragraph("Alto x Ancho Coche Remolque", arial));
        tablaMT.addCell(new Paragraph(mr.getAltoXAnchoRemolque() + " m", arial));
        tablaMT.addCell(new Paragraph("Masa o Tara Total", arial));
        tablaMT.addCell(new Paragraph(mr.getMasa() + " t", arial));
        tablaMT.addCell(new Paragraph("Masa Coche Remolque", arial));
        tablaMT.addCell(new Paragraph(mr.getMasaRemolque() + " t", arial));
        tablaMT.addCell(new Paragraph("Masa Coche Motriz", arial));
        tablaMT.addCell(new Paragraph(mr.getMasaMotriz() + " t", arial));
        tablaMT.addCell(new Paragraph("Frenado", arial));
        tablaMT.addCell(new Paragraph(mr.getFrenadoDescripcion() + "", arial));
        tablaMT.addCell(new Paragraph("Trocha", arial));
        tablaMT.addCell(new Paragraph(l.getTrocha() + " m", arial));
        tablaMT.addCell(new Paragraph("Velocidad Comercial", arial));
        tablaMT.addCell(new Paragraph(mr.getVelocidadOperativa() + " Km/h", arial));
        tablaMT.addCell(new Paragraph("Aceleracin Mx.", arial));
        tablaMT.addCell(new Paragraph(mr.getAceleracionMax() + " m/s^2", arial));
        tablaMT.addCell(new Paragraph("Desaceleracin de Servicio", arial));
        tablaMT.addCell(new Paragraph(mr.getDesaceleracionMax() + " m/s^2", arial));
        tablaMT.addCell(new Paragraph("Desaceleracion de Emergencia", arial));
        tablaMT.addCell(new Paragraph(mr.getDesaceleracionEmergencia() + " m/s^2", arial));
        tablaMT.addCell(new Paragraph("Voltaje", arial));
        tablaMT.addCell(new Paragraph(mr.getVoltaje() + " V", arial));
        tablaMT.addCell(new Paragraph("Voltaje de Bateras", arial));
        tablaMT.addCell(new Paragraph(mr.getVoltajeBateria() + " V", arial));
        tablaMT.addCell(new Paragraph("Presin de Trabajo", arial));
        tablaMT.addCell(new Paragraph(mr.getPresionTrabajo() + "", arial));
        if (mr.getSubTipo().equals("Tren de Viajeros")) {
            tablaMT.addCell(new Paragraph("Capacidad Coche Remolque", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadRemolque() + " pasajeros", arial));
            tablaMT.addCell(new Paragraph("Capacidad Coche Motriz", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadMotriz() + " pasajeros", arial));
            tablaMT.addCell(new Paragraph("Capacidad Total", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadPasajeros() + " pasajeros", arial));
        } else {
            tablaMT.addCell(new Paragraph("Capacidad Coche Remolque", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadRemolque() + " t", arial));
            tablaMT.addCell(new Paragraph("Capacidad Coche Motriz", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadMotriz() + " t", arial));
            tablaMT.addCell(new Paragraph("Capacidad Total", arial));
            tablaMT.addCell(new Paragraph(mr.getCapacidadPasajeros() + " t", arial));
        }
        documento.add(tablaMT);
        documento.add(new Paragraph(" ", saltoDeLinea));
        documento.add(new Paragraph(" ", saltoDeLinea));

        try {
            URL url = getClass().getResource("/img/" + request.getParameter("materialRodante") + ".jpg");
            Image foto = Image.getInstance(url);
            foto.scaleToFit(300, 300);
            foto.setAlignment(Chunk.ALIGN_MIDDLE);
            documento.add(foto);
        } catch (Exception e) {
            e.printStackTrace();
        }
        documento.add(new Paragraph(" ", saltoDeLinea));
        documento.add(new Paragraph(" ", saltoDeLinea));
        PdfPTable t = new PdfPTable(1);
        t.setWidthPercentage(100f);
        t.addCell("Nota: " + nota2);
        documento.add(t);

        documento.add(new Paragraph(" ", saltoDeLinea));
        documento.add(new Paragraph(" ", saltoDeLinea));

        Paragraph preface = new Paragraph(Paragraph.ALIGN_CENTER, "Realizado Por: " + usr.toString(),
                arialNegrita);
        documento.add(preface);

        documento.close();

        response.addHeader("Content-Disposition", "attachment; filename=DocumentoDeTren.pdf");
        response.addHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");
        response.addHeader("Pragma", "public");
        response.setContentType("application/pdf");

        DataOutput output = new DataOutputStream(response.getOutputStream());

        byte[] bytes = baos.toByteArray();
        response.setContentLength(bytes.length);

        for (int i = 0; i < bytes.length; i++) {
            output.writeByte(bytes[i]);

        }

    } catch (Exception e) {
        e.printStackTrace();
        //            salida.print("http://localhost:8084/MODULO2.3/img/error.png");
    }

}

From source file:sipl.recursos.GenerarPDFGrafica.java

private void addTitlePage(Document document)
        throws DocumentException, MalformedURLException, BadElementException, IOException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);//from ww w  .j a v  a  2  s.  co m
    preface.add(new Paragraph(Titulo, catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(
            "Reporte generado por: " + user.getNombre() + " " + user.getApellido() + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Este documento es creado a peticin del autor", smallBold));

    addEmptyLine(preface, 6);
    Image img = Image.getInstance(direc + "img//logo_unab.jpg");
    img.scaleAbsolute(70, 100);
    img.setAlignment(Image.ALIGN_CENTER);
    Chunk c = new Chunk(img, 0, 0);
    preface.add(c);
    document.add(preface);
    document.newPage();
    Paragraph preface1 = new Paragraph();
    preface1.add(new Paragraph("Grfica", smallBold));
    addEmptyLine(preface1, 20);
    img = Image.getInstance(imgG);
    img.scaleAbsolute(400, 300);
    img.setAlignment(Image.ALIGN_CENTER);
    c = new Chunk(img, 0, 0);
    preface1.add(c);
    document.add(preface1);
    document.newPage();
}

From source file:sipl.recursos.GenerarPDFListar.java

private void addTitlePage(Document document)
        throws DocumentException, MalformedURLException, BadElementException, IOException {
    Paragraph preface = new Paragraph();
    addEmptyLine(preface, 1);//from w  w w  .j  ava  2s .  c  o m
    preface.add(new Paragraph(Titulo, catFont));
    addEmptyLine(preface, 1);
    preface.add(new Paragraph(
            "Reporte generado por: " + user.getNombre() + " " + user.getApellido() + ", " + new Date(), //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
            smallBold));
    addEmptyLine(preface, 3);
    preface.add(new Paragraph("Este documento es creado a peticin del autor", smallBold));
    addEmptyLine(preface, 6);
    Image img = Image.getInstance(direc + "img//logo_unab.jpg");
    img.scaleAbsolute(70, 100);
    img.setAlignment(Image.ALIGN_CENTER);
    Chunk c = new Chunk(img, 0, 0);
    preface.add(c);
    document.add(preface);
    document.newPage();
}