List of usage examples for com.lowagie.text.pdf BaseFont HELVETICA
String HELVETICA
To view the source code for com.lowagie.text.pdf BaseFont HELVETICA.
Click Source Link
From source file:net.algem.contact.TeacherCtrl.java
License:Open Source License
private File getFollowUpAsPDF(String userId, String from, String to) throws IOException, BadElementException, DocumentException { String path = "/tmp/" + "suivi-" + userId + ".pdf"; File f = new File(path); LOGGER.log(Level.INFO, f.getName()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Document document = new Document(PageSize.A4.rotate()); PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open() document.open();/*from w w w.j a va 2 s. co m*/ PdfPTable table = new PdfPTable(10); table.setWidthPercentage(100); table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f }); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false); Font normalFont = new Font(bf, 10); Font boldFont = new Font(bfb, 10); String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE); String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE); String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " " + organization.get("name.label"); String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to; PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont)); headerCell.setBackgroundColor(Color.LIGHT_GRAY); headerCell.setColspan(10); table.addCell(headerCell); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("student.label", null, CTX_LOCALE), boldFont))); String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE); table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont))); List<ScheduleElement> items = getFollowUpSchedules(userId, from, to); //LOGGER.log(Level.INFO, items.toString()); for (ScheduleElement e : items) { List<ScheduleRangeElement> ranges = new ArrayList<ScheduleRangeElement>( (Collection<? extends ScheduleRangeElement>) e.getRanges()); for (ScheduleRangeElement r : ranges) { String status = CommonDao.getAbsenceFromNumberStatus(r.getFollowUp().getStatus()); String note = r.getFollowUp().getNote(); String content1 = r.getFollowUp().getContent(); String content2 = e.getFollowUp().getContent(); table.addCell(new Phrase(e.getDateFr().toString(), normalFont)); table.addCell(new Phrase(r.getStart() + "-" + r.getEnd(), normalFont)); table.addCell(new Phrase(new Hour(r.getLength()).toString(), normalFont)); table.addCell(new Phrase(e.getDetail().get("room").getName(), normalFont)); table.addCell(new Phrase(e.getDetail().get("course").getName(), normalFont)); table.addCell(new Phrase(r.getPerson().getFirstName() + " " + r.getPerson().getName(), normalFont)); table.addCell(new Phrase(status, normalFont)); table.addCell(new Phrase(note == null ? "" : note, normalFont)); table.addCell(new Phrase(content1 == null ? "" : content1.replaceAll("[\r\n]", " "), normalFont)); table.addCell(new Phrase(content2 == null ? "" : content2.replaceAll("[\r\n]", " "), normalFont)); } } document.add(table); document.close(); byte[] pdfBytes = byteArrayOutputStream.toByteArray(); Files.write(Paths.get(path), pdfBytes); return f; }
From source file:net.algem.security.UserCtrl.java
License:Open Source License
private File getFollowUpAsPDF(String userId, String from, String to) throws IOException, BadElementException, DocumentException { String path = "/tmp/" + "suivi-" + userId + ".pdf"; File f = new File(path); LOGGER.log(Level.INFO, f.getName()); ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Document document = new Document(PageSize.A4.rotate()); PdfWriter.getInstance(document, byteArrayOutputStream); // Do this BEFORE document.open() document.open();//from w w w . ja v a 2 s .c om PdfPTable table = new PdfPTable(10); table.setWidthPercentage(100); table.setWidths(new float[] { 1.1f, 1.2f, 0.6f, 1.5f, 1.5f, 2f, 0.5f, 0.5f, 1.9f, 1.9f }); BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, false); BaseFont bfb = BaseFont.createFont(BaseFont.HELVETICA_BOLD, BaseFont.WINANSI, false); Font normalFont = new Font(bf, 10); Font boldFont = new Font(bfb, 10); String fromLabel = messageSource.getMessage("from.label", null, CTX_LOCALE); String toLabel = messageSource.getMessage("to.label", null, CTX_LOCALE); String prefix = messageSource.getMessage("follow-up.label", null, CTX_LOCALE) + " " + organization.get("name.label"); String period = fromLabel.toLowerCase() + " " + from + " " + toLabel.toLowerCase() + " " + to; PdfPCell headerCell = new PdfPCell(new Phrase(prefix + " " + period, boldFont)); headerCell.setBackgroundColor(Color.LIGHT_GRAY); headerCell.setColspan(10); table.addCell(headerCell); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("date.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("time.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("time.length.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell(new Phrase(messageSource.getMessage("room.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("course.label", null, CTX_LOCALE), boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("teacher.label", null, CTX_LOCALE), boldFont))); String abs = messageSource.getMessage("absence.label", null, CTX_LOCALE); table.addCell(new PdfPCell(new Phrase(abs != null ? abs.substring(0, 3) + "." : "", boldFont))); table.addCell( new PdfPCell(new Phrase(messageSource.getMessage("score.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("individual.logbook.label", null, CTX_LOCALE), boldFont))); table.addCell(new PdfPCell( new Phrase(messageSource.getMessage("collective.comment.label", null, CTX_LOCALE), boldFont))); fillPdfTable(table, getFollowUpSchedules(userId, from, to), normalFont); document.add(table); document.close(); byte[] pdfBytes = byteArrayOutputStream.toByteArray(); Files.write(Paths.get(path), pdfBytes); return f; }
From source file:net.bull.javamelody.swing.print.AdvancedPageNumberEvents.java
License:Apache License
/** * we override the onOpenDocument method. * * @param writer/*from ww w .j av a 2s . c o m*/ * PdfWriter * @param document * Document */ @Override public void onOpenDocument(final PdfWriter writer, final Document document) { try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = writer.getDirectContent(); template = cb.createTemplate(50, 50); } catch (final DocumentException de) { throw new IllegalStateException(de); } catch (final IOException ioe) { throw new IllegalStateException(ioe); } }
From source file:net.sf.jsignpdf.utils.FontUtils.java
License:Mozilla Public License
/** * Returns BaseFont for text of visible signature; * /*www. j av a2 s .c o m*/ * @return */ public static synchronized BaseFont getL2BaseFont() { if (l2baseFont == null) { final ConfigProvider conf = ConfigProvider.getInstance(); try { final ByteArrayOutputStream tmpBaos = new ByteArrayOutputStream(); String fontPath = conf.getNotEmptyProperty("font.path", null); String fontName; String fontEncoding; InputStream tmpIs; if (fontPath != null) { fontName = conf.getNotEmptyProperty("font.name", null); if (fontName == null) { fontName = new File(fontPath).getName(); } fontEncoding = conf.getNotEmptyProperty("font.encoding", null); if (fontEncoding == null) { fontEncoding = BaseFont.WINANSI; } tmpIs = new FileInputStream(fontPath); } else { fontName = Constants.L2TEXT_FONT_NAME; fontEncoding = BaseFont.IDENTITY_H; tmpIs = FontUtils.class.getResourceAsStream(Constants.L2TEXT_FONT_PATH); } IOUtils.copy(tmpIs, tmpBaos); tmpIs.close(); tmpBaos.close(); l2baseFont = BaseFont.createFont(fontName, fontEncoding, BaseFont.EMBEDDED, BaseFont.CACHED, tmpBaos.toByteArray(), null); } catch (Exception e) { e.printStackTrace(); try { l2baseFont = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); } catch (Exception ex) { // where is the problem, dear Watson? } } } return l2baseFont; }
From source file:org.allcolor.yahp.cl.converter.CDocumentReconstructor.java
License:Open Source License
/** * construct a pdf document from pdf parts. * //from w w w .ja v a2 s .c om * @param files * list containing the pdf to assemble * @param properties * converter properties * @param fout * outputstream to write the new pdf * @param base_url * base url of the document * @param producer * producer of the pdf * * @throws CConvertException * if an error occured while reconstruct. */ public static void reconstruct(final List files, final Map properties, final OutputStream fout, final String base_url, final String producer, final PageSize[] size, final List hf) throws CConvertException { OutputStream out = fout; OutputStream out2 = fout; boolean signed = false; OutputStream oldOut = null; File tmp = null; File tmp2 = null; try { tmp = File.createTempFile("yahp", "pdf"); tmp2 = File.createTempFile("yahp", "pdf"); oldOut = out; if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SIGNING))) { signed = true; out2 = new FileOutputStream(tmp2); } // end if else { out2 = oldOut; } out = new FileOutputStream(tmp); com.lowagie.text.Document document = null; PdfCopy writer = null; boolean first = true; Map mapSizeDoc = new HashMap(); int totalPage = 0; for (int i = 0; i < files.size(); i++) { final File fPDF = (File) files.get(i); final PdfReader reader = new PdfReader(fPDF.getAbsolutePath()); reader.consolidateNamedDestinations(); final int n = reader.getNumberOfPages(); if (first) { first = false; // step 1: creation of a document-object // set title/creator/author document = new com.lowagie.text.Document(reader.getPageSizeWithRotation(1)); // step 2: we create a writer that listens to the document writer = new PdfCopy(document, out); // use pdf version 1.5 writer.setPdfVersion(PdfWriter.VERSION_1_3); // compress the pdf writer.setFullCompression(); // check if encryption is needed if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { final String password = (String) properties .get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final int securityType = CDocumentReconstructor.getSecurityFlags(properties); writer.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, securityType); } // end if final String title = (String) properties.get(IHtmlToPdfTransformer.PDF_TITLE); if (title != null) { document.addTitle(title); } // end if else if (base_url != null) { document.addTitle(base_url); } // end else if final String creator = (String) properties.get(IHtmlToPdfTransformer.PDF_CREATOR); if (creator != null) { document.addCreator(creator); } // end if else { document.addCreator(IHtmlToPdfTransformer.VERSION); } // end else final String author = (String) properties.get(IHtmlToPdfTransformer.PDF_AUTHOR); if (author != null) { document.addAuthor(author); } // end if final String sproducer = (String) properties.get(IHtmlToPdfTransformer.PDF_PRODUCER); if (sproducer != null) { document.add(new Meta("Producer", sproducer)); } // end if else { document.add(new Meta("Producer", (IHtmlToPdfTransformer.VERSION + " - http://www.allcolor.org/YaHPConverter/ - " + producer))); } // end else // step 3: we open the document document.open(); } // end if PdfImportedPage page; for (int j = 0; j < n;) { ++j; totalPage++; mapSizeDoc.put("" + totalPage, "" + i); page = writer.getImportedPage(reader, j); writer.addPage(page); } // end for } // end for document.close(); out.flush(); out.close(); { final PdfReader reader = new PdfReader(tmp.getAbsolutePath()); ; final int n = reader.getNumberOfPages(); final PdfStamper stp = new PdfStamper(reader, out2); int i = 0; BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); final CHtmlToPdfFlyingSaucerTransformer trans = new CHtmlToPdfFlyingSaucerTransformer(); while (i < n) { i++; int indexSize = Integer.parseInt((String) mapSizeDoc.get("" + i)); final int[] dsize = size[indexSize].getSize(); final int[] dmargin = size[indexSize].getMargin(); for (final Iterator it = hf.iterator(); it.hasNext();) { final CHeaderFooter chf = (CHeaderFooter) it.next(); if (chf.getSfor().equals(CHeaderFooter.ODD_PAGES) && (i % 2 == 0)) { continue; } else if (chf.getSfor().equals(CHeaderFooter.EVEN_PAGES) && (i % 2 != 0)) { continue; } final String text = chf.getContent().replaceAll("<pagenumber>", "" + i) .replaceAll("<pagecount>", "" + n); // text over the existing page final PdfContentByte over = stp.getOverContent(i); final ByteArrayOutputStream bbout = new ByteArrayOutputStream(); if (chf.getType().equals(CHeaderFooter.HEADER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[3]), new ArrayList(), properties, bbout); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { trans.transform(new ByteArrayInputStream(text.getBytes("utf-8")), base_url, new PageSize(dsize[0] - (dmargin[0] + dmargin[1]), dmargin[2]), new ArrayList(), properties, bbout); } final PdfReader readerHF = new PdfReader(bbout.toByteArray()); if (chf.getType().equals(CHeaderFooter.HEADER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], dsize[1] - dmargin[3]); } else if (chf.getType().equals(CHeaderFooter.FOOTER)) { over.addTemplate(stp.getImportedPage(readerHF, 1), dmargin[0], 0); } readerHF.close(); } } stp.close(); } try { out2.flush(); } catch (Exception ignore) { } finally { try { out2.close(); } catch (Exception ignore) { } } if (signed) { final String keypassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_PASSWORD); final String password = (String) properties.get(IHtmlToPdfTransformer.PDF_ENCRYPTION_PASSWORD); final String keyStorepassword = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_KEYSTORE_PASSWORD); final String privateKeyFile = (String) properties .get(IHtmlToPdfTransformer.PDF_SIGNING_PRIVATE_KEY_FILE); final String reason = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_REASON); final String location = (String) properties.get(IHtmlToPdfTransformer.PDF_SIGNING_LOCATION); final boolean selfSigned = !"false" .equals(properties.get(IHtmlToPdfTransformer.USE_PDF_SELF_SIGNING)); PdfReader reader = null; if (password != null) { reader = new PdfReader(tmp2.getAbsolutePath(), password.getBytes()); } // end if else { reader = new PdfReader(tmp2.getAbsolutePath()); } // end else final KeyStore ks = selfSigned ? KeyStore.getInstance(KeyStore.getDefaultType()) : KeyStore.getInstance("pkcs12"); ks.load(new FileInputStream(privateKeyFile), keyStorepassword.toCharArray()); final String alias = (String) ks.aliases().nextElement(); final PrivateKey key = (PrivateKey) ks.getKey(alias, keypassword.toCharArray()); final Certificate chain[] = ks.getCertificateChain(alias); final PdfStamper stp = PdfStamper.createSignature(reader, oldOut, '\0'); if ("true".equals(properties.get(IHtmlToPdfTransformer.USE_PDF_ENCRYPTION))) { stp.setEncryption(PdfWriter.STANDARD_ENCRYPTION_128, password, null, CDocumentReconstructor.getSecurityFlags(properties)); } // end if final PdfSignatureAppearance sap = stp.getSignatureAppearance(); if (selfSigned) { sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); } // end if else { sap.setCrypto(key, chain, null, PdfSignatureAppearance.WINCER_SIGNED); } // end else if (reason != null) { sap.setReason(reason); } // end if if (location != null) { sap.setLocation(location); } // end if stp.close(); oldOut.flush(); } // end if } // end try catch (final Exception e) { throw new CConvertException( "ERROR: An Exception occured while reconstructing the pdf document: " + e.getMessage(), e); } // end catch finally { try { tmp.delete(); } // end try catch (final Exception ignore) { } try { tmp2.delete(); } // end try catch (final Exception ignore) { } } // end finally }
From source file:org.caisi.tickler.web.TicklerPrinter.java
License:Open Source License
public void start() throws DocumentException, IOException { //Create the font we are going to print to bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); font = new Font(bf, FONTSIZE, Font.NORMAL); boldFont = new Font(bf, FONTSIZE, Font.BOLD); document = new Document(); writer = PdfWriterFactory.newInstance(document, os, FontSettings.HELVETICA_10PT); writer.setStrictImageSequence(true); document.setPageSize(PageSize.LETTER); document.open();// w w w. ja v a 2 s . c om }
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 *//* w w w .jav a2 s .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.kuali.kfs.fp.document.service.impl.CashReceiptCoverSheetServiceImpl.java
License:Open Source License
/** * Read-only accessor for <code>{@link BaseFont}</code>. Used for creating the check detail information. The font being * used is Helvetica./*from ww w .j a v a 2 s.co m*/ * * @return A BaseFont object used to identify what type of font is used on the cover sheet. */ protected BaseFont getTextFont() throws DocumentException, IOException { return BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); }
From source file:org.kuali.kfs.sys.PdfFormFillerUtil.java
License:Open Source License
/** * This method creates a Final watermark on the input Stream. * * @param templateStream// w ww. ja va2s. co m * @param finalmarkText * @return * @throws IOException * @throws DocumentException */ public static byte[] createFinalmarkOnFile(byte[] templateStream, String finalmarkText) throws IOException, DocumentException { // Create a PDF reader for the template PdfReader pdfReader = new PdfReader(templateStream); ByteArrayOutputStream outputStream = new ByteArrayOutputStream(); // Create a PDF writer PdfStamper pdfStamper = new PdfStamper(pdfReader, outputStream); int n = pdfReader.getNumberOfPages(); int i = 1; PdfContentByte over; BaseFont bf; try { bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gstate = new PdfGState(); while (i <= n) { // Watermark under the existing page Rectangle pageSize = pdfReader.getPageSizeWithRotation(i); over = pdfStamper.getOverContent(i); over.beginText(); over.setFontAndSize(bf, 8); over.setGState(gstate); over.setColorFill(Color.BLACK); over.showTextAligned(Element.ALIGN_CENTER, finalmarkText, (pageSize.width() / 2), (pageSize.height() - 10), 0); over.endText(); i++; } pdfStamper.close(); } catch (DocumentException ex) { throw new IOException("iText error creating final watermark on PDF", ex); } catch (IOException ex) { throw new IOException("IO error creating final watermark on PDF", ex); } return outputStream.toByteArray(); }
From source file:org.meveo.admin.action.billing.BillingAccountBean.java
License:Open Source License
public void generatePDF(long invoiceId) { Invoice invoice = invoiceService.findById(invoiceId); byte[] invoicePdf = invoice.getPdf(); FacesContext context = FacesContext.getCurrentInstance(); String invoiceFilename = null; BillingRun billingRun = invoice.getBillingRun(); invoiceFilename = invoice.getInvoiceNumber() + ".pdf"; if (billingRun != null && billingRun.getStatus() != BillingRunStatusEnum.VALIDATED) { invoiceFilename = "unvalidated-invoice.pdf"; }//from w w w . ja v a2 s .c o m HttpServletResponse response = (HttpServletResponse) context.getExternalContext().getResponse(); response.setContentType("application/pdf"); // fill in response.setHeader("Content-disposition", "attachment; filename=" + invoiceFilename); try { OutputStream os = response.getOutputStream(); Document document = new Document(PageSize.A4); if (billingRun != null && invoice.getBillingRun().getStatus() != BillingRunStatusEnum.VALIDATED) { // Add watemark image PdfReader reader = new PdfReader(invoicePdf); int n = reader.getNumberOfPages(); PdfStamper stamp = new PdfStamper(reader, os); PdfContentByte over = null; BaseFont bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.WINANSI, BaseFont.EMBEDDED); PdfGState gs = new PdfGState(); gs.setFillOpacity(0.5f); int i = 1; while (i <= n) { over = stamp.getOverContent(i); over.setGState(gs); over.beginText(); System.out.println("top=" + document.top() + ",bottom=" + document.bottom()); over.setTextMatrix(document.top(), document.bottom()); over.setFontAndSize(bf, 150); over.setColorFill(Color.GRAY); over.showTextAligned(Element.ALIGN_CENTER, "TEST", document.getPageSize().getWidth() / 2, document.getPageSize().getHeight() / 2, 45); over.endText(); i++; } stamp.close(); } else { os.write(invoicePdf); // fill in PDF with bytes } // contentType os.flush(); os.close(); context.responseComplete(); } catch (IOException e) { log.error("failed to generate PDF ", e); } catch (DocumentException e) { log.error("error in generation PDF ", e); } }