Example usage for com.itextpdf.text Rectangle Rectangle

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

Introduction

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

Prototype

public Rectangle(final float urx, final float ury) 

Source Link

Document

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

Usage

From source file:com.vectorprint.report.itext.style.stylers.DocumentSettings.java

License:Open Source License

@Override
public final <E> E style(E element, Object data) throws VectorPrintException {
    document.setPageSize(new Rectangle(getValue(WIDTH, Float.class), getValue(HEIGHT, Float.class)));
    document.setMargins(getValue(ReportConstants.MARGIN.margin_left.name(), Float.class),
            getValue(ReportConstants.MARGIN.margin_right.name(), Float.class),
            getValue(ReportConstants.MARGIN.margin_top.name(), Float.class),
            getValue(ReportConstants.MARGIN.margin_bottom.name(), Float.class));
    writer.setPdfVersion(PdfWriter.PDF_VERSION_1_5);
    writer.addViewerPreference(PdfName.NONFULLSCREENPAGEMODE, PdfName.USEOC);
    writer.addViewerPreference(PdfName.PRINT, PdfName.DUPLEX);
    document.addProducer();// ww w.  j av  a 2  s .c om
    document.addCreationDate();
    byte[] password = getValue(PASSWORD, byte[].class);
    byte[] userpassword = getValue(USER_PASSWORD, byte[].class);
    byte[] ownerpassword = getValue(OWNER_PASSWORD, byte[].class);
    if (userpassword == null) {
        userpassword = password;
    }
    if (ownerpassword == null) {
        ownerpassword = password;
    }
    int permissions = ((PermissionsParameter) getParameter(PERMISSIONS, PERMISSION[].class)).getPermission();
    ENCRYPTION encryption = getValue(ENCRYPTION_PARAM, ENCRYPTION.class);
    if (userpassword != null) {
        int enc = encryption != null ? encryption.encryption : PdfWriter.ENCRYPTION_AES_128;
        try {
            writer.setEncryption(userpassword, ownerpassword, permissions, enc);
            ArrayHelper.clear(password);
            ArrayHelper.clear(ownerpassword);
            ArrayHelper.clear(userpassword);
        } catch (DocumentException ex) {
            throw new VectorPrintException(ex);
        }
    } else if (getValue(CERTIFICATE, URL.class) != null) {
        int enc = encryption != null ? encryption.encryption : PdfWriter.ENCRYPTION_AES_128;
        try {
            writer.setEncryption(new Certificate[] { loadCertificate() }, new int[] { permissions }, enc);
        } catch (DocumentException ex) {
            throw new VectorPrintException(ex);
        }
    }

    for (PDFBOX b : PDFBOX.values()) {
        if (getValue(b.name(), float[].class) != null) {
            float[] size = getValue(b.name(), float[].class);
            writer.setBoxSize(b.name(), new Rectangle(size[0], size[1], size[2], size[3]));
        }
    }

    document.addSubject(getValue(SUBJECT, String.class));
    document.addAuthor(getValue(AUTHOR, String.class));
    document.addTitle(getValue(TITLE, String.class));
    document.addCreator(getValue(CREATOR, String.class));
    document.addKeywords(getValue(KEYWORDS, String.class));

    if (getValue(PDFA, Boolean.class)) {
        try {
            pdfA1A(writer);
        } catch (IOException | DocumentException ex) {
            throw new VectorPrintException(ex);
        }
    }
    writer.createXmpMetadata();

    return (E) document;
}

From source file:com.vectorprint.report.itext.style.stylers.ImportTiff.java

License:Open Source License

/**
 * applies settigns to the image and after this adds the image to the report based on
 * {@link #SEPARATE_PAGE}, {@link #FITTOIMAGE}, {@link #FITTOPAGE}, {@link #NOFOOTER} and {@link #DRAWDIRECT}.
 *
 * @param img/*from  ww  w .  ja  v a 2  s.  co  m*/
 * @throws VectorPrintException
 */
@Override
public final void processImage(com.itextpdf.text.Image img) throws VectorPrintException {
    applySettings(img);
    for (BaseStyler bs : stylers) {
        // these stylers are configured in the setup after this importing stylers, apply here
        if (bs.canStyle(img) && bs.shouldStyle(data, img)) {
            bs.style(img, data);
        }
    }

    if (getValue(SEPARATE_PAGE, Boolean.class)) {
        if (getValue(FITTOIMAGE, Boolean.class)) {
            getDocument().setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight()));
        } else if (getValue(FITTOPAGE, Boolean.class)) {
            img.scaleToFit(getDocument().getPageSize().getWidth(), getDocument().getPageSize().getHeight());
        }
        if (getValue(NOFOOTER, Boolean.class)) {
            getSettings().put(ReportConstants.PRINTFOOTER, "false");
        }
        getDocument().newPage();
    }
    if (getValue(DRAWDIRECT, Boolean.class)) {
        this.imageBeingProcessed = img;
        drawOnPage(imageBeingProcessed);
        this.imageBeingProcessed = null;
    } else {
        addToDocument(img);
    }
}

From source file:com.vectorprint.report.itext.style.stylers.Page.java

License:Open Source License

