List of usage examples for com.lowagie.text Document topMargin
public float topMargin()
From source file:org.goodoldai.jeff.report.pdf.PDFImageChunkBuilder.java
License:Open Source License
/** * This method transforms an image explanation chunk into a PDF report * piece and writes this piece into the provided output stream which is, in * this case, an instance of com.lowagie.text.Document. The method first * collects all general chunk data (context, rule, group, tags) and inserts * them into the report, and then retrieves the chunk content. Since the * content is, in this case, an ImageData instance, the image it relates to * (caption and URL) gets inserted into the report. If the image caption is * missing, it doesn't get inserted into the report. * * @param echunk image explanation chunk that needs to be transformed * @param stream output stream to which the transformed chunk will be * written as output (in this case com.lowagie.text.Document) * @param insertHeaders denotes if chunk headers should be inserted into the * report (true) or not (false)/*w ww . ja v a2 s . co m*/ * * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are * null, if the entered chunk is not an ImageExplanationChunk instance or * if the entered output stream type is not com.lowagie.text.Document */ public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) { if (echunk == null) { throw new ExplanationException("The entered chunk must not be null"); } if (stream == null) { throw new ExplanationException("The entered stream must not be null"); } if (!(echunk instanceof ImageExplanationChunk)) { throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance"); } if (!(stream instanceof com.lowagie.text.Document)) { throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance"); } com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream); //Insert general chunk data if (insertHeaders) PDFChunkUtility.insertChunkHeader(echunk, doc); try { //Insert content - in this case an image ImageData imdata = (ImageData) (echunk.getContent()); //Get image data Image img = Image.getInstance(getClass().getResource(imdata.getURL())); //Scale the image in order to fit the page img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()), doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin())); //Add image doc.add(img); //If a caption is present, insert it below the image if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) { doc.add(new Paragraph("IMAGE: " + imdata.getCaption())); } } catch (NullPointerException e) { throw new ExplanationException( "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found"); } catch (Exception e) { throw new ExplanationException(e.getMessage()); } }
From source file:org.goodoldai.jeff.report.pdf.RTFImageChunkBuilder.java
License:Open Source License
/** * This method transforms an image explanation chunk into a PDF report * piece and writes this piece into the provided output stream which is, in * this case, an instance of com.lowagie.text.Document. The method first * collects all general chunk data (context, rule, group, tags) and inserts * them into the report, and then retrieves the chunk content. Since the * content is, in this case, an ImageData instance, the image it relates to * (caption and URL) gets inserted into the report. If the image caption is * missing, it doesn't get inserted into the report. * * @param echunk image explanation chunk that needs to be transformed * @param stream output stream to which the transformed chunk will be * written as output (in this case com.lowagie.text.Document) * @param insertHeaders denotes if chunk headers should be inserted into the * report (true) or not (false)/*from w w w . j a va 2 s.com*/ * * @throws org.goodoldai.jeff.explanation.ExplanationException if any of the arguments are * null, if the entered chunk is not an ImageExplanationChunk instance or * if the entered output stream type is not com.lowagie.text.Document */ public void buildReportChunk(ExplanationChunk echunk, Object stream, boolean insertHeaders) { if (echunk == null) { throw new ExplanationException("The entered chunk must not be null"); } if (stream == null) { throw new ExplanationException("The entered stream must not be null"); } if (!(echunk instanceof ImageExplanationChunk)) { throw new ExplanationException("The entered chunk must be an ImageExplanationChunk instance"); } if (!(stream instanceof com.lowagie.text.Document)) { throw new ExplanationException("The entered stream must be a com.lowagie.text.Document instance"); } com.lowagie.text.Document doc = ((com.lowagie.text.Document) stream); //Insert general chunk data if (insertHeaders) RTFChunkUtility.insertChunkHeader(echunk, doc); try { //Insert content - in this case an image ImageData imdata = (ImageData) (echunk.getContent()); //Get image data Image img = Image.getInstance(getClass().getResource(imdata.getURL())); //Scale the image in order to fit the page img.scaleToFit(doc.getPageSize().getRight(doc.leftMargin() + doc.rightMargin()), doc.getPageSize().getTop(doc.topMargin() + doc.bottomMargin())); //Add image doc.add(img); //If a caption is present, insert it below the image if ((imdata.getCaption() != null) && (!imdata.getCaption().equals(""))) { doc.add(new Paragraph("IMAGE: " + imdata.getCaption())); } } catch (NullPointerException e) { throw new ExplanationException( "The image '" + ((ImageData) (echunk.getContent())).getURL() + "' could not be found"); } catch (Exception e) { throw new ExplanationException(e.getMessage()); } }
From source file:org.revager.export.PDFPageEventHelper.java
License:Open Source License
@Override public void onEndPage(PdfWriter writer, Document document) { int columnNumber; try {//from ww w .ja v a2 s . co m Rectangle page = document.getPageSize(); float pageWidth = page.getWidth() - document.leftMargin() - document.rightMargin(); /* * Write marks */ setMarks(writer, document); /* * Define fonts */ headBaseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.EMBEDDED); Font headFont = new Font(headBaseFont, headFontSize); footBaseFont = BaseFont.createFont(BaseFont.HELVETICA_OBLIQUE, BaseFont.CP1252, BaseFont.EMBEDDED); Font footFont = new Font(footBaseFont, footFontSize); /* * Cell fill for space between head/foot and content */ PdfPCell cellFill = new PdfPCell(); cellFill.setMinimumHeight(PDFTools.cmToPt(0.8f)); cellFill.setBorderWidth(0); /* * Write head */ if (headLogoPath != null) { columnNumber = 2; } else { columnNumber = 1; } PdfPTable head = new PdfPTable(columnNumber); Phrase phraseTitle = new Phrase(headTitle, headFont); PdfPCell cellTitle = new PdfPCell(phraseTitle); cellTitle.setHorizontalAlignment(Element.ALIGN_LEFT); cellTitle.setVerticalAlignment(Element.ALIGN_BOTTOM); cellTitle.setPaddingTop(0); cellTitle.setPaddingBottom(PDFTools.cmToPt(0.2f)); cellTitle.setPaddingLeft(0); cellTitle.setPaddingRight(0); cellTitle.setBorderWidthTop(0); cellTitle.setBorderWidthBottom(0.5f); cellTitle.setBorderWidthLeft(0); cellTitle.setBorderWidthRight(0); head.addCell(cellTitle); if (headLogoPath != null) { Image headLogo = Image.getInstance(headLogoPath); headLogo.scaleToFit(PDFTools.cmToPt(5.0f), PDFTools.cmToPt(1.1f)); PdfPCell cellLogo = new PdfPCell(headLogo); cellLogo.setHorizontalAlignment(Element.ALIGN_RIGHT); cellLogo.setVerticalAlignment(Element.ALIGN_BOTTOM); cellLogo.setPaddingTop(0); cellLogo.setPaddingBottom(PDFTools.cmToPt(0.15f)); cellLogo.setPaddingLeft(0); cellLogo.setPaddingRight(0); cellLogo.setBorderWidthTop(0); cellLogo.setBorderWidthBottom(0.5f); cellLogo.setBorderWidthLeft(0); cellLogo.setBorderWidthRight(0); head.addCell(cellLogo); head.addCell(cellFill); } head.addCell(cellFill); head.setTotalWidth(pageWidth); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); /* * Write foot */ if (footText == null) { footText = " "; } PdfPTable foot = new PdfPTable(1); foot.addCell(cellFill); PdfPCell cellFootText = new PdfPCell(new Phrase(footText, footFont)); cellFootText.setHorizontalAlignment(Element.ALIGN_RIGHT); cellFootText.setVerticalAlignment(Element.ALIGN_TOP); cellFootText.setPaddingTop(PDFTools.cmToPt(0.15f)); cellFootText.setPaddingBottom(0); cellFootText.setPaddingLeft(0); cellFootText.setPaddingRight(0); cellFootText.setBorderWidthTop(0.5f); cellFootText.setBorderWidthBottom(0); cellFootText.setBorderWidthLeft(0); cellFootText.setBorderWidthRight(0); foot.addCell(cellFootText); /* * Print page numbers */ PdfContentByte contentByte = writer.getDirectContent(); contentByte.saveState(); String text = MessageFormat.format(translate("Page {0} of") + " ", writer.getPageNumber()); float textSize = footBaseFont.getWidthPoint(text, footFontSize); float textBase = document.bottom() - PDFTools.cmToPt(1.26f); contentByte.beginText(); contentByte.setFontAndSize(footBaseFont, footFontSize); float adjust; if (footText.trim().equals("")) { adjust = (pageWidth / 2) - (textSize / 2) - footBaseFont.getWidthPoint("0", footFontSize); } else { adjust = 0; } contentByte.setTextMatrix(document.left() + adjust, textBase); contentByte.showText(text); contentByte.endText(); contentByte.addTemplate(template, document.left() + adjust + textSize, textBase); contentByte.stroke(); contentByte.restoreState(); foot.setTotalWidth(pageWidth); foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); } catch (Exception e) { /* * Not part of unit testing because this exception is only thrown if * an internal error occurs. */ throw new ExceptionConverter(e); } }
From source file:org.sigmah.server.report.renderer.itext.ItextChartRenderer.java
License:Open Source License
public void render(DocWriter writer, Document doc, PivotChartElement element) { try {// w w w. ja va2 s. c o m doc.add(ThemeHelper.elementTitle(element.getTitle())); ItextRendererHelper.addFilterDescription(doc, element.getContent().getFilterDescriptions()); float width = doc.getPageSize().getWidth() - doc.rightMargin() - doc.leftMargin(); float height = (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) / 3f; if (writer instanceof PdfWriter) { // We can render the chart directly as vector graphics // in the PDF file PdfWriter pdfWriter = (PdfWriter) writer; PdfContentByte cb = pdfWriter.getDirectContent(); Graphics2D g2d = cb.createGraphics(width, height); chartRenderer.render(element, false, g2d, (int) width, (int) height, 72); g2d.dispose(); } else { // For RTF/Html we embed as a GIF width = width / 72f * RESOLUTION; height = height / 72f * RESOLUTION; BufferedImage chartImage = chartRenderer.renderImage(element, false, (int) width, (int) height, RESOLUTION); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(chartImage, "GIF", baos); Image image = Image.getInstance(baos.toByteArray()); image.scalePercent(72f / RESOLUTION * 100f); doc.add(image); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * @param texto//from w ww . j av a 2s. c o m * Texto a colocar * @param textoQR * Imagen QR a colocar * @param codFirma * Cdigo de Firma a generar. * @param url Url del servicio de verificacin desde donde se puede descargar el documento. * @param document * Documeto destino * @param pageSize * Tamao de la pgina * @return * @throws BadElementException * @throws MalformedURLException * @throws IOException * @throws DocumentException * @throws ExcepcionErrorInterno */ private static float addContent(String texto, String url, String textoQR, String codFirma, Document document, Rectangle pageSize, boolean completo, boolean isSellado) throws BadElementException, MalformedURLException, IOException, DocumentException, ExcepcionErrorInterno { Image imagenCabezera = null; float widthCabecera = 0; float heightCabecera = 0; if (!isSellado) { // Recuperamos la imagen de cabecera imagenCabezera = Image.getInstance(QRCodeUtil.class.getResource(IMAGE_CABECERA)); // Colocamos la imagen en la zona superior de la pgina imagenCabezera.setAbsolutePosition(0, pageSize.getHeight() - imagenCabezera.getHeight()); heightCabecera = imagenCabezera.getHeight(); widthCabecera = imagenCabezera.getWidth(); } // Recuperamos el pie de firma Image imagenQR = Image.getInstance(QRCodeUtil.getInstance().generate(texto, url, textoQR, codFirma)); float rescalado = pageSize.getWidth() / (widthCabecera + document.leftMargin() + document.rightMargin()); float sizeCabecera = 0; if (rescalado < 1f && !isSellado) { // Requiere rescalado, la imagen es mayor que la pgina. imagenCabezera.scalePercent(rescalado * 100); sizeCabecera = rescalado * imagenCabezera.getHeight(); } float sizeCabecerayPie = HEIGHT_QR_CODE_PDF + sizeCabecera + document.bottomMargin() + document.topMargin() + SPACE_SEPARACION; // float escaleQR = HEIGHT_QR_CODE_PDF / (imagenQR.getHeight() + 5); float escaleQR = (pageSize.getWidth() - document.leftMargin() - document.rightMargin()) / (imagenQR.getWidth() + 6); // imagen.setSpacingAfter(120); if (!isSellado) { document.add(imagenCabezera); } // Aadimos una caja de texto si estamos mostrando el contenido del // fichero firmado. if (completo) { // Aadimos el espacio ocupado por la imagen Paragraph p = new Paragraph(""); p.setSpacingAfter(heightCabecera * rescalado); document.add(p); // Aadimos una tabla con borde donde colocar el documento. PdfPTable table = new PdfPTable(1); table.setWidthPercentage(100); table.getDefaultCell().setBorderWidth(10); PdfPCell celda = new PdfPCell(); celda.setFixedHeight(pageSize.getHeight() - sizeCabecerayPie); table.addCell(celda); table.setSpacingAfter(SPACE_SEPARACION); document.add(table); } if (completo) { // La imagen la colocamos justo debajo imagenQR.setAbsolutePosition(document.leftMargin(), escaleQR * HEIGHT_QR_CODE_PDF - SPACE_SEPARACION * 2); } else { imagenQR.setAbsolutePosition(document.leftMargin(), pageSize.getHeight() - sizeCabecerayPie); } imagenQR.scalePercent(escaleQR * 100); document.add(imagenQR); return sizeCabecerayPie; }
From source file:org.viafirma.util.QRCodeUtil.java
License:Apache License
/** * Genera un documento sellado en fichero pdf. * /* w ww . j a v a 2 s .c om*/ * @param input * Fichero pdf de entrada * @param texto * @param textoQR * @param codFirma * @param out * @throws ExcepcionErrorInterno */ public void firmarPDFSellado(InputStream input, String texto, String texto2Line, String textoQR, String codFirma, OutputStream out) throws ExcepcionErrorInterno { // leemos el pdf utilizando iText. try { // Recuperamos el documento original PdfReader reader = new PdfReader(input); // Obtenemos el tamao de la pgina Rectangle pageSize = reader.getPageSize(1); // Creamos un nuevo documento del mismo tamao que el original Document document = new Document(pageSize); // creo una instancia para escritura en el documento PdfWriter writer = PdfWriter.getInstance(document, out); document.open(); // Aadimos al documento la imagen de cabecera y de pie float altoCabeceraYPie = addContent(texto, texto2Line, textoQR, codFirma, document, pageSize, true, true); altoCabeceraYPie = altoCabeceraYPie + document.topMargin(); // insertamos la portada del documento que estamos firmando. float escala = (pageSize.getHeight() - altoCabeceraYPie) / pageSize.getHeight(); PdfContentByte cb = writer.getDirectContent(); PdfImportedPage portada = writer.getImportedPage(reader, 1); cb.setRGBColorStroke(0xCC, 0xCC, 0xCC); cb.transform(AffineTransform.getScaleInstance(escala, escala)); cb.transform(AffineTransform.getTranslateInstance(document.leftMargin() * 2.5, ALTO_ETIQUETA + document.topMargin())); cb.addTemplate(portada, 0, 0);// , escala, 0, 0, escala,dx,dy); document.close(); out.close(); } catch (Exception e) { throw new ExcepcionErrorInterno(CodigoError.ERROR_INTERNO, e); } }
From source file:org.webguitoolkit.ui.util.export.PDFEvent.java
License:Apache License
public void onEndPage(PdfWriter writer, Document document) { TableExportOptions exportOptions = wgtTable.getExportOptions(); try {//from w w w. ja v a 2 s. c o m Rectangle page = document.getPageSize(); if (exportOptions.isShowDefaultHeader() || StringUtils.isNotEmpty(exportOptions.getHeaderImage())) { PdfPTable head = new PdfPTable(3); head.getDefaultCell().setBorder(Rectangle.NO_BORDER); Paragraph title = new Paragraph(wgtTable.getTitle()); title.setAlignment(Element.ALIGN_LEFT); head.addCell(title); Paragraph empty = new Paragraph(""); head.addCell(empty); if (StringUtils.isNotEmpty(exportOptions.getHeaderImage())) { try { URL absoluteFileUrl = wgtTable.getPage().getClass() .getResource("/" + exportOptions.getHeaderImage()); if (absoluteFileUrl != null) { String path = absoluteFileUrl.getPath(); Image jpg = Image.getInstance(path); jpg.scaleAbsoluteHeight(40); jpg.scaleAbsoluteWidth(200); head.addCell(jpg); } } catch (Exception e) { logger.error(e.getMessage()); Paragraph noImage = new Paragraph("Image not found!"); head.addCell(noImage); } } else { head.addCell(empty); } head.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); head.writeSelectedRows(0, -1, document.leftMargin(), page.getHeight() - document.topMargin() + head.getTotalHeight(), writer.getDirectContent()); } if (exportOptions.isShowDefaultFooter() || StringUtils.isNotEmpty(exportOptions.getFooterText()) || exportOptions.isShowPageNumber()) { PdfPTable foot = new PdfPTable(3); String footerText = exportOptions.getFooterText() != null ? exportOptions.getFooterText() : ""; if (!exportOptions.isShowDefaultFooter()) { foot.addCell(new Paragraph(footerText)); foot.addCell(new Paragraph("")); } else { foot.getDefaultCell().setBorder(Rectangle.NO_BORDER); String leftText = ""; if (StringUtils.isNotEmpty(exportOptions.getFooterText())) { leftText = exportOptions.getFooterText(); } Paragraph left = new Paragraph(leftText); left.setAlignment(Element.ALIGN_LEFT); foot.addCell(left); DateFormat df = DateFormat.getDateTimeInstance(DateFormat.FULL, DateFormat.MEDIUM, TextService.getLocale()); Date today = new Date(); String date = df.format(today); Paragraph center = new Paragraph(date); center.setAlignment(Element.ALIGN_CENTER); foot.addCell(center); } if (exportOptions.isShowPageNumber()) { Paragraph right = new Paragraph( TextService.getString("pdf.page@Page:") + " " + writer.getPageNumber()); right.setAlignment(Element.ALIGN_LEFT); foot.addCell(right); foot.setTotalWidth(page.getWidth() - document.leftMargin() - document.rightMargin()); foot.writeSelectedRows(0, -1, document.leftMargin(), document.bottomMargin(), writer.getDirectContent()); } else { foot.addCell(new Paragraph("")); } } } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:s2s.report.Report.java
License:GNU General Public License
public Element prepareImage(Document doc, byte[] fileContent, boolean marginConsider, float distanceFromBottomMargin) { try {/*from www . j a v a 2 s. c om*/ Image img = Image.getInstance(fileContent); // Detemino le dimensioni della pagina, margini esclusi. float pageWidth = doc.getPageSize().getWidth() - (marginConsider ? doc.leftMargin() + doc.topMargin() : 0); float pageHeight = doc.getPageSize().getHeight() - (marginConsider ? doc.topMargin() + doc.bottomMargin() : 0) - (distanceFromBottomMargin > 0 ? distanceFromBottomMargin : 0); // Se l'immagine pi larga e/o pi alta della pagina, // esclusi i margini... if (img.getWidth() > pageWidth || img.getHeight() > pageHeight) { // Determino le percentuali di riduzione di entrambi le grandezze // dell'immagine (larghezza ed altezza). float reducePrecentWidth = (img.getWidth() - pageWidth) > 0 ? (pageWidth * 100) / img.getWidth() : 100; float reducePrecentHeight = (img.getHeight() - pageHeight) > 0 ? (pageHeight * 100) / img.getHeight() : 100; // Determino la percentuale di riduzione float ReducePrecent = reducePrecentWidth; ReducePrecent = reducePrecentHeight < ReducePrecent ? reducePrecentHeight : ReducePrecent; img.scalePercent(ReducePrecent); } return img; } catch (Exception ex) { // Eccezione silenziosa. // Gestisce il caso in cui l'allegato non sia un immagine ex.printStackTrace(); return null; } }