package gastostarjetaServlet;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Locale;
import java.util.ResourceBundle;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import m05bClasses.m05bComun;
import m05bClasses.m05bConexion;
import m05bClasses.m05bConstantes;
import m05bClasses.m05bFileLog;

import org.apache.fop.apps.Driver;
import org.apache.fop.apps.FOPException;
import org.xml.sax.InputSource;

public class m05bImpGastoFestivoServlet extends javax.servlet.http.HttpServlet {m05bFileLog miLog = new m05bFileLog();
	java.sql.Connection conn = null;
	String sLinea;
	String sFoFileDir = "/datos/m05b/tmp/";
	File foFileDir;
	File tmpFoFile;
	FileOutputStream tmpFoFileStream;
	m05bComun miComun = new m05bComun();
	

	String sSituacion = "";
	String sGRango = "";
	String sRango = "";
	String sTarjeta = "";
	String sMatricula = "";
	String sFecDesde = "";
	String sFecHasta = "";
	String sDesDpto = "";
	String sSituacionDesc = "";
	String sCombPeaje = "";

	public static final String FO_REQUEST_PARAM = "fo";

	// Logger log = null;

	public void doPost(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws javax.servlet.ServletException, java.io.IOException {
		try {
			doGet(request, response);
		} catch (Exception e) {
			miLog.addTraza(e);
		}
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException {
		performTask(request, response);
	}

	// if(log == null)
	// {
	// Hierarchy hierarchy = Hierarchy.getDefaultHierarchy();
	// log = hierarchy.getLoggerFor("fop");
	// log.setPriority(Priority.WARN);
	// }

	private void fncAbrirFicheroTemporal() throws java.io.IOException {
		foFileDir = new File(sFoFileDir);
		tmpFoFile = File.createTempFile("m05b", "Fo", foFileDir);
		tmpFoFileStream = new FileOutputStream(tmpFoFile);

	}

	private void fncImprimirFinPagina() throws java.io.IOException {
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:flow>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "   </fo:page-sequence>\n";
		tmpFoFileStream.write(sLinea.getBytes());

	}

	private void fncImprimirComienzoPagina(ResourceBundle res,String idioma) throws java.io.IOException,
			javax.naming.NamingException {
		sLinea = "<fo:page-sequence master-reference=\"general\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// REGION BEFORE
		sLinea = "		<fo:static-content flow-name=\"xsl-region-before\" >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// -------------- CABECERA DEL LISTADO --------------
		// Cabecera 1
		sLinea = "      <fo:block text-align=\"end\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" padding-top=\"10pt\">\n "
				+ res.getString("infGastFest.titulo")+ "</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" font-size=\"8pt\" padding-top=\"10pt\">\n <![CDATA["
				+ res.getString("infGastTarj.texto1") + sTarjeta + "]]></fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" font-size=\"8pt\" padding-top=\"10pt\">\n <![CDATA["
				+ res.getString("infGastTarj.texto3") + sMatricula + "]]></fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" font-size=\"8pt\" padding-top=\"10pt\">\n <![CDATA["
				+ res.getString("infGastTarj.texto4") + sDesDpto + "]]></fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		if (!(sSituacion.equals(""))) {
			sLinea = "      <fo:block font-weight=\"bold\" font-size=\"8pt\" padding-top=\"10pt\">\n <![CDATA["
					+ res.getString("infGastNVer.texto6") + sSituacionDesc + "]]></fo:block>\n";
			tmpFoFileStream.write(sLinea.getBytes());
		}

		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());

		// PIE DE PAGINA Pie
		sLinea = "		<fo:static-content flow-name=\"xsl-region-after\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// PIE DE PAGINA Pie
		sLinea = "      <fo:block >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       <fo:table table-layout=\"fixed\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"127mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"125mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"6pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"left\">"
				+ miComun.getDetFechaActual(idioma)
				+ "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-cell >\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block text-align=\"right\">";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = res.getString("pagina")+" <fo:page-number/> \n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-body>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "       </fo:table>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      </fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = " 		</fo:static-content>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// BODY
		sLinea = "	<fo:flow flow-name=\"xsl-region-body\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "        <fo:table table-layout=\"fixed\" space-after.optimum=\"12pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"80mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"30mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"24mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"24mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"24mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"24mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"23mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-column column-width=\"23mm\"/>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-body font-family=\"Helvetica\" font-size=\"8pt\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Usuario
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\" text-align=\"center\">\n "+ res.getString("infGastNVer.col1") 
				+ "</fo:block>";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Fecha
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col2") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Km
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col3") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Litros
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col4") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Importe
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col5") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// C/A
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col6") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Tipo
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col7") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		// Rango
		sLinea = "	    <fo:table-cell padding-top=\"1mm\">\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "      <fo:block font-weight=\"bold\"  text-align=\"center\">\n "+ res.getString("infGastNVer.col8") +"</fo:block>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    </fo:table-cell>\n";
		tmpFoFileStream.write(sLinea.getBytes());

		sLinea = "	    </fo:table-row>\n";
		tmpFoFileStream.write(sLinea.getBytes());
		sLinea = "	    <fo:table-row >\n";
		tmpFoFileStream.write(sLinea.getBytes());

	}