private void pageSettings() {
    if (getBackground() != null) {
        if (log.isLoggable(Level.FINE)) {
            log.fine("Possibly page background is written on top of page content making it invisible");
        }/*from  w  w w .j a va2 s  .  c  om*/
        PdfContentByte bg = getWriter().getDirectContentUnder();
        Rectangle rect = getWriter().getPageSize();
        rect.setBackgroundColor(itextHelper.fromColor(getBackground()));
        bg.rectangle(rect);
        bg.closePathFillStroke();
    }
    getDocument().setPageSize(new Rectangle(getWidth(), getHeight()));
    getDocument().setMargins(getMargin_left(), getMargin_right(), getMargin_top(), getMargin_bottom());
}

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

License:Open Source License

@Override
public void secondPass(InputStream firstPass, OutputStream orig) throws IOException {
    PdfReader reader = null;/* ww  w  .  j ava2  s .  com*/
    VectorPrintDocument vpd = (VectorPrintDocument) outer.getDocument();
    try {
        reader = new PdfReader(firstPass);
        prepareToc();
        // init fresh components for second pass styling
        StylerFactory _stylerFactory = outer.getStylerFactory().getClass().newInstance();
        StylerFactoryHelper.SETTINGS_ANNOTATION_PROCESSOR.initSettings(_stylerFactory, outer.getSettings());
        _stylerFactory.setLayerManager(outer.getElementProducer());
        _stylerFactory.setImageLoader(outer.getElementProducer());
        outer.getStyleHelper().setStylerFactory(_stylerFactory);
        EventHelper event = outer.getEventHelper().getClass().newInstance();
        event.setItextStylerFactory(_stylerFactory);
        event.setElementProvider(outer.getElementProducer());
        ((DefaultElementProducer) outer.getElementProducer()).setPh(event);
        Document d = new VectorPrintDocument(event, _stylerFactory, outer.getStyleHelper());
        PdfWriter w = PdfWriter.getInstance(d, orig);
        w.setPageEvent(event);
        outer.getStyleHelper().setVpd((VectorPrintDocument) d);
        _stylerFactory.setDocument(d, w);
        DocumentStyler ds = _stylerFactory.getDocumentStyler();
        outer.getStyleHelper().style(d, null, StyleHelper.toCollection(ds));
        d.open();
        ds.styleAfterOpen(d, null);
        List outline = SimpleBookmark.getBookmark(reader);
        if (!ds.getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
            if (outline != null) {
                int cur = w.getCurrentPageNumber();
                SimpleBookmark.shiftPageNumbers(outline, cur, null);
            }
            d.newPage();
        }
        outer.getSettings().put(ReportConstants.DEBUG, Boolean.FALSE.toString());
        for (int p = 1; p <= reader.getNumberOfPages(); p++) {
            Image page = Image.getInstance(w.getImportedPage(reader, p));
            page.setAbsolutePosition(0, 0);
            d.setPageSize(page);
            d.newPage();
            Chunk i = new Chunk(" ");
            if (vpd.getToc().containsKey(p)) {
                Section s = null;
                for (Map.Entry<Integer, List<Section>> e : vpd.getToc().entrySet()) {
                    if (e.getKey() == p) {
                        s = e.getValue().get(0);
                        break;
                    }
                }
                i.setLocalDestination(s.getTitle().getContent());
            }
            d.add(i);
            w.getDirectContent().addImage(page);
            w.freeReader(reader);
        }
        if (_stylerFactory.getDocumentStyler().getValue(DocumentSettings.TOCAPPEND, Boolean.class)) {
            printToc(d, w, vpd);
        }
        w.setOutlines(outline);
        if (outer.isWasDebug()) {
            event.setLastPage(outer.getWriter().getCurrentPageNumber());
            d.setPageSize(new Rectangle(ItextHelper.mmToPts(297), ItextHelper.mmToPts(210)));
            d.setMargins(5, 5, 5, 5);
            d.newPage();
            outer.getSettings().put(ReportConstants.DEBUG, Boolean.TRUE.toString());
            event.setDebugHereAfter(true);
            DebugHelper.appendDebugInfo(w, d, outer.getSettings(), _stylerFactory);
        }
        d.close();
    } catch (VectorPrintException | DocumentException | InstantiationException | IllegalAccessException ex) {
        throw new VectorPrintRuntimeException(ex);
    } finally {
        if (reader != null) {
            reader.close();
        }
    }
}

From source file:controller.CCInstance.java

License:Open Source License

