List of usage examples for com.lowagie.text Image getInstance
public static Image getInstance(Image image)
From source file:de.xirp.report.ReportGenerator.java
License:Open Source License
/** * Adds a/*from w w w. ja v a2 s . c om*/ * {@link de.xirp.report.data.ContentPartImage image} * item to the PDF {@link com.lowagie.text.Document}. * * @param item * The image item to add. * @throws IOException * if something went wrong saving the PDF. * @throws DocumentException * if something went wrong adding the page. * @throws MalformedURLException * if something went wrong saving the PDF. * @see de.xirp.report.data.ContentPartImage * @see com.lowagie.text.Document */ private static void addImage(ContentPartImage item) throws MalformedURLException, IOException, DocumentException { imageCounter++; String path = ""; //$NON-NLS-1$ File file = new File(item.getPath()); if (file.exists()) { path = item.getPath(); } Image image = Image.getInstance(path); image.setAlignment(Image.MIDDLE); int maxWidth = 500; float plain = image.plainWidth(); if (plain > maxWidth) { float percentage = maxWidth / plain; image.scalePercent(percentage * 100); } document.add(image); document.add(getParagraph(I18n.getString("ReportGenerator.report.document.image") //$NON-NLS-1$ + " " + imageCounter + ": " + item.getShortDescription(), //$NON-NLS-1$ //$NON-NLS-2$ IMAGE, Element.ALIGN_CENTER)); }
From source file:docx4j.TextSubstitution.java
License:Apache License
private String addWaterMark() throws IOException, DocumentException { String result = null;//from w w w . ja v a2 s . c o m String newFileName = this.getFolderPath() + "wm" + this.fileName; try { // try to delete the file if it already exists so that we refresh the watermark // if it fails then at least we have the existing version which can be deleted manually File target = new File(newFileName); if (target.exists()) { if (!target.delete()) { return "existing"; } } // add the watermark PdfReader reader = new PdfReader(this.filePath); PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(newFileName)); Image watermark_image = Image.getInstance(this.getFolderPath() + "doc-watermark.png"); watermark_image.setAbsolutePosition(5, 5); int i = 0; PdfContentByte add_watermark; // loop the pages adding the watermark while (i < reader.getNumberOfPages()) { i++; add_watermark = stamp.getUnderContent(i); add_watermark.addImage(watermark_image); } stamp.close(); reader.close(); } catch (Exception e) { result = e.getMessage(); } return result; }
From source file:domain.reports.menu.PDFReportMenu.java
License:LGPL
@Override protected void createPDF(GenericTransaction data, ByteArrayOutputStream buf) throws Throwable { //inicializar documento: tamano de pagina, orientacion, margenes Document doc = new Document(); PdfWriter docWriter = PdfWriter.getInstance(doc, buf); doc.setPageSize(PageSize.LETTER.rotate()); doc.setMargins(30, 30, 30, 40);//from w w w. jav a2 s. com doc.open(); //crear fonts por defecto tblHeaderFont = new Font(Font.HELVETICA, 10f, Font.BOLD); tblBodyFont = new Font(Font.HELVETICA, 10f, Font.NORMAL); //definir pie de pagina del lado izquierdo String footerText = this.getFooter(); //read it from config.xml or web.xml String reportDate = StringUtil.formatDate(new java.util.Date(), "dd-MM-yyyy HH:mm"); //crear template (objeto interno de IText) y manejador de evento //para imprimir el pie de pagina bf = BaseFont.createFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); cb = docWriter.getDirectContent(); tpl = cb.createTemplate(20, 14); docWriter.setPageEvent(new PDFPageEvents(footerText, pageXofY, tpl, bf, cb, reportDate)); //titulo - lo lee de config.xml por defecto reportTitle = getReportTitle(); Paragraph t = new Paragraph(reportTitle, new Font(Font.HELVETICA, 14f, Font.BOLD)); t.setAlignment(Rectangle.ALIGN_RIGHT); doc.add(t); //logo img = Image.getInstance(getImage(this.getServerBaseURL() + logoPath, false)); img.scalePercent(100); float imgY = doc.top() - img.getHeight(); float imgX = doc.left(); img.setAbsolutePosition(imgX, imgY); doc.add(img); //blank line doc.add(new Paragraph(" ")); //blank line doc.add(new Paragraph(" ")); //blank line doc.add(new Paragraph(" ")); //for each master record print a master/detail section MasterDetailReader dataobj = (MasterDetailReader) data; Recordset master = dataobj.getRecordset("master"); master.top(); while (master.next()) { //blank line doc.add(new Paragraph(" ")); //print master section doc.add(getGroupMaster(master)); //print detail section doc.add(getGroupDetail(master, dataobj.getDetail(master))); } //print grand total doc.add(new Paragraph(" ")); doc.close(); docWriter.close(); }
From source file:edu.eci.pdsw.g4.bean.control.web.SystemManageBean.java
public void preProcessPDF(Object document) throws IOException, BadElementException, DocumentException { Document pdf = (Document) document; pdf.open();/* www .j av a 2 s . co m*/ pdf.setPageSize(PageSize.A4); pdf.addTitle("Ficha del Equipo : " + loadTipoEquipo.getNombre_equipo()); ExternalContext externalContext = FacesContext.getCurrentInstance().getExternalContext(); String logo = externalContext.getRealPath("") + File.separator + "resource" + File.separator + "ecijulio.png"; pdf.add(Image.getInstance(logo)); pdf.bottom(30); pdf.add(new Chunk( "Datos del Equipo : " + loadTipoEquipo.getNombre_equipo() + " con Placa No : " + getPlacaficha())); }
From source file:eu.europa.ec.markt.dss.signature.pdf.StatefulITextPDFSignatureService.java
License:Open Source License
@SuppressWarnings({ "unchecked", "rawtypes" }) private PdfStamper prepareStamper(InputStream pdfData, OutputStream output, SignatureParameters parameters) throws IOException, DocumentException { if (stp != null) { return stp; }// w ww . ja v a 2s . co m PdfReader reader = new PdfReader(pdfData); stp = PdfStamper.createSignature(reader, output, '\0', null, true); PdfSignatureAppearance sap = stp.getSignatureAppearance(); sap.setAcro6Layers(true); sap.setLayer2Text(""); if (parameters.getSignatureAppearance() != null) { sap.setRender(PdfSignatureAppearance.SignatureRenderGraphic); sap.setImage(null); PdfReader stampReader = new PdfReader(parameters.getSignatureAppearance()); PdfTemplate stamp = stp.getWriter().getImportedPage(stampReader, 1); //stamp.setBoundingBox(new Rectangle(200, 100)); sap.setTemplate(stamp); sap.setSignatureGraphic(Image.getInstance(stamp)); float[] pos = parameters.getSignaturePosition(); Rectangle rect = new Rectangle(pos[0], pos[1], pos[2], pos[3]); sap.setVisibleSignature(rect, 1, parameters.getSignatureName()); } else { sap.setRender(PdfSignatureAppearance.SignatureRenderDescription); } PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, new PdfName("ETSI.CAdES.detached")); Calendar cal = Calendar.getInstance(); cal.setTime(parameters.getSigningDate()); sap.setSignDate(cal); dic.setDate(new PdfDate(cal)); if (parameters.getReason() != null) { dic.setReason(parameters.getReason()); } if (parameters.getLocation() != null) { dic.setLocation(parameters.getLocation()); } if (parameters.getContactInfo() != null) { dic.setContact(parameters.getContactInfo()); } sap.setCryptoDictionary(dic); int csize = getSignatureSize(); HashMap exc = new HashMap(); exc.put(PdfName.CONTENTS, new Integer(csize * 2 + 2)); sap.preClose(exc); return stp; }
From source file:fr.aliasource.webmail.server.export.ConversationPdfEventHandler.java
License:GNU General Public License
/** * @see com.lowagie.text.pdf.PdfPageEventHelper#onOpenDocument(com.lowagie.text.pdf.PdfWriter, * com.lowagie.text.Document)/*from w w w . ja v a 2s . co m*/ */ public void onOpenDocument(PdfWriter writer, Document document) { try { headerImage = Image.getInstance(getLogoUrl()); table = new PdfPTable(new float[] { 1f, 2f }); Phrase p = new Phrase(); Chunk ck = new Chunk(cr.getTitle(), new Font(Font.HELVETICA, 16, Font.BOLD)); p.add(ck); p.add(Chunk.NEWLINE); ck = new Chunk(ConversationExporter.formatName(account), new Font(Font.HELVETICA, 12, Font.BOLDITALIC)); p.add(ck); p.add(Chunk.NEWLINE); ck = new Chunk(cm.length + " messages", new Font(Font.HELVETICA, 10)); p.add(ck); table.getDefaultCell().setBorder(0); table.addCell(new Phrase(new Chunk(headerImage, 0, 0))); table.getDefaultCell().setHorizontalAlignment(Element.ALIGN_RIGHT); table.addCell(p); // initialization of the template tpl = writer.getDirectContent().createTemplate(100, 100); tpl.setBoundingBox(new Rectangle(-20, -20, 100, 100)); // initialization of the font helv = BaseFont.createFont("Helvetica", BaseFont.WINANSI, false); } catch (Exception e) { throw new ExceptionConverter(e); } }
From source file:fr.opensagres.odfdom.converter.pdf.internal.BackgroundImage.java
License:Open Source License
/** * Insert the backgroundImage in the given OutputStream. * @param out the pdf as a ByteArrayOutputStream *//*from w w w . j a va2s . co m*/ public ByteArrayOutputStream insert(ByteArrayOutputStream out) { try { Image image = Image.getInstance(imageBytes); float imageWidth = image.getWidth() * DEFAULT_DPI / image.getDpiX(); float imageHeight = image.getHeight() * DEFAULT_DPI / image.getDpiY(); switch (repeat) { case BOTH: ByteArrayOutputStream stream = out; //TODO: maybe we could get better results if we tiled the byteArray instead of the images themselves. for (float x = leftMargin; x < pageWidth - rightMargin; x += imageWidth) { for (float y = pageHeight - topMargin; y > bottomMargin; y -= imageHeight) { if (x + imageWidth > pageWidth - rightMargin || y - imageHeight < bottomMargin) { byte[] data = new byte[(int) imageWidth * (int) imageHeight]; for (int k = 0; k < (int) imageHeight; k++) { for (int i = 0; i < imageWidth; i++) { if (x + i < pageWidth - rightMargin && y - k > bottomMargin) { data[i + k * (int) imageWidth] = (byte) 0xff; } } } Image clone = Image.getInstance(image); Image mask = Image.getInstance((int) imageWidth, (int) imageHeight, 1, 8, data); mask.makeMask(); clone.setImageMask(mask); clone.setAbsolutePosition(x, y - imageHeight); stream = insertImage(stream, clone); } else { image.setAbsolutePosition(x, y - imageHeight); image.scaleAbsolute(imageWidth, imageHeight); stream = insertImage(stream, image); } } } return stream; case NONE: float y; if (position.name().split("_")[0].equals("TOP")) { y = pageHeight - imageHeight - topMargin; } else if (position.name().split("_")[0].equals("CENTER")) { y = (pageHeight - imageHeight - topMargin) / 2; } else if (position.name().split("_")[0].equals("BOTTOM")) { y = bottomMargin; } else { throw new UnsupportedOperationException(position + " is not supported"); } float x; if (position.name().split("_")[1].equals("LEFT")) { x = leftMargin; } else if (position.name().split("_")[1].equals("CENTER")) { x = (pageWidth - imageWidth - rightMargin) / 2; } else if (position.name().split("_")[1].equals("RIGHT")) { x = pageWidth - imageWidth - rightMargin; } else { throw new UnsupportedOperationException(position + " is not supported"); } image.setAbsolutePosition(x, y); image.scaleAbsolute(imageWidth, imageHeight); return insertImage(out, image); case STRETCH: image.setAbsolutePosition(leftMargin, bottomMargin); image.scaleAbsolute(pageWidth - leftMargin - rightMargin, pageHeight - topMargin - bottomMargin); return insertImage(out, image); default: throw new UnsupportedOperationException(repeat + " is not implemented"); } } catch (Exception e) { throw new RuntimeException(e); } }
From source file:fr.opensagres.odfdom.converter.pdf.internal.stylable.StylableImage.java
License:Open Source License
public static Image getImage(byte[] imgb) { try {/*from ww w . j av a2 s. c om*/ if (imgb.length >= 6 && imgb[0] == 'V' && imgb[1] == 'C' && imgb[2] == 'L' && imgb[3] == 'M' && imgb[4] == 'T' && imgb[5] == 'F') { // the image is in StarViewMetafile format // this format is undocumented and there is no java library to parse it // this image probably contains a wrapped bitmap // we don't try to interpret this format, instead we do a hack, we search for bitmap magic number int bmpStartOffset = getBmpStartOffset(imgb); if (bmpStartOffset >= 0) { // we found the bitmap, which consists of // <bitmap header - 14 bytes> // <dib header - variable size> // <image data - variable size> int bmpFileSize = getInt(imgb, bmpStartOffset + 2); // whole bitmap size including headers byte[] bmpb = new byte[bmpFileSize]; int bmpHeaderSize = 14; int compressionMethod = getInt(imgb, bmpStartOffset + bmpHeaderSize + 16); int ZCOMPRESS = 'S' | 'D' << 8 | 0x01000000; if (compressionMethod == ZCOMPRESS) { // this is a new "invention", a bitmap with nonstandard compression // of course it is undocumented too // the idea how to process it was taken from // 'vcl/source/gdi/bitmap2.cxx' - open office source file // // the original <image data> is replaced by // <compressed data size - 4 bytes> // <uncompressed data size - 4 bytes> // <original compression method - 4 bytes> // <zlib compressed image data - variable size> int dibHeaderSize = getInt(imgb, bmpStartOffset + bmpHeaderSize); int allHeadersSize = bmpHeaderSize + dibHeaderSize; int compressedSize = getInt(imgb, bmpStartOffset + allHeadersSize); int uncompressedSize = getInt(imgb, bmpStartOffset + allHeadersSize + 4); // uncompress data Inflater inflater = new Inflater(); inflater.setInput(imgb, bmpStartOffset + allHeadersSize + 12, compressedSize); byte[] uncompressedData = new byte[uncompressedSize]; inflater.inflate(uncompressedData); // gather all parts together System.arraycopy(imgb, bmpStartOffset, bmpb, 0, allHeadersSize); System.arraycopy(imgb, bmpStartOffset + allHeadersSize + 8, bmpb, bmpHeaderSize + 16, 4); System.arraycopy(uncompressedData, 0, bmpb, allHeadersSize, uncompressedSize); } else { // standard bitmap System.arraycopy(imgb, bmpStartOffset, bmpb, 0, bmpFileSize); } imgb = bmpb; } } return Image.getInstance(imgb); } catch (Exception e) { return null; } }
From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.FastPdfMapper.java
License:Open Source License
@Override protected void visitPicture(CTPicture picture, Float offsetX, org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromH.Enum relativeFromH, Float offsetY,/*from w w w . j ava2 s. co m*/ org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromV.Enum relativeFromV, STWrapText.Enum wrapText, IITextContainer pdfParentContainer) throws Exception { CTPositiveSize2D ext = picture.getSpPr().getXfrm().getExt(); long x = ext.getCx(); long y = ext.getCy(); byte[] pictureData = super.getPictureBytes(picture); if (pictureData != null) { try { Image img = Image.getInstance(pictureData); img.scaleAbsolute(emu2points(x), emu2points(y)); IITextContainer parentOfParentContainer = pdfParentContainer.getITextContainer(); if (parentOfParentContainer != null && parentOfParentContainer instanceof PdfPCell) { parentOfParentContainer.addElement(img); } else { float chunkOffsetX = 0; if (offsetX != null) { if (STRelFromH.CHARACTER.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.COLUMN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.INSIDE_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.LEFT_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.MARGIN.equals(relativeFromH)) { chunkOffsetX = pdfDocument.left() + offsetX; } else if (STRelFromH.OUTSIDE_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.PAGE.equals(relativeFromH)) { chunkOffsetX = offsetX - pdfDocument.left(); } } float chunkOffsetY = 0; boolean useExtendedImage = false; if (STRelFromV.PARAGRAPH.equals(relativeFromV)) { useExtendedImage = true; } if (useExtendedImage) { ExtendedImage extImg = new ExtendedImage(img, -offsetY); if (STRelFromV.PARAGRAPH.equals(relativeFromV)) { chunkOffsetY = -extImg.getScaledHeight(); } Chunk chunk = new Chunk(extImg, chunkOffsetX, chunkOffsetY, false); pdfParentContainer.addElement(chunk); } /* * float chunkOffsetY = 0; if ( wrapText != null ) { chunkOffsetY = -img.getScaledHeight(); } * boolean useExtendedImage = offsetY != null; // if ( STRelFromV.PARAGRAPH.equals( relativeFromV ) * ) // { // useExtendedImage = true; // } // if ( useExtendedImage ) { float imgY = -offsetY; if ( * pdfHeader != null ) { float headerY = pdfHeader.getY() != null ? pdfHeader.getY() : 0; imgY += - * img.getScaledHeight() + headerY; } ExtendedImage extImg = new ExtendedImage( img, imgY ); // if ( * STRelFromV.PARAGRAPH.equals( relativeFromV ) ) // { // chunkOffsetY = -extImg.getScaledHeight(); * // } Chunk chunk = new Chunk( extImg, chunkOffsetX, chunkOffsetY, false ); * pdfParentContainer.addElement( chunk ); } */ else { if (pdfParentContainer instanceof Paragraph) { // I don't know why but we need add some spacing before in the paragraph // otherwise the image cut the text of the below paragraph (see FormattingTests JUnit)? Paragraph paragraph = (Paragraph) pdfParentContainer; paragraph.setSpacingBefore(paragraph.getSpacingBefore() + 5f); } pdfParentContainer.addElement(new Chunk(img, chunkOffsetX, chunkOffsetY, false)); } } } catch (Exception e) { LOGGER.severe(e.getMessage()); } } }
From source file:fr.opensagres.poi.xwpf.converter.pdf.internal.PdfMapper.java
License:Open Source License
@Override protected void visitPicture(CTPicture picture, Float offsetX, org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromH.Enum relativeFromH, Float offsetY,//from w ww . j a va 2 s . com org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.STRelFromV.Enum relativeFromV, STWrapText.Enum wrapText, IITextContainer pdfParentContainer) throws Exception { CTPositiveSize2D ext = picture.getSpPr().getXfrm().getExt(); long x = ext.getCx(); long y = ext.getCy(); XWPFPictureData pictureData = super.getPictureData(picture); if (pictureData != null) { try { Image img = Image.getInstance(pictureData.getData()); img.scaleAbsolute(emu2points(x), emu2points(y)); IITextContainer parentOfParentContainer = pdfParentContainer.getITextContainer(); if (parentOfParentContainer != null && parentOfParentContainer instanceof PdfPCell) { parentOfParentContainer.addElement(img); } else { float chunkOffsetX = 0; if (offsetX != null) { if (STRelFromH.CHARACTER.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.COLUMN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.INSIDE_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.LEFT_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.MARGIN.equals(relativeFromH)) { chunkOffsetX = pdfDocument.left() + offsetX; } else if (STRelFromH.OUTSIDE_MARGIN.equals(relativeFromH)) { chunkOffsetX = offsetX; } else if (STRelFromH.PAGE.equals(relativeFromH)) { chunkOffsetX = offsetX - pdfDocument.left(); } } float chunkOffsetY = 0; boolean useExtendedImage = false; if (STRelFromV.PARAGRAPH.equals(relativeFromV)) { useExtendedImage = true; } if (useExtendedImage) { ExtendedImage extImg = new ExtendedImage(img, -offsetY); if (STRelFromV.PARAGRAPH.equals(relativeFromV)) { chunkOffsetY = -extImg.getScaledHeight(); } Chunk chunk = new Chunk(extImg, chunkOffsetX, chunkOffsetY, false); pdfParentContainer.addElement(chunk); } /* * float chunkOffsetY = 0; if ( wrapText != null ) { * chunkOffsetY = -img.getScaledHeight(); } boolean * useExtendedImage = offsetY != null; // if ( * STRelFromV.PARAGRAPH.equals( relativeFromV ) ) // { // * useExtendedImage = true; // } // if ( useExtendedImage ) * { float imgY = -offsetY; if ( pdfHeader != null ) { float * headerY = pdfHeader.getY() != null ? pdfHeader.getY() : * 0; imgY += - img.getScaledHeight() + headerY; } * ExtendedImage extImg = new ExtendedImage( img, imgY ); // * if ( STRelFromV.PARAGRAPH.equals( relativeFromV ) ) // { * // chunkOffsetY = -extImg.getScaledHeight(); // } Chunk * chunk = new Chunk( extImg, chunkOffsetX, chunkOffsetY, * false ); pdfParentContainer.addElement( chunk ); } */ else { if (pdfParentContainer instanceof Paragraph) { // I don't know why but we need add some spacing // before in the paragraph // otherwise the image cut the text of the below // paragraph (see FormattingTests JUnit)? Paragraph paragraph = (Paragraph) pdfParentContainer; paragraph.setSpacingBefore(paragraph.getSpacingBefore() + 5f); } pdfParentContainer.addElement(new Chunk(img, chunkOffsetX, chunkOffsetY, false)); } } } catch (Exception e) { LOGGER.severe(e.getMessage()); } } }