List of usage examples for com.lowagie.text.pdf ColumnText showTextAligned
public static void showTextAligned(PdfContentByte canvas, int alignment, Phrase phrase, float x, float y, float rotation)
From source file:at.reppeitsolutions.formbuilder.components.pdf.itext.ITextRadio.java
License:Open Source License
public static void addBoxDescription(Rectangle rectangle, int i, String[] values, PdfContentByte[] canvases) { Font f = new Font(); f.setSize(ITextInputText.FONTSIZE);//from www . j a va2s .c o m ColumnText.showTextAligned(canvases[0], Element.ALIGN_LEFT, new Phrase(values[i], f), 190, rectangle.getTop(i * 20) - 15, 0); }
From source file:ch.gpb.elexis.kgexporter.pdf.HeaderFooterPageEvent.java
License:Open Source License
public void onStartPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(sbHeader), rect.getLeft(), rect.getTop(), 0); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_RIGHT, new Phrase(sDate), rect.getRight(), rect.getTop(), 0); PdfContentByte cb = writer.getDirectContentUnder(); //cb.rectangle(document.left(), document.top(), // document.right() - document.left(), document.top() - 25); /*//ww w.jav a2 s . c o m System.out.println("l: " + document.left()); System.out.println("r: " + document.right()); System.out.println("t: " + document.top()); System.out.println("b: " + document.bottom()); l: 36.0 r: 559.0 t: 806.0 b: 36.0 */ //Rectangle rect2 = new Rectangle(document.top() - 36, document.top() - 36, 559, 1); /* float l = 36f; float r = 36f; float t = 559f; float b = 2f; Rectangle rect2 = new Rectangle(l, r, t, b); //Rectangle rect2 = new Rectangle(36, 36, 559, 1); rect2.setBorder(Rectangle.BOTTOM); rect2.setBorderWidth(0.5f); cb.rectangle(rect2); //cb.setColorStroke(Color.BLACK); */ /* for (int i = 30; i > 0; i--) { System.err.println((float) i / 10); cb.setLineWidth((float) i / 10); cb.moveTo(36, 806 - (5 * i)); cb.lineTo(400, 806 - (5 * i)); cb.stroke(); } cb.moveTo(10, 50); cb.lineTo(559, 50); */ cb.setLineWidth(0.5f); cb.moveTo(30, 791); cb.lineTo(559, 791); cb.stroke(); }
From source file:ch.gpb.elexis.kgexporter.pdf.HeaderFooterPageEvent.java
License:Open Source License
public void onEndPage(PdfWriter writer, Document document) { Rectangle rect = writer.getBoxSize("art"); ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_LEFT, new Phrase(this.sbFooter), rect.getLeft(), rect.getBottom(), 0); /*//ww w. j av a 2s.c o m ColumnText.showTextAligned(writer.getDirectContent(), Element.ALIGN_CENTER, new Phrase("Bottom Right"), rect.getRight(), rect.getBottom(), 0); */ PdfContentByte cb = writer.getDirectContentUnder(); cb.setLineWidth(0.5f); cb.moveTo(30, 50); cb.lineTo(559, 50); cb.stroke(); }
From source file:com.actelion.research.spiritapp.print.CagePrinterPDF.java
License:Open Source License
private static void print(PdfContentByte canvas, String txt, float x, float y, float maxX, int maxHeight, int lineHeight, String fontName, Color color, float fontSize) throws Exception { float width = maxX - x - 5; float minY = Math.min(y, y - maxHeight + lineHeight - 3); if (txt == null) return;/*from w w w . java 2s . c om*/ canvas.setFontAndSize(BaseFont.createFont(fontName, "Cp1252", false), fontSize); while (txt.length() > 0 && y >= minY) { int index = 0; while (true) { int index2 = index + 1; if (index2 >= txt.length()) { index = index2; break; } float w = canvas.getEffectiveStringWidth(txt.substring(0, index2), true); System.out.println("CagePrinterPDF.print() " + txt.substring(0, index2) + " " + w + "," + width); if (w > width) break; index = index2; } if (index < 0) index = txt.length(); String t = txt.substring(0, index); System.out.println( "CagePrinterPDF.print() " + t + " at " + x + "x" + y + " (of " + txt + ") minY=" + minY); txt = txt.substring(index).trim(); Phrase phrase = new Paragraph(t, FontFactory.getFont(fontName, fontSize, color)); ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, phrase, x, y, 0); y -= lineHeight; } }
From source file:com.actelion.research.spiritapp.ui.util.PDFUtils.java
License:Open Source License
public static void addHeader(PdfWriter writer, String header) { class MyFooter extends PdfPageEventHelper { com.lowagie.text.Font ffont; @Override//from w ww.j a va2s . co m public void onEndPage(PdfWriter writer, Document document) { try { ffont = new com.lowagie.text.Font( BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED), 6f, com.lowagie.text.Font.ITALIC); } catch (Exception e) { e.printStackTrace(); return; } String date = FormatterUtils.formatDateTime(new Date()); PdfContentByte cb = writer.getDirectContent(); ColumnText.showTextAligned(cb, Element.ALIGN_LEFT, new Phrase(header, ffont), document.left(), document.top() + 5, 0); ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, new Phrase("Page " + writer.getCurrentPageNumber(), ffont), (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 5, 0); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, new Phrase(date, ffont), document.right(), document.bottom() - 5, 0); } } writer.setPageEvent(new MyFooter()); }
From source file:com.preparatic.archivos.PdfGenerator.java
License:Apache License
@Override public void onEndPage(PdfWriter writer, Document document) { PdfContentByte cb = writer.getDirectContent(); // Phrase header = new Phrase("this is a header", ffont); // ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, // header, // (document.right() - document.left()) / 2 + document.leftMargin(), // document.top() + 10, 0); Phrase footer = new Phrase(String.format(title + ", pgina %d", pageNumber), ffont); ColumnText.showTextAligned(cb, Element.ALIGN_CENTER, footer, (document.right() - document.left()) / 2 + document.leftMargin(), document.bottom() - 10, 0); }
From source file:com.prime.report.template.TableHeader.java
/** * Fills out the total number of pages before the document is closed. * * @param writer/*from ww w. ja v a2 s . c o m*/ * @param document * @see com.itextpdf.text.pdf.PdfPageEventHelper#onCloseDocument( * com.itextpdf.text.pdf.PdfWriter, com.itextpdf.text.Document) */ @Override public void onCloseDocument(PdfWriter writer, Document document) { ColumnText.showTextAligned(total, Element.ALIGN_LEFT, new Phrase(String.valueOf(writer.getPageNumber() - 1)), 2, 2, 0); }
From source file:mitm.common.pdf.MessagePDFBuilder.java
License:Open Source License
public void buildPDF(MimeMessage message, String replyURL, OutputStream pdfStream) throws DocumentException, MessagingException, IOException { Document document = createDocument(); PdfWriter pdfWriter = createPdfWriter(document, pdfStream); document.open();//from w w w. j a v a 2 s . c o m String[] froms = null; try { froms = EmailAddressUtils.addressesToStrings(message.getFrom(), true /* mime decode */); } catch (MessagingException e) { logger.warn("From address is not a valid email address."); } if (froms != null) { for (String from : froms) { document.addAuthor(from); } } String subject = null; try { subject = message.getSubject(); } catch (MessagingException e) { logger.error("Error getting subject.", e); } if (subject != null) { document.addSubject(subject); document.addTitle(subject); } String[] tos = null; try { tos = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.TO), true /* mime decode */); } catch (MessagingException e) { logger.warn("To is not a valid email address."); } String[] ccs = null; try { ccs = EmailAddressUtils.addressesToStrings(message.getRecipients(RecipientType.CC), true /* mime decode */); } catch (MessagingException e) { logger.warn("CC is not a valid email address."); } Date sentDate = null; try { sentDate = message.getSentDate(); } catch (MessagingException e) { logger.error("Error getting sent date.", e); } Collection<Part> attachments = new LinkedList<Part>(); String body = BodyPartUtils.getPlainBodyAndAttachments(message, attachments); attachments = preprocessAttachments(attachments); if (body == null) { body = MISSING_BODY; } /* * PDF does not have tab support so we convert tabs to spaces */ body = StringReplaceUtils.replaceTabsWithSpaces(body, tabWidth); PdfPTable headerTable = new PdfPTable(2); headerTable.setHorizontalAlignment(Element.ALIGN_LEFT); headerTable.setWidthPercentage(100); headerTable.setWidths(new int[] { 1, 6 }); headerTable.getDefaultCell().setBorder(Rectangle.NO_BORDER); Font headerFont = createHeaderFont(); FontSelector headerFontSelector = createHeaderFontSelector(); PdfPCell cell = new PdfPCell(new Paragraph("From:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); String decodedFroms = StringUtils.defaultString(StringUtils.join(froms, ", ")); headerTable.addCell(headerFontSelector.process(decodedFroms)); cell = new PdfPCell(new Paragraph("To:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(tos, ", ")))); cell = new PdfPCell(new Paragraph("CC:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(StringUtils.join(ccs, ", ")))); cell = new PdfPCell(new Paragraph("Subject:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(headerFontSelector.process(StringUtils.defaultString(subject))); cell = new PdfPCell(new Paragraph("Date:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable.addCell(ObjectUtils.toString(sentDate)); cell = new PdfPCell(new Paragraph("Attachments:", headerFont)); cell.setBorder(Rectangle.NO_BORDER); cell.setHorizontalAlignment(Element.ALIGN_RIGHT); headerTable.addCell(cell); headerTable .addCell(headerFontSelector.process(StringUtils.defaultString(getAttachmentHeader(attachments)))); document.add(headerTable); if (replyURL != null) { addReplyLink(document, replyURL); } /* * Body table will contain the body of the message */ PdfPTable bodyTable = new PdfPTable(1); bodyTable.setWidthPercentage(100f); bodyTable.setSplitLate(false); bodyTable.setSpacingBefore(15f); bodyTable.setHorizontalAlignment(Element.ALIGN_LEFT); addBodyAndAttachments(pdfWriter, document, bodyTable, body, attachments); Phrase footer = new Phrase(FOOTER_TEXT); PdfContentByte cb = pdfWriter.getDirectContent(); ColumnText.showTextAligned(cb, Element.ALIGN_RIGHT, footer, document.right(), document.bottom(), 0); document.close(); }
From source file:org.jaffa.modules.printing.services.FormPrintEngineIText.java
License:Open Source License
/** * This will fill in the page with data, * m_currentPageData contains the details of the current page being printed * @throws FormPrintException Thrown if there is any form processing problems *///from w w w .java2s.c o m protected void fillPageFields() throws FormPrintException { log.debug("fillPageFields: Page=" + getCurrentPage()); try { PdfContentByte cb = m_writer.getDirectContent(); PageDetailsExtended page = (PageDetailsExtended) getCurrentPageData(); // // Test code to throw a barcode on the page... // Barcode39 code39 = new Barcode39(); // code39.setCode("CODE39-1234567890"); // code39.setStartStopText(false); // code39.setSize(0); // Image image39 = code39.createImageWithBarcode(cb, null, null); // com.lowagie.text.pdf.PdfPTable table = new com.lowagie.text.pdf.PdfPTable(2); // table.setWidthPercentage(100); // table.getDefaultCell().setBorder(com.lowagie.text.Rectangle.NO_BORDER); // table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_CENTER); // table.getDefaultCell().setVerticalAlignment(Element.ALIGN_MIDDLE); // table.getDefaultCell().setFixedHeight(70); // table.addCell("CODE 39"); // table.addCell(new Phrase(new Chunk(image39, 0, 0))); // m_generatedDoc.add(table); // //-------------------------------------------------- // Loop through each field to be inserted for (Iterator i = page.fieldList.iterator(); i.hasNext();) { String fieldname = (String) i.next(); // Get the properties for displaying this field FieldProperties props = (FieldProperties) page.fieldProperties.get(fieldname); // Get the data to display FormPrintEngine.DomValue data = new FormPrintEngine.DomValue(fieldname, props.sampleData); // Caluclate Clipping Region float x1 = Math.min(props.x1, props.x2); float x2 = Math.max(props.x1, props.x2); float y1 = Math.min(props.y1, props.y2); float y2 = Math.max(props.y1, props.y2); float w = Math.abs(props.x1 - props.x2) + 1; float h = Math.abs(props.y1 - props.y2) + 1; if (log.isDebugEnabled()) log.debug("Print Field " + fieldname + "=" + data.getObject() + " @ [(" + x1 + "," + y1 + ")->(" + x2 + "," + y2 + ")]"); // Default the font if not specified String font = BaseFont.HELVETICA; if (props.fontFace != null) font = props.fontFace; // Handle Barcodes diffently withing iText, don't just use fonts if (font.startsWith("Barcode")) { String bcClassName = "com.lowagie.text.pdf." + font; Object bcode = null; String dataStr = data.getValue(); if (dataStr != null) { log.debug("Barcode Data String = " + dataStr); // Try and create the correct Barcode Object try { Class bcClass = Class.forName(bcClassName); bcode = bcClass.newInstance(); } catch (Exception e) { String err = "Can't Create Barcode Object for barcode type '" + font + "' on field " + fieldname; log.error(err, e); } // Only continue if the barcode object was created if (bcode != null) { // Generate and Print barcode, based on common interface if (bcode instanceof Barcode) { Barcode b = (Barcode) bcode; // Set some default output a barcode b.setCode(dataStr); if (props.fontSize <= 0) { // Hide text if font size is 0, and make the barcode height the size of the box b.setBarHeight(h); b.setFont(null); } else { b.setSize(props.fontSize); // size of text under barcode b.setBarHeight(h - props.fontSize - 5); // Adjust Bar Height to allow for font size } b.setN(2); // Wide Bars // Set custom parameters setBarcodeParams(fieldname, bcode, props.style); // Print out barcode Image image = ((Barcode) bcode).createImageWithBarcode(cb, null, null); printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else // Print PDF417 barcode, not based on common interface if (bcode instanceof BarcodePDF417) { BarcodePDF417 b = (BarcodePDF417) bcode; // Set some default output a barcode b.setText(dataStr); b.setErrorLevel(5); // Set custom parameters setBarcodeParams(fieldname, bcode, props.style); log.debug("PDF417 Settings\n" + "BitColumns=" + b.getBitColumns() + "\n" + "CodeColumns=" + b.getCodeColumns() + "\n" + "CodeRows=" + b.getCodeRows() + "\n" + "ErrorLevel=" + b.getErrorLevel() + "\n" + "YHeight=" + b.getYHeight() + "\n" + "AspectRatio=" + b.getAspectRatio() + "\n" + "Options=" + b.getOptions() + "\n" + "LenCodewords=" + b.getLenCodewords()); // Print out barcode //image = b.getImage(); printImage(b.getImage(), cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else { // Error, unknown barcode String err = "Error, No print handler for barcode object " + bcode.getClass().getName(); log.error(err); //throw new EngineProcessingException(err); } } } else log.debug("SKIPPED BARCODE : No data for " + fieldname); // Handle Images differently within iText, native support for JFreeChart } else if ("image".equalsIgnoreCase(font)) { try { java.awt.Image image = data.getDomImage(); // Add an image to the page if (image != null) { if (fieldname.startsWith("watermark")) { // Add an image-based watermark to the under content layer PdfContentByte contentUnder = m_writer.getDirectContentUnder(); if (props.opacity != 1f) { PdfGState gs = new PdfGState(); gs.setFillOpacity(props.opacity); contentUnder.setGState(gs); } printImage(image, contentUnder, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } else { // Add an image to main page layer printImage(image, cb, x1, y1, x2, y2, props.align, props.fitMethod, props.rotate); } } } catch (IOException e) { // Add Error on page. Phrase text = new Phrase("Image Error", FontFactory .getFont(FontFactory.HELVETICA_BOLDOBLIQUE, 8f, 0, ColorHelper.getColor("red"))); ColumnText ct = new ColumnText(cb); ct.setSimpleColumn(text, x1, y1, x2, y2, 8f, Element.ALIGN_LEFT); } } else if (fieldname.startsWith("watermark")) { // Add a text-based watermark String text = data.getValue(); PdfContentByte contentUnder = m_writer.getDirectContentUnder(); if (props.opacity != 1f) { PdfGState gs = new PdfGState(); gs.setFillOpacity(props.opacity); contentUnder.setGState(gs); } // The text aligns (left, center, right) on the pivot point. // Default to align left. float pivotX = x1; float pivotY = y1; if (Element.ALIGN_CENTER == props.align) { pivotX = (x1 / 2) + (x2 / 2); pivotY = y1; } else if (Element.ALIGN_RIGHT == props.align) { pivotX = x2; pivotY = y1; } Phrase watermark = new Phrase(text, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(defaultWatermarkColor))); ColumnText.showTextAligned(contentUnder, props.align, watermark, pivotX, pivotY, props.rotate); } else { // Handle printing of basic Text float lineHeight = props.fontSize; String str = data.getValue(); if (str != null) { // Add a bounded column to add text to. Phrase text = new Phrase(str, FontFactory.getFont(props.fontFace, props.fontSize, decodeFontStyle(props.style), ColorHelper.getColor(props.color))); ColumnText ct = new ColumnText(cb); if (props.fitMethod == FIT_METHOD_CLIP) // set up column with height/width restrictions ct.setSimpleColumn(text, x1, y1, x2, y2, lineHeight, props.align); else // set up column without (i.e. large) height/width restrictions ct.setSimpleColumn(text, x1, y1, 1000, 0, lineHeight, props.align); ct.go(); } } // Draw outline boxes arround fields if (isTemplateMode()) { cb.setLineWidth(0.5f); cb.setLineDash(4f, 2f); cb.setColorStroke(new Color(0xA0, 0xA0, 0xA0)); cb.moveTo(x1, y1); cb.lineTo(x1, y2); cb.lineTo(x2, y2); cb.lineTo(x2, y1); cb.lineTo(x1, y1); cb.stroke(); } } // end for-loop } catch (DocumentException e) { String err = "Error printing data - " + e.getMessage(); log.error(err, e); throw new EngineProcessingException(err); // } catch (IOException e) { // String err = "Error printing data - " + e.getMessage(); // log.error(err ,e); // throw new EngineProcessingException(err); } }
From source file:org.lucee.extension.pdf.tag.PDF.java
License:Open Source License
private void doActionAddHeaderFooter(boolean isHeader) throws PageException, IOException, DocumentException { required("pdf", "write", "source", source); // required("pdf", "write", "destination", destination); /*// ww w.j av a 2s. c o m * optinal - pages */ /* * isBase64 = "yes|no" showonprint = "yes|no"> opacity = "header opacity" image = "image file name to be used as the header" * */ PDFStruct doc = toPDFDocument(source, password, null); PdfReader reader = doc.getPdfReader(); BIF bif = null; if (NUMBERFORMAT_NUMERIC != numberformat) { ClassUtil classUtil = engine.getClassUtil(); try { bif = classUtil.loadBIF(pageContext, "lucee.runtime.functions.displayFormatting.NumberFormat"); } catch (Exception e) { e.printStackTrace(); throw engine.getCastUtil().toPageException(e); } } // output stream boolean destIsSource = destination != null && doc.getResource() != null && destination.equals(doc.getResource()); OutputStream os = null; if (!Util.isEmpty(name) || destIsSource) { os = new ByteArrayOutputStream(); } else if (destination != null) { os = destination.getOutputStream(); } PdfStamper stamper = null; try { if (destination != null && destination.exists() && !overwrite) throw engine.getExceptionUtil() .createApplicationException("destination file [" + destination + "] already exists"); int len = reader.getNumberOfPages(); Set<Integer> pageSet = PDFUtil.parsePageDefinition(pages, len); stamper = new PdfStamper(reader, destination.getOutputStream()); if (font == null) font = getDefaultFont(); // , new Font(FontFamily.HELVETICA, 14) for (int p = 1; p <= len; p++) { if (pageSet != null && !pageSet.contains(p)) continue; Phrase header = text(text, p, len, numberformat, bif, font); // vertical orientation float y; if (isHeader) { y = reader.getPageSize(p).getTop(header.getFont().getCalculatedSize() + (topmargin - 3)); } else { y = reader.getPageSize(p).getBottom((bottommargin + 2)); /* * System.out.println("y:"+y); System.out.println("bottom:"+reader.getPageSize(p).getBottom()); System.out.println("margin:"+bottommargin); * System.out.println("font:"+header.getFont().getSize()); System.out.println("CalculatedStyle:"+header.getFont().getCalculatedStyle()); * System.out.println("CalculatedSize:"+header.getFont().getCalculatedSize()); */ } // float yh = reader.getPageSize(p).getTop(topmargin); // float yf = reader.getPageSize(p).getBottom(bottommargin); System.out.println("++++++++++++"); System.out.println(y); System.out.println(reader.getPageSize(p).getTop()); // horizontal orientation float x = reader.getPageSize(p).getWidth() / 2; if (Element.ALIGN_LEFT == align) { x = leftmargin; } else if (Element.ALIGN_RIGHT == align) { x = reader.getPageSize(p).getWidth() - rightmargin; } else { x = reader.getPageSize(p).getWidth() / 2; } ColumnText.showTextAligned(stamper.getOverContent(p), align, header, x, y, 0); } } finally { try { if (stamper != null) stamper.close(); } catch (IOException ioe) { } ; Util.closeEL(os); if (os instanceof ByteArrayOutputStream) { if (destination != null) engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream) os).toByteArray()), destination, true);// MUST overwrite if (!Util.isEmpty(name)) { pageContext.setVariable(name, new PDFStruct(((ByteArrayOutputStream) os).toByteArray(), password)); } } } // PdfReader pr = doc.getPdfReader(); // output /* * boolean destIsSource = doc.getResource()!=null && destination.equals(doc.getResource()); * * OutputStream os=null; if(destIsSource){ os=new ByteArrayOutputStream(); } else if(destination!=null) { os=destination.getOutputStream(); } * * try { PDFUtil.concat(new PDFStruct[]{doc}, os, true, true, true,version); } finally { Util.closeEL(os); if(os instanceof ByteArrayOutputStream) { * if(destination!=null)engine.getIOUtil().copy(new ByteArrayInputStream(((ByteArrayOutputStream)os).toByteArray()), destination,true);// MUST overwrite * } } */ }