	public void performTask(javax.servlet.http.HttpServletRequest request,
			javax.servlet.http.HttpServletResponse response)
			throws ServletException {
		java.sql.Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		PreparedStatement pstmt2 = null;
		ResultSet rs2 = null;
		PreparedStatement pstmt3 = null;
		ResultSet rs3 = null;
		// m05bComun miComun = new m05bComun();

		try {
			HttpSession session = request.getSession(true);
			/* Iker. idioma */
			Locale idiomaLocal = (Locale) session.getAttribute("Local");
			String idiomaSes = ((idiomaLocal.getLanguage() == null) ? "es"
					: idiomaLocal.getLanguage());
			String campoTexto = "";
			String campoTexto2 = "";
			String campoTexto3 = "C";
			String formatoFecha="dd/MM/yyyy";
			ResourceBundle res = (ResourceBundle) session
					.getAttribute("resTit");
			if (!idiomaSes.equals("es")) {
				campoTexto = "E";
				campoTexto2 = "E_";
				campoTexto3 = "E";
				formatoFecha = "yyyy/MM/dd";
			}
			m05bConexion miConex = new m05bConexion();
			conn = miConex.getConnection();

			// Obtención de información de BD
			// Vehículo
			// Recogemos la situacion
			sSituacion = request.getParameter("Situacion");
			if ((sSituacion == null) || (sSituacion.equals(""))) {
				sSituacion = "";
			} else {
				sSituacion = miComun.ListaCaracteres(sSituacion);
			}
			// Recogemos el Grupo Rango
			sGRango = request.getParameter("GRango");
			if ((sGRango == null) || (sGRango.equals(""))) {
				sGRango = "";
			}
			// Recogemos el Rango
			sRango = request.getParameter("Rango");
			if ((sRango == null) || (sRango.equals(""))) {
				sRango = "";
			}
			// Recogemos Tarjeta
			sTarjeta = request.getParameter("Tarjeta");
			if (sTarjeta == null) {
				sTarjeta = "";
			}
			// Recogemos Matricula
			sMatricula = request.getParameter("Matricula");
			if (sMatricula == null) {
				sMatricula = "";
			}
			// Recogemos Fecha Desde:
			sFecDesde = request.getParameter("FecDesde");
			if (sFecDesde == null) {
				sFecDesde = "";
			}

			// Recogemos Fecha Hasta:
			sFecHasta = request.getParameter("FecHasta");
			if (sFecHasta == null) {
				sFecHasta = "";
			}

			// Recogemos CombPeaje:
			sCombPeaje = request.getParameter("CombPeaje");
			if (sCombPeaje == null) {
				sCombPeaje = "";
			}

			sDesDpto = "";
			String sUsuario = "";
			String sFecha = "";
			String sKilometros = "";
			String sLitros = "";
			String sImporte = "";
			String sCargo = "";
			String sTipo = "";
			String sTarjetaAnt = "";
			String sFecha2 = "";
			String sFecha2bis = "";
			double dImporte = 0.0;
			double dLitros = 0.0;
			String sSituacionD = "";

			if (!(sSituacion.equals(""))) {
				String sSentenciaSituacion = " SELECT "
						+ m05bConstantes.COL_99_DESCRIPCION + " FROM "
						+ m05bConstantes.TAB_DESCRIPCIONES + "  S " + " WHERE "
						+ m05bConstantes.COL_99_CODDESC + " in (" + sSituacion
						+ ") AND " + m05bConstantes.COL_99_CODTABLA + "='"
						+ m05bConstantes.DESC_SITUACIONES + "'";
				pstmt = conn.prepareStatement(sSentenciaSituacion);
				rs = pstmt.executeQuery();
				while (rs.next()) {
					sSituacionD = rs.getString(1);
					if (!(sSituacionDesc.equals(""))) {
						sSituacionDesc = sSituacionDesc + "," + sSituacionD;
					} else {
						sSituacionDesc = sSituacionD;
					}
				}
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
			}
			String sUsuario2 = (String) session.getAttribute("persona");

			String sSentenciaFechaNoDevueltos = "";
			String sSentenciaPersonal = "";

			String sSentencia = "SELECT " + m05bConstantes.COL_95_TARJETA + ","
					+ m05bConstantes.COL_95_MATRICULA + ","
					+ m05bConstantes.COL_95_TIPO + ","
					+ m05bConstantes.COL_95_CONCEPTO + ","
					+ m05bConstantes.COL_95_KM + ","
					+ m05bConstantes.COL_95_LITROS + ","
					+ m05bConstantes.COL_95_IMPORTE + ","
					+ m05bConstantes.COL_95_CARGABONO + ","
					+ m05bConstantes.COL_95_VERIFIC + ",TO_CHAR("
					+ m05bConstantes.COL_95_FECHA
					+ ",'"+formatoFecha+" hh24:mi:ss'),"
					+ m05bConstantes.COL_95_RANGO + ","
					+ m05bConstantes.COL_95_SITUACION + ","
					+ m05bConstantes.COL_95_DESDPTO + ","
					+ m05bConstantes.COL_94_NOMBRE + ",TO_CHAR("
					+ m05bConstantes.COL_95_FECHA + ",'"+formatoFecha+"')" + " FROM "
					+ m05bConstantes.TAB_TMPLSTGASTOS + ","
					+ m05bConstantes.TAB_TMPLSTGASTOS2 + " WHERE "
					+ m05bConstantes.COL_95_USUARIO + "='" + sUsuario2
					+ "' AND " + m05bConstantes.COL_95_USUARIO + "="
					+ m05bConstantes.COL_94_USUARIO + "(+) AND "
					+ m05bConstantes.COL_94_MATRICULA + "(+) ="
					+ m05bConstantes.COL_95_MATRICULA + " AND "
					+ m05bConstantes.COL_94_FINICIO + "(+) <="
					+ m05bConstantes.COL_95_FECHA + " AND "
					+ m05bConstantes.COL_94_FFIN + "(+) >="
					+ m05bConstantes.COL_95_FECHA;
			if (sCombPeaje.equals("1")) {
				sSentencia = sSentencia + " AND " + m05bConstantes.COL_95_TIPO
						+ " = 'C'";
			} else if (sCombPeaje.equals("2")) {
				sSentencia = sSentencia + " AND " + m05bConstantes.COL_95_TIPO
						+ " = 'P'";
			}
			sSentencia = sSentencia + " ORDER BY "
					+ m05bConstantes.COL_95_TARJETA + ","
					+ m05bConstantes.COL_95_FECHA;
			miLog.addTraza(m05bConstantes.LOG_NO_USER,
					m05bConstantes.LOG_NO_SRC, "sSentencia: " + sSentencia,
					m05bConstantes.LOG_NIVEL_BAJO);

			pstmt = conn.prepareStatement(sSentencia);
			rs = pstmt.executeQuery();

			// String foParam = request.getParameter(FO_REQUEST_PARAM);
			fncAbrirFicheroTemporal();

			sLinea = "<?xml version=\"1.0\" encoding=\"windows-1252\"?>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "<fo:root xmlns:fo=\"http://www.w3.org/1999/XSL/Format\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// LAYOUT DEL LISTADO
			sLinea = "<fo:layout-master-set>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "	<fo:simple-page-master master-name=\"general\"  page-height=\"21cm\" page-width=\"29.5cm\" margin-top=\"2cm\" margin-bottom=\"2cm\" margin-left=\"2cm\" margin-right=\"2cm\">\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-before extent=\"4cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-body  margin-top=\"4.8cm\" margin-bottom=\"1.5cm\" />\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-after  extent=\"1cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-start extent=\"0cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			sLinea = "		<fo:region-end extent=\"0cm\"/>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "	</fo:simple-page-master>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			sLinea = "</fo:layout-master-set>\n";
			tmpFoFileStream.write(sLinea.getBytes());
			// -------------- DETALLE DEL LISTADO --------------

			int cont = 0;
			while (rs.next()) {
				sDesDpto = rs.getString(13) == null ? "" : rs.getString(13);
				sRango = rs.getString(11) == null ? "" : rs.getString(11);

				sMatricula = rs.getString(2) == null ? "" : rs.getString(2);

				sFecha2 = rs.getString(10) == null ? "" : rs.getString(10);
				sFecha2bis = rs.getString(15) == null ? "" : rs.getString(15);
				sKilometros = rs.getString(5) == null ? "0" : rs.getString(5);

				sLitros = rs.getString(6) == null ? "0" : rs.getString(6);
				dLitros = Double.valueOf(sLitros).doubleValue();

				sImporte = rs.getString(7) == null ? "0" : rs.getString(7);
				dImporte = Double.valueOf(sImporte).doubleValue();

				sCargo = rs.getString(8) == null ? "" : rs.getString(8);

				sTipo = rs.getString(3) == null ? "" : rs.getString(3);

				sTarjeta = rs.getString(1) == null ? "" : rs.getString(1);

				sUsuario = rs.getString(14) == null ? "" : rs.getString(14);
				if (sUsuario.equals("")) {
					// sSentenciaFechaNoDevueltos= "select max(" +
					// m05bConstantes.COL_94_FFIN + ")," +
					// " max(" + m05bConstantes.COL_94_NOMBRE + ") from "+
					// m05bConstantes.TAB_TMPLSTGASTOS2 +" where " +
					// m05bConstantes.COL_94_MATRICULA+"='"+ sMatricula
					// +"' and "+
					// " TO_CHAR( "+ m05bConstantes.COL_94_FFIN+
					// ",'dd/mm/yyyy') <= '" + sFecha2 + "'";
					sSentenciaFechaNoDevueltos = "select "
							+ m05bConstantes.COL_94_NOMBRE + " from "
							+ m05bConstantes.TAB_TMPLSTGASTOS2 + " where "
							+ m05bConstantes.COL_94_MATRICULA + "='"
							+ sMatricula + "' and "
							+ m05bConstantes.COL_94_FFIN + " = (select max("
							+ m05bConstantes.COL_94_FFIN + ") from "
							+ m05bConstantes.TAB_TMPLSTGASTOS2 + " where "
							+ m05bConstantes.COL_94_MATRICULA + "='"
							+ sMatricula + "' and(TO_CHAR("
							+ m05bConstantes.COL_94_FFIN
							+ ",'YYYY/mm/dd') <= '" + sFecha2bis + "'))";
					pstmt3 = conn.prepareStatement(sSentenciaFechaNoDevueltos);
					rs3 = pstmt3.executeQuery();
					if (rs3.next()) {
						sUsuario = rs3.getString(1) == null ? "" : rs3
								.getString(1);
					}
					if (rs3 != null)
						rs3.close();
					if (pstmt3 != null)
						pstmt3.close();
				}
				if (((!(sTarjeta.equals(sTarjetaAnt)))) || (cont == 18)) {
					if (sTarjetaAnt != "") {
						fncImprimirFinPagina();
					}
					fncImprimirComienzoPagina(res,campoTexto3);
					cont = 0;
				} else {
					cont = cont + 1;
					sLinea = "	    <fo:table-row >\n";
					tmpFoFileStream.write(sLinea.getBytes());
				}
				sTarjetaAnt = sTarjeta;
				// Matricula
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA["
						+ sUsuario + "]]></fo:block>";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Marca
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n <![CDATA[" + sFecha2
						+ "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Modelo
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n"
						+ miComun.formatearStrMiles(sKilometros)
						+ "</fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// F.Matricula
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n"
						+ miComun.formatearDblMilesDec(dLitros)
						+ "</fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Km
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n"
						+ miComun.formatearDblMilesDec(dImporte)
						+ "</fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// situacion
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA[" + sCargo
						+ "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// Centro
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA[" + sTipo
						+ "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				// descripcion
				sLinea = "	    <fo:table-cell padding-top=\"2mm\" border-width=\"0.1mm\" border-style=\"solid\">\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "      <fo:block  text-align=\"center\">\n<![CDATA[" + sRango
						+ "]]></fo:block>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-cell>\n";
				tmpFoFileStream.write(sLinea.getBytes());
				sLinea = "	    </fo:table-row>\n";
				tmpFoFileStream.write(sLinea.getBytes());

			}
			fncImprimirFinPagina();
			rs.close();

			sLinea = "</fo:root>\n";
			tmpFoFileStream.write(sLinea.getBytes());

			tmpFoFileStream.close();
			// renderFO(new InputSource(file), response);
			generarPDFdesdeFO(sFoFileDir + tmpFoFile.getName(), sFoFileDir,
					response);

			// tmpFoFile.delete();

			// response.flushBuffer();

		} catch (Exception ex) {
			try {
				response.sendRedirect("m05bError.jsp");
			} catch (IOException e) {
				// TODO Auto-generated catch block
				miLog.addTraza(e);
			}
		} finally {
			try {
				if (rs != null)
					rs.close();
				if (pstmt != null)
					pstmt.close();
				if (rs2 != null)
					rs2.close();
				if (pstmt2 != null)
					pstmt2.close();
				if (rs3 != null)
					rs3.close();
				if (pstmt3 != null)
					pstmt3.close();
				if (conn != null)
					conn.close();
			} catch (SQLException e2) {
				try {
					response.sendRedirect("m05bError.jsp");
				} catch (IOException e) {
					// TODO Auto-generated catch block
					miLog.addTraza(e);
				}
			}
		}
	}

	/**
	 * renders an FO inputsource into a PDF file which is rendered directly to
	 * the response object's OutputStream
	 */
	public void renderFO(InputSource foFile, HttpServletResponse response)
			throws ServletException {
		try {
			ByteArrayOutputStream out = new ByteArrayOutputStream();

			response.reset();
			OutputStream oOut = response.getOutputStream();
			BufferedOutputStream bOut = new BufferedOutputStream(oOut);
			Driver driver = new Driver(foFile, out);
			driver.setRenderer(Driver.RENDER_PDF);
			driver.run();

			response.setContentLength(out.size());
			response.setContentType("application/pdf");

			bOut.write(out.toByteArray());
			out.close();
			bOut.flush();
			bOut.close();
			// response.flushBuffer();
		} catch (Exception ex) {
			throw new ServletException(ex);
		}
	}

	public void generarPDFdesdeFO(String ficheroFO, String rutaPDF,
			HttpServletResponse response) throws FOPException {
		try {

			Driver driver = new Driver();

			driver.setRenderer(Driver.RENDER_PDF);

			// Si no existe el directrio lo crea
			File f = new File(rutaPDF);

			if (!f.exists()) {

				f.mkdir();

			}
			// Cargar los datos del .FO
			FileInputStream file = new FileInputStream(ficheroFO);

			BufferedInputStream bfile = new BufferedInputStream(file);

			driver.setInputSource(new InputSource(bfile));

			// Crear un temporal que va a ser el .pdf
			String sPdfFileDir = rutaPDF;
			File pdfFileDir = new File(sPdfFileDir);
			File tmpPdfFile = File.createTempFile("m05b", ".pdf", pdfFileDir);

			FileOutputStream fileout = new FileOutputStream(tmpPdfFile);

			BufferedOutputStream bfileout = new BufferedOutputStream(fileout);

			driver.setOutputStream(bfileout);

			driver.run();

			bfile.close();

			bfileout.close();
			// Longitus del Fichero PDF.
			Long longitud = new Long(tmpPdfFile.length());
			String sLongitud = "" + longitud;
			int iLongitud = Integer.parseInt(sLongitud);

			response.setContentLength((int) iLongitud);
			response.setContentType("application/pdf");

			byte[] fileBytes = new byte[longitud.intValue()];
			FileInputStream fisficheroPdf = new FileInputStream(tmpPdfFile);
			fisficheroPdf.read(fileBytes);
			ServletOutputStream os = response.getOutputStream();
			((OutputStream) os).write(fileBytes);
			((OutputStream) os).flush();
			((OutputStream) os).close();

			// BORRAR EL FICHERO FO

			File fichero = new File(ficheroFO);

			boolean borrado = fichero.delete();
			boolean borrado2 = tmpPdfFile.delete();

		} catch (Exception e) {

			// System.out.println("EXCEPCION !!! : Error pasando de FO a PDF: "
			// + e);

		}

	}

}