public final boolean signPdf(final String pdfPath, final String destination, final CCSignatureSettings settings,
        final SignatureListener sl) throws CertificateException, IOException, DocumentException,
        KeyStoreException, SignatureFailedException, FileNotFoundException, NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {
    PrivateKey pk;/*from www . j  a  va2  s .  c o m*/

    final PdfReader reader = new PdfReader(pdfPath);
    pk = getPrivateKeyFromAlias(settings.getCcAlias().getAlias());

    if (getCertificationLevel(pdfPath) == PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED) {
        String message = Bundle.getBundle().getString("fileDoesNotAllowChanges");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new SignatureFailedException(message);
    }

    if (reader.getNumberOfPages() - 1 < settings.getPageNumber()) {
        settings.setPageNumber(reader.getNumberOfPages() - 1);
    }

    if (null == pk) {
        String message = Bundle.getBundle().getString("noSmartcardFound");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    if (null == pkcs11ks.getCertificateChain(settings.getCcAlias().getAlias())) {
        String message = Bundle.getBundle().getString("certificateNullChain");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }
    final ArrayList<Certificate> embeddedCertificateChain = settings.getCcAlias().getCertificateChain();
    final Certificate owner = embeddedCertificateChain.get(0);
    final Certificate lastCert = embeddedCertificateChain.get(embeddedCertificateChain.size() - 1);

    if (null == owner) {
        String message = Bundle.getBundle().getString("certificateNameUnknown");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new CertificateException(message);
    }

    final X509Certificate X509C = ((X509Certificate) lastCert);
    final Calendar now = Calendar.getInstance();
    final Certificate[] filledMissingCertsFromChainInTrustedKeystore = getCompleteTrustedCertificateChain(
            X509C);

    final Certificate[] fullCertificateChain;
    if (filledMissingCertsFromChainInTrustedKeystore.length < 2) {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()];
        for (int i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
    } else {
        fullCertificateChain = new Certificate[embeddedCertificateChain.size()
                + filledMissingCertsFromChainInTrustedKeystore.length - 1];
        int i = 0;
        for (i = 0; i < embeddedCertificateChain.size(); i++) {
            fullCertificateChain[i] = embeddedCertificateChain.get(i);
        }
        for (int f = 1; f < filledMissingCertsFromChainInTrustedKeystore.length; f++, i++) {
            fullCertificateChain[i] = filledMissingCertsFromChainInTrustedKeystore[f];
        }
    }

    // Leitor e Stamper
    FileOutputStream os = null;
    try {
        os = new FileOutputStream(destination);
    } catch (FileNotFoundException e) {
        String message = Bundle.getBundle().getString("outputFileError");
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, false, message);
        }
        throw new IOException(message);
    }

    // Aparncia da Assinatura
    final char pdfVersion;
    switch (Settings.getSettings().getPdfVersion()) {
    case "/1.2":
        pdfVersion = PdfWriter.VERSION_1_2;
        break;
    case "/1.3":
        pdfVersion = PdfWriter.VERSION_1_3;
        break;
    case "/1.4":
        pdfVersion = PdfWriter.VERSION_1_4;
        break;
    case "/1.5":
        pdfVersion = PdfWriter.VERSION_1_5;
        break;
    case "/1.6":
        pdfVersion = PdfWriter.VERSION_1_6;
        break;
    case "/1.7":
        pdfVersion = PdfWriter.VERSION_1_7;
        break;
    default:
        pdfVersion = PdfWriter.VERSION_1_7;
    }

    final PdfStamper stamper = (getNumberOfSignatures(pdfPath) == 0
            ? PdfStamper.createSignature(reader, os, pdfVersion)
            : PdfStamper.createSignature(reader, os, pdfVersion, null, true));

    final PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
    appearance.setSignDate(now);
    appearance.setReason(settings.getReason());
    appearance.setLocation(settings.getLocation());
    appearance.setCertificationLevel(settings.getCertificationLevel());
    appearance.setSignatureCreator(SIGNATURE_CREATOR);
    appearance.setCertificate(owner);

    final String fieldName = settings.getPrefix() + " " + (1 + getNumberOfSignatures(pdfPath));
    if (settings.isVisibleSignature()) {
        appearance.setVisibleSignature(settings.getPositionOnDocument(), settings.getPageNumber() + 1,
                fieldName);
        appearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
        if (null != settings.getAppearance().getImageLocation()) {
            appearance.setImage(Image.getInstance(settings.getAppearance().getImageLocation()));
        }

        com.itextpdf.text.Font font = new com.itextpdf.text.Font(FontFactory
                .getFont(settings.getAppearance().getFontLocation(), BaseFont.IDENTITY_H, BaseFont.EMBEDDED, 0)
                .getBaseFont());

        font.setColor(new BaseColor(settings.getAppearance().getFontColor().getRGB()));
        if (settings.getAppearance().isBold() && settings.getAppearance().isItalic()) {
            font.setStyle(Font.BOLD + Font.ITALIC);
        } else if (settings.getAppearance().isBold()) {
            font.setStyle(Font.BOLD);
        } else if (settings.getAppearance().isItalic()) {
            font.setStyle(Font.ITALIC);
        } else {
            font.setStyle(Font.PLAIN);
        }

        appearance.setLayer2Font(font);
        String text = "";
        if (settings.getAppearance().isShowName()) {
            if (!settings.getCcAlias().getName().isEmpty()) {
                text += settings.getCcAlias().getName() + "\n";
            }
        }
        if (settings.getAppearance().isShowReason()) {
            if (!settings.getReason().isEmpty()) {
                text += settings.getReason() + "\n";
            }
        }
        if (settings.getAppearance().isShowLocation()) {
            if (!settings.getLocation().isEmpty()) {
                text += settings.getLocation() + "\n";
            }
        }
        if (settings.getAppearance().isShowDate()) {
            DateFormat df = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
            SimpleDateFormat sdf = new SimpleDateFormat("Z");
            text += df.format(now.getTime()) + " " + sdf.format(now.getTime()) + "\n";
        }
        if (!settings.getText().isEmpty()) {
            text += settings.getText();
        }

        PdfTemplate layer2 = appearance.getLayer(2);
        Rectangle rect = settings.getPositionOnDocument();
        Rectangle sr = new Rectangle(rect.getWidth(), rect.getHeight());
        float size = ColumnText.fitText(font, text, sr, 1024, PdfWriter.RUN_DIRECTION_DEFAULT);
        ColumnText ct = new ColumnText(layer2);
        ct.setRunDirection(PdfWriter.RUN_DIRECTION_DEFAULT);
        ct.setAlignment(Element.ALIGN_MIDDLE);
        int align;
        switch (settings.getAppearance().getAlign()) {
        case 0:
            align = Element.ALIGN_LEFT;
            break;
        case 1:
            align = Element.ALIGN_CENTER;
            break;
        case 2:
            align = Element.ALIGN_RIGHT;
            break;
        default:
            align = Element.ALIGN_LEFT;
        }

        ct.setSimpleColumn(new Phrase(text, font), sr.getLeft(), sr.getBottom(), sr.getRight(), sr.getTop(),
                size, align);
        ct.go();
    } else {
        appearance.setVisibleSignature(new Rectangle(0, 0, 0, 0), 1, fieldName);
    }

    // CRL <- Pesado!
    final ArrayList<CrlClient> crlList = null;

    // OCSP
    OcspClient ocspClient = new OcspClientBouncyCastle();

    // TimeStamp
    TSAClient tsaClient = null;
    if (settings.isTimestamp()) {
        tsaClient = new TSAClientBouncyCastle(settings.getTimestampServer(), null, null);
    }

    final String hashAlg = getHashAlgorithm(X509C.getSigAlgName());

    final ExternalSignature es = new PrivateKeySignature(pk, hashAlg, pkcs11Provider.getName());
    final ExternalDigest digest = new ProviderDigest(pkcs11Provider.getName());

    try {
        MakeSignature.signDetached(appearance, digest, es, fullCertificateChain, crlList, ocspClient, tsaClient,
                0, MakeSignature.CryptoStandard.CMS);
        if (sl != null) {
            sl.onSignatureComplete(pdfPath, true, "");
        }
        return true;
    } catch (Exception e) {
        os.flush();
        os.close();
        new File(destination).delete();
        if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_FUNCTION_CANCELED".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("userCanceled"));
        } else if ("sun.security.pkcs11.wrapper.PKCS11Exception: CKR_GENERAL_ERROR".equals(e.getMessage())) {
            throw new SignatureFailedException(Bundle.getBundle().getString("noPermissions"));
        } else if (e instanceof ExceptionConverter) {
            String message = Bundle.getBundle().getString("timestampFailed");
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, message);
            }
            throw new SignatureFailedException(message);
        } else {
            if (sl != null) {
                sl.onSignatureComplete(pdfPath, false, Bundle.getBundle().getString("unknownErrorLog"));
            }
            controller.Logger.getLogger().addEntry(e);
        }
        return false;
    }
}

