List of usage examples for com.lowagie.text Document setPageSize
public boolean setPageSize(Rectangle pageSize)
From source file:jdbreport.model.io.pdf.itext2.PdfWriter.java
License:Apache License
private int saveSheet(Document document, int listCount, ReportModel model) throws DocumentException, IOException, SaveReportException { model.updatePages(0);/*from w w w . java 2s . c o m*/ ReportPage pageFormat = model.getReportPage(); Paper paper = pageFormat.getPaper(); Rectangle pageSize = new Rectangle(Math.round((float) paper.getWidth()), Math.round((float) paper.getHeight())); if (pageFormat.getOrientation() == ReportPage.LANDSCAPE) { pageSize = pageSize.rotate(); } document.setPageSize(pageSize); document.setMargins(Math.round((float) pageFormat.getLeftMargin(Units.PT)), Math.round((float) pageFormat.getRightMargin(Units.PT)), Math.round((float) pageFormat.getTopMargin(Units.PT)), Math.round((float) pageFormat.getBottomMargin(Units.PT))); Rectangle viewPageSize = new Rectangle( document.getPageSize().getWidth() - document.leftMargin() - document.rightMargin(), document.getPageSize().getHeight() - document.topMargin() - document.bottomMargin()); if (listCount > 0) { document.newPage(); } listCount++; //float columnMargin = (float) Units.PT.setXPixels(model.getColumnModel().getColumnMargin()); ReportPrintable printable = new ReportPrintable(model); int pageCount = printable.calcCountPage(model.getReportPage()); Map<Integer, PageClip> clips = printable.getPageClips(); int leftCol; int topRow; int rightCol; int bottomRow; for (int pageIndex = 0; pageIndex < pageCount; pageIndex++) { PageClip pageClip = clips.get(pageIndex); if (pageClip == null) break; leftCol = pageClip.getLeftCol(); rightCol = pageClip.getRightCol(); topRow = pageClip.getTopRow(); bottomRow = pageClip.getBottomRow(); int columnCount = rightCol - leftCol; float[] widths = new float[columnCount + 1]; widths[0] = 1; for (int c = 0; c < columnCount; c++) { ReportColumn column = (ReportColumn) model.getColumnModel().getColumn(leftCol + c); widths[c + 1] = (float) Math.round(column.getNativeWidth()); } PdfPTable table = createPdfTable(columnCount + 1, widths, viewPageSize); fillTable(model, leftCol, topRow, rightCol, bottomRow, table); document.add(table); if (pageIndex < clips.size()) { document.newPage(); } } return listCount; }
From source file:managedbean.afos.FlightDutyBacking.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();/*from ww w. j a v a 2 s .c o m*/ pdf.setPageSize(PageSize.A4); ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext() .getContext(); String logo = servletContext.getRealPath("") + File.separator + "resources" + File.separator + "images" + File.separator + "logo.png"; Image logoImg = Image.getInstance(logo); logoImg.scalePercent(20f); SimpleDateFormat sdf = new SimpleDateFormat("E, dd/MM/yyyy 'at' hh:mm:ss a"); Font titleFont = new Font(); Font subtitleFont = new Font(); titleFont.setSize(16); titleFont.setStyle(Font.BOLD); subtitleFont.setSize(12); subtitleFont.setStyle(Font.BOLD); Paragraph title = new Paragraph(flightReport.getType() + " Duty Report", titleFont); title.setAlignment(Element.ALIGN_CENTER); title.setSpacingAfter(12f); Paragraph subTitle1 = new Paragraph("Flight Information:", subtitleFont); subTitle1.setSpacingAfter(8f); Paragraph subTitle2 = new Paragraph(flightReport.getType() + " Checklist:", subtitleFont); subTitle2.setSpacingBefore(12f); subTitle2.setSpacingAfter(12f); com.lowagie.text.List list = new com.lowagie.text.List(true, 15); list.setLettered(true); list.add("Flight: " + selectedFlightSchedule.getFlight().getFlightNo()); list.add("Return Flight: " + selectedFlightSchedule.getFlight().getReturnedFlight().getFlightNo()); Airport departure, arrival; departure = selectedFlightSchedule.getLeg().getDepartAirport(); arrival = selectedFlightSchedule.getLeg().getArrivalAirport(); sdf.setTimeZone(TimeZone.getTimeZone(getTimeZone(departure))); list.add("Departure Time: " + sdf.format(selectedFlightSchedule.getDepartDate()) + " (" + departure.getCity().getCityName() + " Time)"); sdf.setTimeZone(TimeZone.getTimeZone(getTimeZone(arrival))); list.add("Arrival Time: " + sdf.format(selectedFlightSchedule.getArrivalDate()) + " (" + arrival.getCity().getCityName() + " Time)"); list.add("Origin: " + departure.getCity().getCityName() + " (" + departure.getAirportName() + ")"); list.add("Destination: " + arrival.getCity().getCityName() + " (" + arrival.getAirportName() + ")"); pdf.add(logoImg); pdf.add(new Paragraph(" ")); pdf.add(title); pdf.add(subTitle1); pdf.add(list); pdf.add(subTitle2); pdf.setMargins(72, 72, 72, 72); pdf.addAuthor("Merlion Airline"); pdf.addCreationDate(); sdf.applyPattern("dd/MM/yyyy_hh:mm:ss"); pdf.addTitle("Post-Flight Duty Report_" + selectedFlightSchedule.getFlight().getFlightNo() + "_" + sdf.format(selectedFlightSchedule.getDepartDate())); }
From source file:MbView.MbAbonos.java
public void imprimeDespiese(Object document) { try {//from w w w . j av a2s . com Document pdf = (Document) document; pdf.open(); pdf.setPageSize(PageSize.A4); HTMLWorker htmlWorker = new HTMLWorker(pdf); String html = ""; html = new ImprimeDespiece().imprime(lstDespiece); htmlWorker.parse(new StringReader(html)); } catch (Exception e) { System.out.println("Ocurrio un error generando pdf: " + e.toString()); } }
From source file:mx.avanti.siract.ui.RACTBeanUI.java
public void preProcessPDF(Object document) throws IOException, DocumentException { final Document pdf = (Document) document; pdf.setPageSize(PageSize.A4.rotate()); }
From source file:mx.avanti.siract.ui.RACTBeanUI.java
public void postProcessPDF(Object document) throws IOException, DocumentException { final Document pdf = (Document) document; TreeNode[] selectedNodesPDF = selectedNodes; if (selectedNodes != null) { for (TreeNode nodo : selectedNodes) { System.out.println("*********************" + ((NodoMultiClass) nodo.getData()).getNombre()); }/*from w ww. j a va2 s . c o m*/ } pdf.setPageSize(PageSize.A4.rotate()); pdf.open(); String nombrep = profesor.getPronombre() + " " + profesor.getProapellidoPaterno() + " " + profesor.getProapellidoMaterno(); String numEmpPro = Integer.toString(profesor.getPronumeroEmpleado()); String porAv = Float.toString(porcentajeAvance); SimpleDateFormat formato = new SimpleDateFormat("dd/MM/yyyy"); //Obtener el nombre del programa educativo seleccionado String nombreProgEdu = ""; int programaEducativoSeleccionado2 = Integer.parseInt(programaEducativoSeleccionado); for (int x = 0; x < programasEducativos.size(); x++) { if (programasEducativos.get(x).getPedid() == programaEducativoSeleccionado2) { nombreProgEdu = programasEducativos.get(x).getPednombre(); } } //---------------------------------------------------------------------------------- //Obtener el nombre de la unidad de aprendizaje y clave seleccionada String nombreUniApr = ""; String nombreclave = ""; int uniAprselec2 = Integer.parseInt(unidadAprendizajeSeleccionada); for (int x = 0; x < unidadesaprendisaje.size(); x++) { if (unidadesaprendisaje.get(x).getUapclave() == uniAprselec2) { nombreUniApr = unidadesaprendisaje.get(x).getUapnombre(); nombreclave = Integer.toString(unidadesaprendisaje.get(x).getUapclave()); } } //---------------------------------------------------------------------- // rutaImagen es la ruta para acceder a la imagen guardada en el folder resources del proyecto try { // Image imagenLogo = Image.getInstance("C:\\Users\\Y\\Desktop\\RACT 22-01-2015\\RACT\\build\\web\\resources\\imagenes\\logo.jpg"); Image imagenLogo = Image.getInstance(RACTBeanUI.class.getResource("imagenes/logo.jpg")); //Posicion de imagen (Horizontal, Vertiacal) imagenLogo.setAbsolutePosition(120f, 460f); //Tamao de imagen (Ancho, largo) imagenLogo.scaleAbsolute(90, 120); //imagenLogo.scaleAbsoluteWidth(100f); //imagenLogo.scaleAbsoluteHeight(150f); //imagenLogo.scaleToFit(100f, 120f); Esta es la buena //Image imagenLogo = Image.getInstance("http://ed.uabc.mx/sed/images/logo.jpg"); //imagenLogo.scaleAbsolute(70f, 90f); pdf.add(imagenLogo); } catch (Exception exception) { System.out.println("****NO SE ENCONTRO LA RUTA DE IMAGEN ESPECIFICADA"); } //Tabla con UABC y Nombre del profesor(a) PdfPTable pdfTabletitulo = new PdfPTable(2); pdfTabletitulo.getDefaultCell().setBorder(PdfPCell.NO_BORDER); PdfPTable pdfTabletitulo2 = new PdfPTable(2); pdfTabletitulo2.getDefaultCell().setBorder(PdfPCell.NO_BORDER); Paragraph UABC = new Paragraph("Universidad Autnoma de Baja California", FontFactory.getFont(FontFactory.TIMES, 22, Font.BOLD, new Color(0, 113, 65))); UABC.setAlignment(Element.ALIGN_CENTER); Paragraph esp = new Paragraph(" "); pdf.add(UABC); pdf.add(esp); pdf.add(esp); pdf.add(esp); pdf.add(esp); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("")); pdfTabletitulo.addCell(new Paragraph("Profesor(a): ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdfTabletitulo.addCell(new Paragraph(nombrep)); pdfTabletitulo2.addCell(new Paragraph("Num. de Empleado: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdfTabletitulo2.addCell(new Paragraph(numEmpPro)); pdfTabletitulo.setHorizontalAlignment(25); //pdfTabletitulo.setHorizontalAlignment(Element.ALIGN_CENTER); //document.add(table); float[] columnWidthsss = new float[] { 4f, 28 }; pdfTabletitulo.setWidths(columnWidthsss); pdf.add(pdfTabletitulo); float[] columnWidthss = new float[] { 10f, 38 }; pdfTabletitulo2.setWidths(columnWidthss); pdf.add(pdfTabletitulo2); pdf.add(new Phrase(" ")); //---------------------------------------------------------------------- //Tabla Cabezera PdfPTable pdftablecabezera = new PdfPTable(4); pdftablecabezera.getDefaultCell().setBorder(PdfPCell.NO_BORDER); PdfPTable pdftablecabezera2 = new PdfPTable(5); pdftablecabezera2.getDefaultCell().setBorder(PdfPCell.NO_BORDER); pdftablecabezera.addCell(new Paragraph("Programa educativo: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera.addCell(new Paragraph("Fecha: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera.addCell(new Paragraph("Ciclo Escolar: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera.addCell(new Paragraph("Avance Global: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera.addCell(new Paragraph(nombreProgEdu)); pdftablecabezera.addCell(new Paragraph(formato.format(new Date()))); pdftablecabezera.addCell(new Paragraph(" " + cicloEscolar)); pdftablecabezera.addCell(new Paragraph(" " + porAv)); pdftablecabezera.addCell(new Paragraph(" ")); pdftablecabezera.addCell(new Paragraph(" ")); pdftablecabezera.addCell(new Paragraph(" ")); pdftablecabezera.addCell(new Paragraph(" ")); pdftablecabezera2.addCell(new Paragraph("Unidad de Aprendizaje: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera2.addCell(new Paragraph("Clave: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera2.addCell(new Paragraph("Grupo: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera2.addCell(new Paragraph("Subgrupo: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera2.addCell(new Paragraph("Tipo Grupo: ", FontFactory.getFont(FontFactory.TIMES, 14, Font.BOLD, new Color(0, 0, 0)))); pdftablecabezera2.addCell(new Paragraph(nombreUnidadSeleccionado)); pdftablecabezera2.addCell(new Paragraph(claveUnidadAprendizajeSeleccionada)); pdftablecabezera2.addCell(new Paragraph(" " + grupo)); pdftablecabezera2.addCell(new Paragraph(" " + subGrupo)); String tipoGrupo = ""; switch (this.tipoUnidadAprendizaje) { case "C": tipoGrupo = "Clase"; break; case "L": tipoGrupo = "Laboratorio"; break; case "T": tipoGrupo = "Taller"; break; case "P": tipoGrupo = "Practica"; break; case "CL": tipoGrupo = "Practicas Clinica"; break; } pdftablecabezera2.addCell(new Paragraph(" " + tipoGrupo)); pdftablecabezera2.addCell(new Paragraph(" ")); pdftablecabezera.setHorizontalAlignment(25); float[] columnWidths = new float[] { 38f, 10f, 14f, 18f }; pdftablecabezera.setWidths(columnWidths); pdf.add(pdftablecabezera); pdftablecabezera2.setHorizontalAlignment(25); float[] columnWidthss2 = new float[] { 38f, 10f, 8f, 11f, 14f }; pdftablecabezera2.setWidths(columnWidthss2); pdf.add(pdftablecabezera2); pdf.add(new Phrase(" ")); //---------------------------------------------------------------------- Paragraph numrep = new Paragraph("Reporte # " + numeroReporte, FontFactory.getFont(FontFactory.TIMES, 16, Font.BOLD, new Color(0, 0, 0))); numrep.setAlignment(Element.ALIGN_CENTER); pdf.add(numrep); pdf.add(new Paragraph(" ")); //Tabla con Datos PdfPTable pdfTable = new PdfPTable(3); pdfTable.addCell(new Phrase("Nombre", FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0)))); pdfTable.addCell(new Phrase("Porcentaje", FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0)))); pdfTable.addCell(new Phrase("Observaciones", FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0)))); //Evitar Null pointer exception por no tener nodoes en selectedNodes //Se utiliza un auxiliar de selectedNodes por que hay posibilidad de que selectedNodes se modifique durante el proceso de generacion del PDF if (selectedNodesPDF != null && selectedNodesPDF.length > 0) { //Regresar a lo basicoString int nns = selectedNodesPDF.length; String[] ns = new String[nns]; for (int x = 0; x < selectedNodesPDF.length; x++) { ns[x] = ((NodoMultiClass) selectedNodesPDF[x].getData()).getNumero() + "--" + ((NodoMultiClass) selectedNodes[x].getData()).getNombre() + "--" + ((NodoMultiClass) selectedNodes[x].getData()).getPorcentajeAvance() + "--" + ((NodoMultiClass) selectedNodes[x].getData()).getObservaciones() + " -- "; } String[] filas = new String[4]; String[] nstr = new String[3]; String[] filas2 = new String[4]; String[] nstr2 = new String[3]; for (int x = 1; x < ns.length; x++) { for (int y = 0; y < ns.length - x; y++) { //Obtengo los valores para hacer las comparaciones int[] n = new int[3]; int[] n2 = new int[3]; filas = ns[y].split("--"); nstr = filas[0].split("\\."); for (int z = 0; z < nstr.length; z++) { if (nstr == null) { n[z] = 0; } else { n[z] = Integer.parseInt(nstr[z]); } } filas2 = ns[y + 1].split("--"); nstr2 = filas2[0].split("\\."); for (int z = 0; z < nstr2.length; z++) { if (nstr2 == null) { n2[z] = 0; } else { n2[z] = Integer.parseInt(nstr2[z]); } } //-------------------------------------------------comparacion if (n[0] == n2[0]) { if (n[1] == n2[1]) { if (n[2] > n2[2]) { String aux = ns[y]; ns[y] = ns[y + 1]; ns[y + 1] = aux; } } else { if (n[1] > n2[1]) { String aux = ns[y]; ns[y] = ns[y + 1]; ns[y + 1] = aux; } } } else { if (n[0] > n2[0]) { String aux = ns[y]; ns[y] = ns[y + 1]; ns[y + 1] = aux; } } //------------------------------------------------------------- } } String[] auxNum = new String[4]; for (int x = 0; x < ns.length; x++) { filas = ns[x].split("--"); num = filas[0].split("\\."); //Auxiliar para agregar padre de tema/subtema int auxMargen = 1; //Agregar unidad a la que pertenece el tema/subtema String[] auxNum2 = auxNum; int tamanoArbol = root.getChildCount(); //AGREGAR A TEMA if (Integer.parseInt(num[0]) > tamanoArbol) { auxMargen = Integer.parseInt(num[0]) - tamanoArbol; } if (num.length >= 2 && auxNum2[0] != null && !auxNum2[0].equals(num[0])) { if (!num[1].equals("0")) { while (!num[0].equals(auxNum2[0]) && auxMargen > 0) { System.out.println("XXXXXXIteracion para encontrar padre XXXXXXX 0" + auxMargen); auxNum2 = (((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\."); //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){ if (num[0].equals(auxNum2[0])) { } else { auxMargen--; } } System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre()); NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()); //UTIL PARA PONER TEXTO TACHADO // Chunk strikethrough = new Chunk("Strikethrough."); // strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location // document.add(strikethrough); pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(auxNodo.getObservaciones()); } } else { if (auxNum2[0] == null && num.length >= 2) { auxNum2 = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen) .getData()).getNumero()).split("\\."); while (!num[0].equals(auxNum2[0]) && auxMargen > 0) { System.out.println("XXXXXXIteracion para encontrar padre XXXXXXX 0" + auxMargen); auxNum2 = (((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNumero()).split("\\."); //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){ if (num[0].equals(auxNum2[0])) { } else { auxMargen--; } } System.out.println("***Unidad Padre" + ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()).getNombre()); NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()); //UTIL PARA PONER TEXTO TACHADO // Chunk strikethrough = new Chunk("Strikethrough."); // strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location // document.add(strikethrough); pdfTable.addCell(new Phrase(auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(auxNodo.getObservaciones()); } } //AGREGAR A SUBTEMA String[] auxNumeroUnidad = new String[4]; int auxMargen2 = 1; if (num.length == 3 && auxNum[1] != null && !auxNum[1].equals(num[1])) { if (!num[2].equals("0")) { while (!num[0].equals(auxNum[0]) && auxMargen >= 0) { NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()); auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\."); tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount(); if (Integer.parseInt(num[1]) > tamanoArbol) { auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol; } while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1]) && auxMargen > 0) { System.out.println("XXXXXXIteracion para encontrar padre XXXXXXX 0" + auxMargen); auxNum = (((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getChildren() .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero()) .split("\\."); //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){ if (num[1].equals(auxNum[1])) { } else { auxMargen2--; } } // auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\."); if (num[0].equals(auxNum[0])) { } else { auxMargen--; } } System.out.println("*****Unidad Padre(SUBTEMA)" + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen) .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData()) .getNombre()); NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getChildren() .get(Integer.parseInt(num[1]) - auxMargen2).getData()); //UTIL PARA PONER TEXTO TACHADO // Chunk strikethrough = new Chunk("Strikethrough."); // strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location // document.add(strikethrough); pdfTable.addCell( new Phrase(" " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(auxNodo.getObservaciones()); } } else { if (auxNum[0] == null && num.length == 3) { auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen) .getData()).getNumero()).split("\\."); while (!num[0].equals(auxNum[0]) && auxMargen > 0) { NodoMultiClass auxNodoUnidad = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getData()); auxNumeroUnidad = auxNodoUnidad.getNumero().split("\\."); tamanoArbol = root.getChildren().get(Integer.parseInt(num[0])).getChildCount(); if (Integer.parseInt(num[1]) > tamanoArbol) { auxMargen2 = Integer.parseInt(num[1]) - tamanoArbol; } while (auxNumeroUnidad[0].equals(num[0]) && !num[1].equals(auxNum[1]) && auxMargen > 0) { System.out.println("Iteracion para encontrar padre XXXXXXX 0" + auxMargen); auxNum = (((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getChildren() .get(Integer.parseInt(num[1]) - auxMargen2).getData()).getNumero()) .split("\\."); //if(auxNum[0]!=null&&Integer.parseInt(num[0])>Integer.parseInt(auxNum[0])){ if (num[1].equals(auxNum[1])) { } else { auxMargen2--; } } // auxNum = (((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[1]) - auxMargen).getData()).getNumero()).split("\\."); if (num[0].equals(auxNum[0])) { } else { auxMargen--; } } System.out.println("***Unidad Padre(SUBTEMA)" + ((NodoMultiClass) root.getChildren().get(Integer.parseInt(num[0]) - auxMargen) .getChildren().get(Integer.parseInt(num[1]) - auxMargen2).getData()) .getNombre()); NodoMultiClass auxNodo = ((NodoMultiClass) root.getChildren() .get(Integer.parseInt(num[0]) - auxMargen).getChildren() .get(Integer.parseInt(num[1]) - auxMargen2).getData()); //UTIL PARA PONER TEXTO TACHADO // Chunk strikethrough = new Chunk("Strikethrough."); // strikethrough.setUnderline(0.1f, 3f); //0.1 thick, 2 y-location // document.add(strikethrough); pdfTable.addCell( new Phrase(" " + auxNodo.getNumero() + ".- " + auxNodo.getNombre(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(new Phrase(auxNodo.getPorcentajeAvance(), FontFactory .getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(154, 151, 151)))); pdfTable.addCell(auxNodo.getObservaciones()); } } auxNum = num; //FIN AGREGAR PADRE DE TEMA/SUBTEMA boolean banpor = true; if (num.length == 1) { pdfTable.addCell(new Phrase(filas[0] + ".- " + filas[1], FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0)))); pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))), FontFactory.getFont(FontFactory.TIMES_BOLD, 12, Font.BOLD, new Color(0, 0, 0)))); banpor = false; } if (num.length == 2) { pdfTable.addCell(new Phrase(" " + filas[0] + ".- " + filas[1])); } if (num.length == 3) { pdfTable.addCell(new Phrase(" " + filas[0] + ".- " + filas[1], FontFactory.getFont(FontFactory.TIMES_ITALIC, 12))); pdfTable.addCell(new Phrase(String.valueOf(dosDecimales(Float.parseFloat(filas[2]))), FontFactory.getFont(FontFactory.TIMES_ITALIC, 12))); banpor = false; } if (banpor) { pdfTable.addCell(String.valueOf(dosDecimales(Float.parseFloat(filas[2])))); pdfTable.addCell(filas[3]); } else { pdfTable.addCell(filas[3]); } } } else { pdfTable.addCell("No hay nada seleccionado"); pdfTable.addCell(""); pdfTable.addCell(""); } pdfTable.setHorizontalAlignment(15); float[] columnWidths2 = new float[] { 32f, 8f, 14f }; pdfTable.setWidths(columnWidths2); pdf.add(pdfTable); //---------------------------------------------------------------------- }
From source file:optika.sql.java
public void eksportoNePdf(String id) { Document document = new Document() { };//from w w w. j a v a2 s. c o m try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("receta.pdf")); document.open(); document.setPageSize(PageSize.A3); Image img = Image.getInstance("receta.jpg"); img.setAbsolutePosition(450f, 10f); img.scaleToFit(600, 849); img.setAlignment(Image.LEFT | Image.ALIGN_BOTTOM | Image.ALIGN_BASELINE); img.setAbsolutePosition(0, 0); document.add(img); String[][] receta = merrReceten("select * from recetat where id=" + parseInt(id) + ";"); String[][] tabela = merrReceten("select * from tabela where recetat_id=" + parseInt(id) + ";"); int[] white = new int[tabela.length]; for (int i = 0; i < tabela.length; i++) { white[i] = 0; int bosh = 0; for (int j = 3; j < tabela[i].length; j++) { if (tabela[i][j] == tabela[i][6]) { continue; } if (!tabela[i][j].isEmpty()) { bosh = 1; } } if (bosh == 0) { white[i] = 1; } } Paragraph data = new Paragraph("Data: " + receta[0][7]); data.setSpacingBefore(38); data.setSpacingAfter(40); PdfPTable table = new PdfPTable(7); if (white[0] == 0) { table.addCell(getCellPadding("" + tabela[0][3], 1)); } else { table.addCell(getCellWhite("_", 1, 30)); } table.addCell(getCellPadding("" + tabela[0][4], 1)); table.addCell(getCellPadding("" + tabela[0][5], 1)); table.addCell(getCellPadding("", 1)); table.addCell(getCellPadding("" + tabela[0][7], 1)); table.addCell(getCellPadding("" + tabela[0][8], 1)); table.addCell(getCellPadding("" + tabela[0][9], 1)); table.setWidthPercentage(105); table.setHorizontalAlignment(-100); if (white[1] == 0) { table.addCell(getCellPadding("" + tabela[1][3], 1)); } else { table.addCell(getCellWhite("_", 1, 36)); } table.addCell(getCellPadding("" + tabela[1][4], 1)); table.addCell(getCellPadding("" + tabela[1][5], 1)); table.addCell(getCellPadding("", 1)); table.addCell(getCellPadding("" + tabela[1][7], 1)); table.addCell(getCellPadding("" + tabela[1][8], 1)); table.addCell(getCellPadding("" + tabela[1][9], 1)); table.setWidthPercentage(105); table.setHorizontalAlignment(-100); if (white[2] == 0) { if (white[1] == 0) { table.addCell(getCell("" + tabela[2][3], 1, 30)); } else { table.addCell(getCellWhite("_", 1, 23)); } } else { table.addCell(getCellWhite("_", 1, 28)); } table.addCell(getCell("" + tabela[2][4], 1, 0)); table.addCell(getCell("" + tabela[2][5], 1, 0)); table.addCell(getCell("", 1, 0)); table.addCell(getCell("" + tabela[2][7], 1, 0)); table.addCell(getCell("" + tabela[2][8], 1, 0)); table.addCell(getCell("" + tabela[2][9], 1, 0)); table.setWidthPercentage(105); table.setSpacingBefore(27); table.setHorizontalAlignment(-100); String[][] distanca = merrReceten("select * from distanca where recetat_id=" + parseInt(id) + ";"); PdfPTable largAfer = new PdfPTable(3); if (distanca[0][3].isEmpty()) { PdfPCell larg = getCellWhite("_", 2, 15); largAfer.addCell(larg); } else { PdfPCell larg = new PdfPCell(new Phrase("" + distanca[0][3])); larg.setPadding(0); larg.setHorizontalAlignment(2); larg.setBorder(PdfPCell.NO_BORDER); larg.setPaddingBottom(20); largAfer.addCell(larg); } largAfer.addCell(getCell("", PdfPCell.ALIGN_RIGHT, 25)); if (distanca[0][8].isEmpty()) { largAfer.addCell(getCellWhite("_", PdfPCell.ALIGN_RIGHT, 15)); } else { largAfer.addCell(getCell("" + distanca[0][8], PdfPCell.ALIGN_RIGHT, 25)); } largAfer.setWidthPercentage(75); largAfer.setHorizontalAlignment(350); PdfPTable od_os = new PdfPTable(5); od_os.addCell(getCell("OD= " + distanca[0][4], 0, 195)); od_os.addCell(getCell("OS= " + distanca[0][5], 2, 195)); od_os.addCell(getCell("", 0, 0)); od_os.addCell(getCell("OD= " + distanca[0][9], 0, 0)); od_os.addCell(getCell("OS= " + distanca[0][10], 1, 0)); od_os.setWidthPercentage(90); od_os.setHorizontalAlignment(150); PdfPTable visusi = new PdfPTable(2); if (distanca[0][6].isEmpty()) { PdfPCell od_pa = getCellWhite("_", 2, 17); od_pa.setPaddingRight(45); visusi.addCell(od_pa); } else { PdfPCell od_pa = getCell(distanca[0][6], 2, 17); od_pa.setPaddingRight(45); visusi.addCell(od_pa); } if (distanca[0][11].isEmpty()) { visusi.addCell(getCellWhite("_", 2, 17)); } else { visusi.addCell(getCell(distanca[0][11], 2, 17)); } if (distanca[0][7].isEmpty()) { PdfPCell os_pa = getCellWhite("_", 2, 17); os_pa.setPaddingRight(45); visusi.addCell(os_pa); } else { PdfPCell os_pa = getCell(distanca[0][7], 2, 17); os_pa.setPaddingRight(45); visusi.addCell(os_pa); } if (distanca[0][12].isEmpty()) { visusi.addCell(getCellWhite("_", 2, 17)); } else { visusi.addCell(getCell(distanca[0][12], 2, 0)); } visusi.setWidthPercentage(100); visusi.setHorizontalAlignment(50); String[][] admin = merrReceten("select * from admin where id=1;"); PdfPTable klienti = new PdfPTable(3); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("Emri: " + receta[0][2], 0, 0)); klienti.addCell(getCell("Celular: " + admin[0][4], 0, 0)); klienti.addCell(getCell("", 0, 0)); PdfPCell celReceta = getCell("Celular: " + receta[0][4], 0, 0); celReceta.setPaddingTop(5); klienti.addCell(celReceta); klienti.addCell(getCell("Email: " + admin[0][5], 0, 0)); klienti.addCell(getCell("", 0, 0)); PdfPCell emailReceta = getCell("Email: " + receta[0][5], 0, 0); emailReceta.setPaddingBottom(5); emailReceta.setPaddingTop(5); klienti.addCell(emailReceta); klienti.addCell(getCell("Adresa: " + admin[0][6], 0, 0)); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("Adresa: " + receta[0][6], 0, 0)); klienti.setSpacingBefore(50); PdfPTable kreu = new PdfPTable(1); kreu.addCell(getCell(" ", 0, 0)); document.add(kreu); document.add(klienti); document.add(data); document.add(table); document.add(largAfer); document.add(od_os); document.add(visusi); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); }
From source file:org.apache.ofbiz.content.compdoc.CompDocServices.java
License:Apache License
public static Map<String, Object> renderCompDocPdf(DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Locale locale = (Locale) context.get("locale"); String rootDir = (String) context.get("rootDir"); String webSiteId = (String) context.get("webSiteId"); String https = (String) context.get("https"); Delegator delegator = dctx.getDelegator(); String contentId = (String) context.get("contentId"); String contentRevisionSeqId = (String) context.get("contentRevisionSeqId"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try {/* w w w. ja v a 2s. co m*/ List<EntityCondition> exprList = new LinkedList<EntityCondition>(); exprList.add(EntityCondition.makeCondition("contentIdTo", EntityOperator.EQUALS, contentId)); exprList.add( EntityCondition.makeCondition("contentAssocTypeId", EntityOperator.EQUALS, "COMPDOC_PART")); exprList.add(EntityCondition.makeCondition("rootRevisionContentId", EntityOperator.EQUALS, contentId)); if (UtilValidate.isNotEmpty(contentRevisionSeqId)) { exprList.add(EntityCondition.makeCondition("contentRevisionSeqId", EntityOperator.LESS_THAN_EQUAL_TO, contentRevisionSeqId)); } List<GenericValue> compDocParts = EntityQuery.use(delegator) .select("rootRevisionContentId", "itemContentId", "maxRevisionSeqId", "contentId", "dataResourceId", "contentIdTo", "contentAssocTypeId", "fromDate", "sequenceNum") .from("ContentAssocRevisionItemView").where(exprList).orderBy("sequenceNum").filterByDate() .queryList(); ByteArrayOutputStream baos = new ByteArrayOutputStream(); Document document = new Document(); document.setPageSize(PageSize.LETTER); PdfCopy writer = new PdfCopy(document, baos); document.open(); int pgCnt = 0; for (GenericValue contentAssocRevisionItemView : compDocParts) { String thisDataResourceId = contentAssocRevisionItemView.getString("dataResourceId"); GenericValue dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", thisDataResourceId).queryOne(); String inputMimeType = null; if (dataResource != null) { inputMimeType = dataResource.getString("mimeTypeId"); } byte[] inputByteArray = null; PdfReader reader = null; if (inputMimeType != null && inputMimeType.equals("application/pdf")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); reader = new PdfReader(inputByteArray); } else if (inputMimeType != null && inputMimeType.equals("text/html")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, thisDataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); String s = new String(inputByteArray); Debug.logInfo("text/html string:" + s, module); continue; } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) { String surveyResponseId = dataResource.getString("relatedDetailId"); String surveyId = null; String acroFormContentId = null; GenericValue surveyResponse = null; if (UtilValidate.isNotEmpty(surveyResponseId)) { surveyResponse = EntityQuery.use(delegator).from("SurveyResponse") .where("surveyResponseId", surveyResponseId).queryOne(); if (surveyResponse != null) { surveyId = surveyResponse.getString("surveyId"); } } if (UtilValidate.isNotEmpty(surveyId)) { GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId) .queryOne(); if (survey != null) { acroFormContentId = survey.getString("acroFormContentId"); if (UtilValidate.isNotEmpty(acroFormContentId)) { // TODO: is something supposed to be done here? } } } if (surveyResponse != null) { if (UtilValidate.isEmpty(acroFormContentId)) { // Create AcroForm PDF Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyId)); if (ServiceUtil.isError(survey2PdfResults)) { return ServiceUtil.returnError(UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } else { // Fill in acroForm Map<String, Object> survey2AcroFieldResults = dispatcher.runSync( "setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId)); if (ServiceUtil.isError(survey2AcroFieldResults)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); reader = new PdfReader(inputByteArray); } } } else { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale)); } if (reader != null) { int n = reader.getNumberOfPages(); for (int i = 0; i < n; i++) { PdfImportedPage pg = writer.getImportedPage(reader, i + 1); writer.addPage(pg); pgCnt++; } } } document.close(); ByteBuffer outByteBuffer = ByteBuffer.wrap(baos.toByteArray()); Map<String, Object> results = ServiceUtil.returnSuccess(); results.put("outByteBuffer", outByteBuffer); return results; } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } catch (IOException e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, "Error in CompDoc operation: ", module); return ServiceUtil.returnError(e.toString()); } }
From source file:org.apache.ofbiz.content.compdoc.CompDocServices.java
License:Apache License
public static Map<String, Object> renderContentPdf(DispatchContext dctx, Map<String, ? extends Object> context) { LocalDispatcher dispatcher = dctx.getDispatcher(); Map<String, Object> results = ServiceUtil.returnSuccess(); String dataResourceId = null; Locale locale = (Locale) context.get("locale"); String rootDir = (String) context.get("rootDir"); String webSiteId = (String) context.get("webSiteId"); String https = (String) context.get("https"); Delegator delegator = dctx.getDelegator(); String contentId = (String) context.get("contentId"); String contentRevisionSeqId = (String) context.get("contentRevisionSeqId"); GenericValue userLogin = (GenericValue) context.get("userLogin"); try {/*from w w w . j a v a 2s .c o m*/ Document document = new Document(); document.setPageSize(PageSize.LETTER); document.open(); GenericValue dataResource = null; if (UtilValidate.isEmpty(contentRevisionSeqId)) { GenericValue content = EntityQuery.use(delegator).from("Content").where("contentId", contentId) .cache().queryOne(); dataResourceId = content.getString("dataResourceId"); Debug.logInfo("SCVH(0b)- dataResourceId:" + dataResourceId, module); dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).queryOne(); } else { GenericValue contentRevisionItem = EntityQuery.use(delegator).from("ContentRevisionItem") .where("contentId", contentId, "itemContentId", contentId, "contentRevisionSeqId", contentRevisionSeqId) .cache().queryOne(); if (contentRevisionItem == null) { throw new ViewHandlerException("ContentRevisionItem record not found for contentId=" + contentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId); } Debug.logInfo("SCVH(1)- contentRevisionItem:" + contentRevisionItem, module); Debug.logInfo("SCVH(2)-contentId=" + contentId + ", contentRevisionSeqId=" + contentRevisionSeqId + ", itemContentId=" + contentId, module); dataResourceId = contentRevisionItem.getString("newDataResourceId"); Debug.logInfo("SCVH(3)- dataResourceId:" + dataResourceId, module); dataResource = EntityQuery.use(delegator).from("DataResource") .where("dataResourceId", dataResourceId).queryOne(); } String inputMimeType = null; if (dataResource != null) { inputMimeType = dataResource.getString("mimeTypeId"); } byte[] inputByteArray = null; if (inputMimeType != null && inputMimeType.equals("application/pdf")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); } else if (inputMimeType != null && inputMimeType.equals("text/html")) { ByteBuffer byteBuffer = DataResourceWorker.getContentAsByteBuffer(delegator, dataResourceId, https, webSiteId, locale, rootDir); inputByteArray = byteBuffer.array(); String s = new String(inputByteArray); Debug.logInfo("text/html string:" + s, module); } else if (inputMimeType != null && inputMimeType.equals("application/vnd.ofbiz.survey.response")) { String surveyResponseId = dataResource.getString("relatedDetailId"); String surveyId = null; String acroFormContentId = null; GenericValue surveyResponse = null; if (UtilValidate.isNotEmpty(surveyResponseId)) { surveyResponse = EntityQuery.use(delegator).from("SurveyResponse") .where("surveyResponseId", surveyResponseId).queryOne(); if (surveyResponse != null) { surveyId = surveyResponse.getString("surveyId"); } } if (UtilValidate.isNotEmpty(surveyId)) { GenericValue survey = EntityQuery.use(delegator).from("Survey").where("surveyId", surveyId) .queryOne(); if (survey != null) { acroFormContentId = survey.getString("acroFormContentId"); if (UtilValidate.isNotEmpty(acroFormContentId)) { // TODO: is something supposed to be done here? } } } if (surveyResponse != null) { if (UtilValidate.isEmpty(acroFormContentId)) { // Create AcroForm PDF Map<String, Object> survey2PdfResults = dispatcher.runSync("buildPdfFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId)); if (ServiceUtil.isError(survey2PdfResults)) { return ServiceUtil.returnError( UtilProperties.getMessage(resource, "ContentSurveyErrorBuildingPDF", locale), null, null, survey2PdfResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2PdfResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); } else { // Fill in acroForm Map<String, Object> survey2AcroFieldResults = dispatcher.runSync( "setAcroFieldsFromSurveyResponse", UtilMisc.toMap("surveyResponseId", surveyResponseId)); if (ServiceUtil.isError(survey2AcroFieldResults)) { return ServiceUtil .returnError( UtilProperties.getMessage(resource, "ContentSurveyErrorSettingAcroFields", locale), null, null, survey2AcroFieldResults); } ByteBuffer outByteBuffer = (ByteBuffer) survey2AcroFieldResults.get("outByteBuffer"); inputByteArray = outByteBuffer.array(); } } } else { return ServiceUtil .returnError(UtilProperties.getMessage(resource, "ContentMimeTypeNotSupported", locale)); } ByteBuffer outByteBuffer = ByteBuffer.wrap(inputByteArray); results.put("outByteBuffer", outByteBuffer); } catch (GenericEntityException e) { return ServiceUtil.returnError(e.toString()); } catch (IOException e) { Debug.logError(e, "Error in PDF generation: ", module); return ServiceUtil.returnError(e.toString()); } catch (Exception e) { Debug.logError(e, "Error in PDF generation: ", module); return ServiceUtil.returnError(e.toString()); } return results; }
From source file:org.eclipse.birt.report.engine.emitter.pdf.PDFPage.java
License:Open Source License
public PDFPage(int pageWidth, int pageHeight, Document document, PdfWriter writer, PDFPageDevice pageDevice) { super(pageWidth, pageHeight); this.writer = writer; this.pageDevice = pageDevice; this.containerHeight = this.pageHeight; Rectangle pageSize = new Rectangle(this.pageWidth, this.pageHeight); document.setPageSize(pageSize); if (!document.isOpen()) document.open();//w ww.j a va 2 s. c om else document.newPage(); this.contentByte = writer.getDirectContent(); }
From source file:org.efaps.esjp.common.file.FileUtil_Base.java
License:Apache License
/** * Resize.//from w w w .ja va 2s. c o m * * @param _parameter Parameter as passed by the eFaps API * @param _file the file * @param _fileName the file name * @param _pageSize the page size * @return the file * @throws EFapsException on error */ public File resizePdf(final Parameter _parameter, final File _file, final String _fileName, final String _pageSize) throws EFapsException { final Document document = new Document(); final File ret = getFile(_fileName, "pdf"); try { final File destFile = new File(_file.getPath() + ".tmp"); FileUtils.copyFile(_file, destFile); final OutputStream outputStream = new FileOutputStream(ret); final PdfReader pdfReader = new PdfReader(new FileInputStream(destFile)); // Create a writer for the outputstream final PdfWriter writer = PdfWriter.getInstance(document, outputStream); document.open(); PdfImportedPage page; final PdfContentByte cb = writer.getDirectContent(); int pageOfCurrentReaderPDF = 0; // Create a new page in the target for each source page. while (pageOfCurrentReaderPDF < pdfReader.getNumberOfPages()) { document.newPage(); pageOfCurrentReaderPDF++; page = writer.getImportedPage(pdfReader, pageOfCurrentReaderPDF); document.setPageSize(page.getWidth() <= page.getHeight() ? PageSize.getRectangle(_pageSize) : PageSize.getRectangle(_pageSize).rotate()); final float widthFactor = document.getPageSize().getWidth() / page.getWidth(); final float heightFactor = document.getPageSize().getHeight() / page.getHeight(); final float factor = Math.min(widthFactor, heightFactor); final float offsetX = (document.getPageSize().getWidth() - page.getWidth() * factor) / 2; final float offsetY = (document.getPageSize().getHeight() - page.getHeight() * factor) / 2; cb.addTemplate(page, factor, 0, 0, factor, offsetX, offsetY); } pageOfCurrentReaderPDF = 0; outputStream.flush(); document.close(); outputStream.close(); } catch (final FileNotFoundException e) { LOG.error("FileNotFoundException", e); } catch (final IOException e) { LOG.error("IOException", e); } catch (final DocumentException e) { LOG.error("DocumentException", e); } return ret; }