From source file:Controller.ControllerCompra.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods./* w ww  .  ja v  a2  s . c  om*/
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        //int estado = 0;
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String facturaProveedor = (request.getParameter("txtNumeroFactura"));
            String nombreProveedor = (request.getParameter("txtNombre"));
            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalCompra"));
            listObjDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listObjDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objCompra.setFacturaProveedor(facturaProveedor);
            _objCompra.setNombreProveedor(nombreProveedor);
            _objCompra.setTotalCompra(totalCompra);
            daoModelCompra = new ModelCompra();
            String salida = Mensaje(daoModelCompra.Add(_objCompra, _objUsuario, listObjDetalleMovimientos),
                    "La compra ha sido registrada", "Ha ocurrido un error");
            daoModelCompra.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableCompra());
            break;
        }
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iText">
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> compra = (Map) material.get("Compra");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra                        
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Nombre del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("nombreProveedor") + "\n"));
                headerDerecha.add(new Chunk("Factura del Proveedor: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("facturaProveedor") + "\n"));
                headerDerecha.add(new Chunk("Fecha Compra: ", helveticaBold));
                headerDerecha.add(new Chunk(compra.get("fechaCompra") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Compra", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(compra.get("totalCompra")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        //</editor-fold>
        //<editor-fold defaultstate="collapsed" desc="PDF mediante iReports">
        case "Imprimir2": {
            try {
                int id = Integer.parseInt(request.getParameter("id"));
                String source = url + "/reports/newReport1.jrxml";
                JasperPrint jasperPrint = null;
                JasperReport jasperReport = null;
                JasperDesign jasperDesign = null;
                System.out.println(source);
                String reportPath = request.getServletContext().getRealPath("reports") + "\\newReport1.jrxml";
                jasperDesign = JRXmlLoader.load(reportPath);
                jasperReport = JasperCompileManager.compileReport(jasperDesign);
                jasperPrint = JasperFillManager.fillReport(jasperReport, reporte(id),
                        daoModelCompra.getConnection());
                JasperExportManager.exportReportToPdfStream(jasperPrint, response.getOutputStream());
            } catch (Exception ex) {
                for (StackTraceElement ruta : ex.getStackTrace()) {
                    System.err.println(ruta);
                }
            }
        }
            break;
        //</editor-fold>

        }
    }

}

From source file:Controller.ControllerVenta.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w ww  . j a va  2 s  .co  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    if (request.getParameter("action") != null) {
        String url = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort()
                + request.getContextPath();
        String action = request.getParameter("action");
        switch (action) {
        case "Registrar": {
            String documentoUsuario = (request.getParameter("documentoUsuario"));
            String documentoCliente = null;
            String nombreCliente = null;
            int numeroVenta = 0;
            if (Validador.validarDocumento(request.getParameter("documentoCliente"))
                    & Validador.validarNombresCompletos(request.getParameter("txtNombreCliente"))
                    & Validador.validarNumero(request.getParameter("txtNumeroVenta"))) {
                documentoCliente = (request.getParameter("documentoCliente"));
                nombreCliente = (request.getParameter("txtNombreCliente"));
                numeroVenta = Integer.parseInt(request.getParameter("txtNumeroVenta"));
            } else {
                response.setContentType("application/json");
                response.setCharacterEncoding("UTF-8");
                response.getWriter().write(Mensaje(false, null, "Ha ingresado datos incorrectos"));
                break;
            }

            int lenght = Integer.parseInt(request.getParameter("size"));
            int totalCompra = Integer.parseInt(request.getParameter("txtTotalVenta"));
            listOjbDetalleMovimientos = new ArrayList<>();
            for (int i = 0; i < lenght; i++) {
                _objDetalleMovimiento = new ObjDetalleMovimiento();
                _objDetalleMovimiento
                        .setIdArticulo(Integer.parseInt(request.getParameter("lista[" + i + "][idArticulo]")));
                _objDetalleMovimiento
                        .setCantidad(Integer.parseInt(request.getParameter("lista[" + i + "][cantidad]")));
                _objDetalleMovimiento.setPrecioArticulo(
                        Integer.parseInt(request.getParameter("lista[" + i + "][precioArticulo]")));
                _objDetalleMovimiento.setTotalDetalleMovimiento(
                        _objDetalleMovimiento.getCantidad() * _objDetalleMovimiento.getPrecioArticulo());
                _objDetalleMovimiento.setDescuento(lenght);
                listOjbDetalleMovimientos.add(_objDetalleMovimiento);
            }
            _objUsuario.setDocumentoUsuario(documentoUsuario);
            _objVenta.setIdVenta(numeroVenta);
            _objVenta.setDocumentoCliente(documentoCliente);
            _objVenta.setNombreCliente(nombreCliente);
            _objVenta.setTotalVenta(totalCompra);
            daoModelVenta = new ModelVenta();
            String salida = Mensaje(daoModelVenta.Add(_objVenta, _objUsuario, listOjbDetalleMovimientos),
                    "La venta ha sido registrada", "Ha ocurrido un error");
            daoModelVenta.Signout();
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(salida);
            break;
        }
        case "Consultar": {
            int id = Integer.parseInt(request.getParameter("id"));
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(consultarDetalle(id));
            break;
        }
        case "Enlistar": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getTableVenta());
            break;
        }
        case "Contador": {
            response.setContentType("application/json");
            response.setCharacterEncoding("UTF-8");
            response.getWriter().write(getContador());
            break;
        }
        case "Imprimir": {
            response.setContentType("application/pdf");
            try {
                Locale loc = Locale.getDefault();
                NumberFormat currencyFormatter = NumberFormat.getCurrencyInstance(loc);
                //Primero obtengo el id del Movimiento
                int id = Integer.parseInt(request.getParameter("id"));
                //Obtengo el reporte a manera de Map
                Map material = reporte(id);
                //Topo ese reporte y lo divido, primero en la compra y luego el detalle
                Map<String, String> venta = (Map) material.get("Venta");
                List<Map> detalle = (List) material.get("Detalle");
                //Creo el documento y obtengo el canal de comunicacion con el servidor, para luego enviar el documento.
                Document document = new Document();
                OutputStream os = response.getOutputStream();
                //Creo una instancia a partir del documento y del canal
                PdfWriter.getInstance(document, os);
                //Abro el documento
                document.open();
                Image logo = Image.getInstance(url + "/public/images/logo.png");
                logo.scaleAbsolute(new Rectangle(logo.getPlainWidth() / 4, logo.getPlainHeight() / 4));
                document.add(logo);
                //Creo una fuente para la letra en negrilla
                final Font helveticaBold = new Font(Font.FontFamily.HELVETICA, 12, Font.BOLD);
                //Escribo y agrego un primer parrafo con los datos basicos de la compra         
                Paragraph headerDerecha = new Paragraph();
                headerDerecha.add(new Chunk("Id. de la Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("numeroVenta") + "\n"));
                headerDerecha.add(new Chunk("Nombre del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("nombreCliente") + "\n"));
                headerDerecha.add(new Chunk("Documento del Cliente: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("documentoCliente") + "\n"));
                headerDerecha.add(new Chunk("Fecha Venta: ", helveticaBold));
                headerDerecha.add(new Chunk(venta.get("fechaVenta") + "\n"));
                //Escribo y agrego un segundo parrafo con los datos basicos de Stelarte  
                Paragraph headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Stelarte.Decoracion \n", helveticaBold));
                headerIzquierda.add(new Chunk("Direccin: ", helveticaBold));
                headerIzquierda.add(new Chunk("Calle Falsa 123 # 12a34\n"));
                headerIzquierda.add(new Chunk("Telfono: ", helveticaBold));
                headerIzquierda.add(new Chunk("2583697 \n"));
                //Agrego los dos anteriores parrafos al Header
                PdfPTable header = new PdfPTable(2);
                header.getDefaultCell().setBorder(0);
                header.addCell(headerIzquierda);
                header.addCell(headerDerecha);
                header.setWidthPercentage(100f);
                header.setSpacingAfter(20);
                document.add(header);
                //Creo la tabla del detalle
                PdfPTable tablaDetalle = new PdfPTable(new float[] { 1, 3, 2, 2 });
                tablaDetalle.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER);
                //Creo el titulo, le quito el borde, le digo que ocupara cuatro columnas y que ser centrado
                PdfPCell tituloCell = new PdfPCell(new Phrase("Detalle de Venta", helveticaBold));
                tituloCell.setBorder(0);
                tituloCell.setColspan(4);
                tituloCell.setHorizontalAlignment(Element.ALIGN_CENTER);
                tablaDetalle.addCell(tituloCell);
                //Aqui creo cada cabecera
                tablaDetalle.getDefaultCell().setBackgroundColor(BaseColor.LIGHT_GRAY);
                tablaDetalle.addCell(new Phrase("ID", helveticaBold));
                tablaDetalle.addCell(new Phrase("Nombre", helveticaBold));
                tablaDetalle.addCell(new Phrase("Cantidad", helveticaBold));
                tablaDetalle.addCell(new Phrase("Valor", helveticaBold));
                tablaDetalle.getDefaultCell().setBackgroundColor(null);
                //Aqui agrego la tabla cada articulo.
                for (Map<String, String> next : detalle) {
                    tablaDetalle.addCell(next.get("idArticulo"));
                    tablaDetalle.addCell(next.get("descripcionArticulo"));
                    tablaDetalle.addCell(next.get("cantidad"));
                    tablaDetalle
                            .addCell(currencyFormatter.format(Integer.parseInt(next.get("precioArticulo"))));
                }
                //Creo el Footer
                headerIzquierda = new Paragraph();
                headerIzquierda.add(new Chunk("Total: ", helveticaBold));
                headerIzquierda
                        .add(new Chunk(currencyFormatter.format(Integer.parseInt(venta.get("totalVenta")))));
                PdfPCell footerCell = new PdfPCell(headerIzquierda);
                footerCell.setBorder(0);
                footerCell.setColspan(4);
                footerCell.setHorizontalAlignment(Element.ALIGN_RIGHT);
                tablaDetalle.addCell(footerCell);
                //Establesco el tamao  y posicion de la tabla, luego la agrego al documento
                tablaDetalle.setWidthPercentage(100f);
                tablaDetalle.setHorizontalAlignment(Element.ALIGN_RIGHT);
                document.add(tablaDetalle);
                //Cierro el documento y lo envio con flush.
                document.close();
                response.setHeader("Content-Disposition", "attachment;filename=\"reporte.pdf\"");
                os.flush();
                os.close();
            } catch (DocumentException de) {
                throw new IOException(de.getMessage());
            }
            break;
        }
        }
    }
}

From source file:controller.pdfcita.java

/**
 * Processes requests for both HTTP <code>GET</code> and <code>POST</code>
 * methods.//w w  w.  j av  a2s. c o  m
 *
 * @param request servlet request
 * @param response servlet response
 * @throws ServletException if a servlet-specific error occurs
 * @throws IOException if an I/O error occurs
 */
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("application/pdf");

    OutputStream out = response.getOutputStream();

    String codigocita = request.getParameter("codigocita");
    String nombre = request.getParameter("nombre");
    String especialidad = request.getParameter("especialidad");
    String fecha = request.getParameter("fecha");
    String hora = request.getParameter("hora");
    String doctor = request.getParameter("doctor");

    try {

        try {

            Document documento = new Document();
            Rectangle one = new Rectangle(400, 280);
            documento.setPageSize(one);
            PdfWriter.getInstance(documento, out);

            documento.open();

            Paragraph par1 = new Paragraph();
            Font fontitulo = new Font(Font.FontFamily.HELVETICA, 16, Font.BOLD, BaseColor.BLACK);
            par1.add(new Phrase("Cita", fontitulo));
            par1.setAlignment(Element.ALIGN_CENTER);
            par1.add(new Phrase(Chunk.NEWLINE));
            par1.add(new Phrase(Chunk.NEWLINE));
            documento.add(par1);

            Paragraph par2 = new Paragraph();
            Font fontescrip = new Font(Font.FontFamily.TIMES_ROMAN, 9, Font.NORMAL, BaseColor.BLACK);
            par2.add(
                    new Phrase("LUGAR DE CONSULTA :  POLICL?NICO NUESTRA SEORA DE LOS ANGELES", fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("CODIGO DE CITA :  " + codigocita, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("PACIENTE :  " + nombre, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("ESPECIALIDAD :  " + especialidad, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("FECHA :  " + fecha, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("HORA DE CITA :  " + hora, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("DOCTOR(A) :  " + doctor, fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase("COSTO DE CITA :  10.00 SOLES", fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase(
                    "El paciente tendr que imprimir esta cita y acercarse a caja para cancelar el monto de la cita para posteriormente acudir a su cita en el consultorio establecido en el recibo.",
                    fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            //par2.add(new Phrase(Chunk.NEWLINE));
            par2.add(new Phrase(
                    "                                                                                                                      - Administracin",
                    fontescrip));
            par2.add(new Phrase(Chunk.NEWLINE));
            par2.setAlignment(Element.ALIGN_JUSTIFIED);
            documento.add(par2);

            documento.close();

        } catch (Exception ex) {
            ex.getMessage();
        }

    } finally {
        out.close();
    }

    ////            try{
    //                
    //                
    //                
    //                Document document = new Document();
    //                Rectangle one = new Rectangle(70,140);
    //                document.setPageSize(one);
    //                
    //                document.open();
    //                Paragraph par1=new Paragraph();
    //                Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK);   
    //                
    //                par1.add(new Phrase("Citas del dia: Turno Maana",fonttitulo)); 
    //                document.add(par1);
    //                
    //                
    //                
    //                
    ////                Paragraph p = new Paragraph("Hi");
    ////                document.add(p);
    ////                document.setPageSize(two);
    ////                document.setMargins(20, 20, 20, 20);
    ////                document.newPage();
    ////                document.add(p);
    //                document.close();
    //                
    //                
    //                
    ////                String especialidad=request.getParameter("especialidad");
    ////                String turno=request.getParameter("turno");
    ////                String dia=request.getParameter("dia");
    //                
    ////                Document documento=new Document();
    ////                documento.setPageSize(PageSize.A4);
    ////                documento.setPageSize(PageSize.A4.rotate());
    ////                PdfWriter.getInstance(documento, out);
    ////                
    ////                documento.open();
    //                
    ////                Paragraph par1=new Paragraph();
    ////                Font fonttitulo=new Font(Font.FontFamily.HELVETICA,25,Font.BOLD,BaseColor.BLACK);
    ////                if (turno.equalsIgnoreCase("M")) {
    ////                par1.add(new Phrase("Citas del dia: "+dia+" Turno Maana",fonttitulo));    
    ////                }
    ////                else{par1.add(new Phrase("Citas del dia: "+dia+" Turno Tarde",fonttitulo));}
    ////                
    ////                
    ////                par1.setAlignment(Element.ALIGN_CENTER);
    ////                par1.add(new Phrase(Chunk.NEWLINE));
    ////                par1.add(new Phrase(Chunk.NEWLINE));
    ////                documento.add(par1);
    ////                
    ////                PdfPTable tabla=new PdfPTable(9);
    ////                PdfPCell celda1=new PdfPCell(new Paragraph("Codigo Cita",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda2=new PdfPCell(new Paragraph("Especialidad",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda3=new PdfPCell(new Paragraph("Codigo Paciente",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda4=new PdfPCell(new Paragraph("Nombre",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda5=new PdfPCell(new Paragraph("Apellido Paterno",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda6=new PdfPCell(new Paragraph("Apellido Materno",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda7=new PdfPCell(new Paragraph("Hora",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda8=new PdfPCell(new Paragraph("Doctor",FontFactory.getFont("Arial", 12, Font.BOLD)));
    ////                PdfPCell celda9=new PdfPCell(new Paragraph("Da",FontFactory.getFont("Arial", 12, Font.BOLD)));
    //                
    ////                tabla.addCell(celda1);
    ////                tabla.addCell(celda2);
    ////                tabla.addCell(celda3);
    ////                tabla.addCell(celda4);
    ////                tabla.addCell(celda5);
    ////                tabla.addCell(celda6);
    ////                tabla.addCell(celda7);
    ////                tabla.addCell(celda8);
    ////                tabla.addCell(celda9);
    ////                
    ////                try{
    ////                    
    ////                              Connection conex=conexion.obtener();
    ////                                
    ////                            PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();");
    ////                            ResultSet resultado2=consulta2.executeQuery();
    ////                            
    ////                            while(resultado2.next()){
    ////                                
    ////                                PreparedStatement consulta=conex.prepareStatement("call cita_select();");
    ////                            ResultSet resultado=consulta.executeQuery();
    ////                                
    ////                            while(resultado.next()){
    ////                                
    ////                                if (turno.equalsIgnoreCase("M") && resultado.getString(4).charAt(6)=='A' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) {
    ////
    ////                                    tabla.addCell(resultado.getString(1));
    ////                                    tabla.addCell(resultado.getString(2));
    ////                                    tabla.addCell(resultado2.getString(1));
    ////                                    tabla.addCell(resultado2.getString(2));
    ////                                    tabla.addCell(resultado2.getString(3));
    ////                                    tabla.addCell(resultado2.getString(4));
    ////                                    tabla.addCell(resultado.getString(4));
    ////                                    tabla.addCell(resultado.getString(5));
    ////                                    tabla.addCell(resultado.getString(7));
    ////                                    
    ////                                    }
    ////                                
    ////                            }    
    ////                            }
    ////                            
    ////                        conexion.cerrar();
    ////                        }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());}
    //                
    //                
    //                
    //                
    ////                try{
    ////                    
    ////                              Connection conex=conexion.obtener();
    ////                                
    ////                            PreparedStatement consulta2=conex.prepareStatement("call pacientegeneral_select();");
    ////                            ResultSet resultado2=consulta2.executeQuery();
    ////                            
    ////                            while(resultado2.next()){
    ////                                
    ////                                PreparedStatement consulta=conex.prepareStatement("call cita_select();");
    ////                            ResultSet resultado=consulta.executeQuery();
    ////                                
    ////                            while(resultado.next()){
    ////                                
    ////                                if (turno.equalsIgnoreCase("T") && resultado.getString(4).charAt(6)=='P' && resultado.getInt(3)==resultado2.getInt(1) && resultado.getString(7).equalsIgnoreCase(dia) && resultado.getString(2).equalsIgnoreCase(especialidad)) {
    ////
    ////                                    tabla.addCell(resultado.getString(1));
    ////                                    tabla.addCell(resultado.getString(2));
    ////                                    tabla.addCell(resultado2.getString(1));
    ////                                    tabla.addCell(resultado2.getString(2));
    ////                                    tabla.addCell(resultado2.getString(3));
    ////                                    tabla.addCell(resultado2.getString(4));
    ////                                    tabla.addCell(resultado.getString(4));
    ////                                    tabla.addCell(resultado.getString(5));
    ////                                    tabla.addCell(resultado.getString(7));
    ////                                    
    ////                                    }
    ////                                
    ////                            }    
    ////                            }
    ////                            
    ////                        conexion.cerrar();
    ////                        }catch(Exception ex){JOptionPane.showMessageDialog(null, ex.toString());}
    //                
    //                
    //                
    //                
    //                
    //                
    ////            float[] columnWidths = new float[]{15f, 30f, 18f, 23f, 23f, 23f, 20f, 25f, 18f};
    ////                tabla.setWidths(columnWidths);
    ////                
    ////                            documento.add(tabla);
    //                            document.close();    
    //                
    //            }catch(Exception ex){ex.getMessage();}
    //            
    //            String redirectURL="principal.jsp";
    ////            response.sendRedirect(redirectURL);

}

From source file:de.bfs.radon.omsimulation.gui.data.OMExports.java

License:Open Source License

/**
 * //from  ww w . j av a  2 s.c o  m
 * Method to export charts as PDF files using the defined path.
 * 
 * @param path
 *          The filename and absolute path.
 * @param chart
 *          The JFreeChart object.
 * @param width
 *          The width of the PDF file.
 * @param height
 *          The height of the PDF file.
 * @param mapper
 *          The font mapper for the PDF file.
 * @param title
 *          The title of the PDF file.
 * @throws IOException
 *           If writing a PDF file fails.
 */
@SuppressWarnings("deprecation")
public static void exportPdf(String path, JFreeChart chart, int width, int height, FontMapper mapper,
        String title) throws IOException {
    File file = new File(path);
    FileOutputStream pdfStream = new FileOutputStream(file);
    BufferedOutputStream pdfOutput = new BufferedOutputStream(pdfStream);
    Rectangle pagesize = new Rectangle(width, height);
    Document document = new Document();
    document.setPageSize(pagesize);
    document.setMargins(50, 50, 50, 50);
    document.addAuthor("OMSimulationTool");
    document.addSubject(title);
    try {
        PdfWriter pdfWriter = PdfWriter.getInstance(document, pdfOutput);
        document.open();
        PdfContentByte contentByte = pdfWriter.getDirectContent();
        PdfTemplate template = contentByte.createTemplate(width, height);
        Graphics2D g2D = template.createGraphics(width, height, mapper);
        Double r2D = new Rectangle2D.Double(0, 0, width, height);
        chart.draw(g2D, r2D);
        g2D.dispose();
        contentByte.addTemplate(template, 0, 0);
    } catch (DocumentException de) {
        JOptionPane.showMessageDialog(null, "Failed to write PDF document.\n" + de.getMessage(), "Failed",
                JOptionPane.ERROR_MESSAGE);
        de.printStackTrace();
    }
    document.close();
}

From source file:de.fau.amos.ChartToPDF.java

License:Open Source License

/**
 * Converts Chart into PDF//  w  w w. java 2s. c  o m
 * 
 * @param chart JFreeChart from CharRenderer that will be displayed in the PDF file
 * @param fileName Name of created PDF-file
 */
public void convertChart(JFreeChart chart, String fileName) {
    if (chart != null) {

        //set page size
        float width = PageSize.A4.getWidth();
        float height = PageSize.A4.getHeight();

        //creating a new pdf document
        Document document = new Document(new Rectangle(width, height));
        PdfWriter writer;
        try {
            writer = PdfWriter.getInstance(document,
                    new FileOutputStream(new File(System.getProperty("userdir.location"), fileName + ".pdf")));
        } catch (DocumentException e) {
            e.printStackTrace();
            return;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            return;
        }

        document.addAuthor("Green Energy Cockpit");
        document.open();

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

        //sets the pdf page
        Graphics2D g2D = new PdfGraphics2D(tp, width, height);
        Rectangle2D r2D = new Rectangle2D.Double(0, 0, width, height);

        //draws the passed JFreeChart into the PDF file
        chart.draw(g2D, r2D);

        g2D.dispose();
        cb.addTemplate(tp, 0, 0);

        document.close();

        writer.flush();
        writer.close();
    }
}