List of usage examples for com.lowagie.text Image getScaledHeight
public float getScaledHeight()
From source file:com.openkm.util.DocConverter.java
License:Open Source License
/** * TIFF to PDF conversion//from ww w . ja v a 2 s .c o m */ public void tiff2pdf(File input, File output) throws ConversionException { RandomAccessFileOrArray ra = null; Document doc = null; try { // Open PDF doc = new Document(); PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(output)); PdfContentByte cb = writer.getDirectContent(); doc.open(); // int pages = 0; // Open TIFF ra = new RandomAccessFileOrArray(input.getPath()); int comps = TiffImage.getNumberOfPages(ra); for (int c = 0; c < comps; ++c) { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { log.debug("tiff2pdf - page {}", c + 1); if (img.getScaledWidth() > 500 || img.getScaledHeight() > 700) { img.scaleToFit(500, 700); } img.setAbsolutePosition(20, 20); // doc.add(new Paragraph("page " + (c + 1))); cb.addImage(img); doc.newPage(); // ++pages; } } } catch (FileNotFoundException e) { throw new ConversionException("File not found: " + e.getMessage(), e); } catch (DocumentException e) { throw new ConversionException("Document exception: " + e.getMessage(), e); } catch (IOException e) { throw new ConversionException("IO exception: " + e.getMessage(), e); } finally { if (ra != null) { try { ra.close(); } catch (IOException e) { // Ignore } } if (doc != null) { doc.close(); } } }
From source file:mpv5.utils.export.PDFFile.java
License:Open Source License
private void setImage(PdfStamper stamper, String key, java.awt.Image oimg) { try {/*w w w. j a va 2 s .co m*/ Log.Debug(this, "Write Image.." + key); float[] photograph = acroFields.getFieldPositions(key); Rectangle rect = new Rectangle(photograph[1], photograph[2], photograph[3], photograph[4]); Image img = Image.getInstance(oimg, null); img.setAbsolutePosition(photograph[1] + (rect.getWidth() - img.getScaledWidth()) / 2, photograph[2] + (rect.getHeight() - img.getScaledHeight()) / 2); PdfContentByte cb = stamper.getOverContent((int) photograph[0]); cb.addImage(img); } catch (Exception iOException) { Log.Debug(iOException); } }
From source file:org.jrimum.bopepo.pdf.PDFs.java
License:Apache License
/** * <p>//from www . j av a2s . c o m * Muda um input field para uma imgem com as dimenses e possio do field. * </p> * * @param stamper * @param rect * @param image * @return rectanglePDF * @throws DocumentException * * @since 0.2 */ public static PdfRectangle changeFieldToImage(PdfStamper stamper, PdfRectangle rect, Image image) throws DocumentException { // Ajustando o tamanho da imagem de acordo com o tamanho do campo. // image.scaleToFit(rect.getWidth(), rect.getHeight()); image.scaleAbsolute(rect.getWidth(), rect.getHeight()); // A rotina abaixo tem por objetivo deixar a imagem posicionada no // centro // do field, tanto na perspectiva horizontal como na vertical. // Caso no se queira mais posicionar a imagem no centro do field, basta // efetuar a chamada a seguir: // "image.setAbsolutePosition // (rect.getLowerLeftX(),rect.getLowerLeftY());" image.setAbsolutePosition(rect.getLowerLeftX() + (rect.getWidth() - image.getScaledWidth()) / 2, rect.getLowerLeftY() + (rect.getHeight() - image.getScaledHeight()) / 2); stamper.getOverContent(rect.getPage()).addImage(image); return rect; }
From source file:org.jrimum.bopepo.pdf.PDFUtil.java
License:Apache License
/** * <p>//from w w w.ja va 2s . c om * Muda um input field para uma imgem com as dimenses e possio do field. * </p> * * @param stamper * @param rect * @param image * @return rectanglePDF * @throws DocumentException * * @since 0.2 */ public static RectanglePDF changeFieldToImage(PdfStamper stamper, RectanglePDF rect, Image image) throws DocumentException { // Ajustando o tamanho da imagem de acordo com o tamanho do campo. // image.scaleToFit(rect.getWidth(), rect.getHeight()); image.scaleAbsolute(rect.getWidth(), rect.getHeight()); // A rotina abaixo tem por objetivo deixar a imagem posicionada no // centro // do field, tanto na perspectiva horizontal como na vertical. // Caso no se queira mais posicionar a imagem no centro do field, basta // efetuar a chamada a seguir: // "image.setAbsolutePosition // (rect.getLowerLeftX(),rect.getLowerLeftY());" image.setAbsolutePosition(rect.getLowerLeftX() + (rect.getWidth() - image.getScaledWidth()) / 2, rect.getLowerLeftY() + (rect.getHeight() - image.getScaledHeight()) / 2); // cb = stamper.getUnderContent(rect.getPage()); stamper.getOverContent(rect.getPage()).addImage(image); return rect; }
From source file:org.locationtech.udig.printing.ui.pdf.ExportPDFWizard.java
License:Open Source License
/** * This function is used to draw very thin white borders over the outer * edge of the raster map. It's necessary because the map edge "bleeds" into * the adjacent pixels, and we need to cover that. * /*from w ww . j a va2s . co m*/ * I think this quirky behaviour is possibly an iText bug */ private void addWhiteMapBorder(Image img, Document doc) { try { Color color = Color.white; int borderWidth = 1; BufferedImage bufferedTop = new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB); Graphics2D g1 = bufferedTop.createGraphics(); g1.setBackground(color); g1.clearRect(0, 0, bufferedTop.getWidth(), bufferedTop.getHeight()); Image top = Image.getInstance(bufferedImage2ByteArray(bufferedTop)); top.setAbsolutePosition(img.getAbsoluteX(), img.getAbsoluteY() + img.getScaledHeight() - bufferedTop.getHeight() / 2); BufferedImage bufferedBottom = new BufferedImage((int) img.getScaledWidth(), borderWidth, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = bufferedBottom.createGraphics(); g2.setBackground(color); g2.clearRect(0, 0, bufferedBottom.getWidth(), bufferedBottom.getHeight()); Image bottom = Image.getInstance(bufferedImage2ByteArray(bufferedBottom)); bottom.setAbsolutePosition(img.getAbsoluteX(), img.getAbsoluteY() - bufferedTop.getHeight() / 2); BufferedImage bufferedLeft = new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g3 = bufferedLeft.createGraphics(); g3.setBackground(color); g3.clearRect(0, 0, bufferedLeft.getWidth(), bufferedLeft.getHeight()); Image left = Image.getInstance(bufferedImage2ByteArray(bufferedLeft)); left.setAbsolutePosition(img.getAbsoluteX() - bufferedLeft.getWidth() / 2, img.getAbsoluteY()); BufferedImage bufferedRight = new BufferedImage(borderWidth, (int) img.getScaledHeight(), BufferedImage.TYPE_INT_RGB); Graphics2D g4 = bufferedRight.createGraphics(); g4.setBackground(color); g4.clearRect(0, 0, bufferedRight.getWidth(), bufferedRight.getHeight()); Image right = Image.getInstance(bufferedImage2ByteArray(bufferedRight)); right.setAbsolutePosition(img.getAbsoluteX() + img.getScaledWidth() - bufferedRight.getWidth() / 2, img.getAbsoluteY()); doc.add(top); doc.add(bottom); doc.add(left); doc.add(right); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.orbeon.oxf.processor.pdf.PDFTemplateProcessor.java
License:Open Source License
private void handleGroup(PipelineContext pipelineContext, GroupContext groupContext, List<Element> statements, FunctionLibrary functionLibrary, PdfReader reader) throws DocumentException, IOException { final NodeInfo contextNode = (NodeInfo) groupContext.contextNodeSet.get(groupContext.contextPosition - 1); final Map<String, ValueRepresentation> variableToValueMap = new HashMap<String, ValueRepresentation>(); variableToValueMap.put("page-count", new Int64Value(reader.getNumberOfPages())); variableToValueMap.put("page-number", new Int64Value(groupContext.pageNumber)); variableToValueMap.put("page-height", new FloatValue(groupContext.pageHeight)); // Iterate through statements for (final Element currentElement : statements) { // Check whether this statement applies to the current page final String elementPage = currentElement.attributeValue("page"); if ((elementPage != null) && !Integer.toString(groupContext.pageNumber).equals(elementPage)) continue; final NamespaceMapping namespaceMapping = new NamespaceMapping( Dom4jUtils.getNamespaceContextNoDefault(currentElement)); final String elementName = currentElement.getName(); if (elementName.equals("group")) { // Handle group final GroupContext newGroupContext = new GroupContext(groupContext); final String ref = currentElement.attributeValue("ref"); if (ref != null) { final NodeInfo newContextNode = (NodeInfo) XPathCache.evaluateSingle( groupContext.contextNodeSet, groupContext.contextPosition, ref, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); if (newContextNode == null) continue; newGroupContext.contextNodeSet = Collections.singletonList((Item) newContextNode); newGroupContext.contextPosition = 1; }//www. j a v a 2 s . c o m final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); if (offsetXString != null) { newGroupContext.offsetX = groupContext.offsetX + Float.parseFloat(offsetXString); } final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); if (offsetYString != null) { newGroupContext.offsetY = groupContext.offsetY + Float.parseFloat(offsetYString); } final String fontPitch = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-pitch")); if (fontPitch != null) newGroupContext.fontPitch = Float.parseFloat(fontPitch); final String fontFamily = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-family")); if (fontFamily != null) newGroupContext.fontFamily = fontFamily; final String fontSize = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("font-size")); if (fontSize != null) newGroupContext.fontSize = Float.parseFloat(fontSize); handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } else if (elementName.equals("repeat")) { // Handle repeat final String nodeset = currentElement.attributeValue("nodeset"); final List iterations = XPathCache.evaluate(groupContext.contextNodeSet, groupContext.contextPosition, nodeset, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String offsetXString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-x")); final String offsetYString = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("offset-y")); final float offsetIncrementX = (offsetXString == null) ? 0 : Float.parseFloat(offsetXString); final float offsetIncrementY = (offsetYString == null) ? 0 : Float.parseFloat(offsetYString); for (int iterationIndex = 1; iterationIndex <= iterations.size(); iterationIndex++) { final GroupContext newGroupContext = new GroupContext(groupContext); newGroupContext.contextNodeSet = iterations; newGroupContext.contextPosition = iterationIndex; newGroupContext.offsetX = groupContext.offsetX + (iterationIndex - 1) * offsetIncrementX; newGroupContext.offsetY = groupContext.offsetY + (iterationIndex - 1) * offsetIncrementY; handleGroup(pipelineContext, newGroupContext, Dom4jUtils.elements(currentElement), functionLibrary, reader); } } else if (elementName.equals("field")) { final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); groupContext.acroFields.setField(fieldName, text); } else { // Handle field final String leftAttribute = currentElement.attributeValue("left") == null ? currentElement.attributeValue("left-position") : currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top") == null ? currentElement.attributeValue("top-position") : currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); // Output value final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); groupContext.contentByte.beginText(); { groupContext.contentByte.setFontAndSize(baseFont, fontAttributes.fontSize); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); // Get value from instance final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); // Iterate over characters and print them if (text != null) { int len = Math.min(text.length(), (size != null) ? Integer.parseInt(size) : Integer.MAX_VALUE); for (int j = 0; j < len; j++) groupContext.contentByte.showTextAligned(PdfContentByte.ALIGN_CENTER, text.substring(j, j + 1), xPosition + ((float) j) * fontAttributes.fontPitch, yPosition, 0); } } groupContext.contentByte.endText(); } } else if (elementName.equals("barcode")) { // Handle barcode final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); // final String size = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, currentElement.attributeValue("size")); final String value = currentElement.attributeValue("value") == null ? currentElement.attributeValue("ref") : currentElement.attributeValue("value"); final String type = currentElement.attributeValue("type") == null ? "CODE39" : currentElement.attributeValue("type"); final float height = currentElement.attributeValue("height") == null ? 10.0f : Float.parseFloat(currentElement.attributeValue("height")); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String text = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, value, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final FontAttributes fontAttributes = getFontAttributes(currentElement, pipelineContext, groupContext, variableToValueMap, contextNode); final BaseFont baseFont = BaseFont.createFont(fontAttributes.fontFamily, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); final Barcode barcode = createBarCode(type); barcode.setCode(text); barcode.setBarHeight(height); barcode.setFont(baseFont); barcode.setSize(fontAttributes.fontSize); final Image barcodeImage = barcode.createImageWithBarcode(groupContext.contentByte, null, null); barcodeImage.setAbsolutePosition(xPosition, yPosition); groupContext.contentByte.addImage(barcodeImage); } else if (elementName.equals("image")) { // Handle image // Read image final Image image; { final String hrefAttribute = currentElement.attributeValue("href"); final String inputName = ProcessorImpl.getProcessorInputSchemeInputName(hrefAttribute); if (inputName != null) { // Read the input final ByteArrayOutputStream os = new ByteArrayOutputStream(); readInputAsSAX(pipelineContext, inputName, new BinaryTextXMLReceiver(null, os, true, false, null, false, false, null, false)); // Create the image image = Image.getInstance(os.toByteArray()); } else { // Read and create the image final URL url = URLFactory.createURL(hrefAttribute); // Use ConnectionResult so that header/session forwarding takes place final ConnectionResult connectionResult = new Connection().open( NetUtils.getExternalContext(), new IndentedLogger(logger, ""), false, Connection.Method.GET.name(), url, null, null, null, null, Connection.getForwardHeaders()); if (connectionResult.statusCode != 200) { connectionResult.close(); throw new OXFException("Got invalid return code while loading image: " + url.toExternalForm() + ", " + connectionResult.statusCode); } // Make sure things are cleaned-up not too late pipelineContext.addContextListener(new PipelineContext.ContextListener() { public void contextDestroyed(boolean success) { connectionResult.close(); } }); // Here we decide to copy to temp file and load as a URL. We could also provide bytes directly. final String tempURLString = NetUtils.inputStreamToAnyURI( connectionResult.getResponseInputStream(), NetUtils.REQUEST_SCOPE); image = Image.getInstance(URLFactory.createURL(tempURLString)); } } final String fieldNameStr = currentElement.attributeValue("acro-field-name"); if (fieldNameStr != null) { // Use field as placeholder final String fieldName = XPathCache.evaluateAsString(groupContext.contextNodeSet, groupContext.contextPosition, fieldNameStr, namespaceMapping, variableToValueMap, functionLibrary, null, null, (LocationData) currentElement.getData()); final float[] positions = groupContext.acroFields.getFieldPositions(fieldName); if (positions != null) { final Rectangle rectangle = new Rectangle(positions[1], positions[2], positions[3], positions[4]); // This scales the image so that it fits in the box (but the aspect ratio is not changed) image.scaleToFit(rectangle.getWidth(), rectangle.getHeight()); final float yPosition = positions[2] + rectangle.getHeight() - image.getScaledHeight(); image.setAbsolutePosition( positions[1] + (rectangle.getWidth() - image.getScaledWidth()) / 2, yPosition); // Add image groupContext.contentByte.addImage(image); } } else { // Use position, etc. final String leftAttribute = currentElement.attributeValue("left"); final String topAttribute = currentElement.attributeValue("top"); final String scalePercentAttribute = currentElement.attributeValue("scale-percent"); final String dpiAttribute = currentElement.attributeValue("dpi"); final String leftPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, leftAttribute); final String topPosition = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, topAttribute); final float xPosition = Float.parseFloat(leftPosition) + groupContext.offsetX; final float yPosition = groupContext.pageHeight - (Float.parseFloat(topPosition) + groupContext.offsetY); final String scalePercent = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, scalePercentAttribute); final String dpi = resolveAttributeValueTemplates(pipelineContext, contextNode, variableToValueMap, null, null, currentElement, dpiAttribute); // Set image parameters image.setAbsolutePosition(xPosition, yPosition); if (scalePercent != null) { image.scalePercent(Float.parseFloat(scalePercent)); } if (dpi != null) { final int dpiInt = Integer.parseInt(dpi); image.setDpi(dpiInt, dpiInt); } // Add image groupContext.contentByte.addImage(image); } } else { // NOP } } }
From source file:org.sakaiproject.tool.assessment.pdf.itext.HTMLWorker.java
License:Mozilla Public License
public void startElement(String tag, HashMap h) { if (!tagsSupported.containsKey(tag)) return;// w w w . j av a 2 s. c om try { style.applyStyle(tag, h); String follow = (String) FactoryProperties.followTags.get(tag); if (follow != null) { HashMap prop = new HashMap(); prop.put(follow, null); cprops.addToChain(follow, prop); return; } FactoryProperties.insertStyle(h); if (tag.equals("a")) { cprops.addToChain(tag, h); if (currentParagraph == null) currentParagraph = new Paragraph(); stack.push(currentParagraph); currentParagraph = new Paragraph(); return; } if (tag.equals("br")) { if (currentParagraph == null) currentParagraph = new Paragraph(); currentParagraph.add(factoryProperties.createChunk("\n", cprops)); return; } if (tag.equals("hr")) { PdfPTable hr = new PdfPTable(1); hr.setHorizontalAlignment(Element.ALIGN_CENTER); hr.setWidthPercentage(100f); hr.setSpacingAfter(0f); hr.setSpacingBefore(0f); PdfPCell cell = new PdfPCell(); cell.setUseVariableBorders(true); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(PdfPCell.BOTTOM); cell.setBorderWidth(1f); cell.setPadding(0); cell.addElement(factoryProperties.createChunk("\n", cprops)); hr.addCell(cell); // paragraphs can't have tables? really? without it hr's may be rendered a bit early.. //if (currentParagraph != null) // currentParagraph.add(hr); //else document.add(hr); return; } if (tag.equals("font") || tag.equals("span")) { cprops.addToChain(tag, h); return; } if (tag.equals("img")) { String src = (String) h.get("src"); if (src == null) return; cprops.addToChain(tag, h); Image img = null; if (interfaceProps != null) { HashMap images = (HashMap) interfaceProps.get("img_static"); if (images != null) { Image tim = (Image) images.get(src); if (tim != null) img = Image.getInstance(tim); } else { if (!src.startsWith("http")) { // relative src references only String baseurl = (String) interfaceProps.get("img_baseurl"); if (baseurl != null) { src = baseurl + src; img = Image.getInstance(src); } } } } if (img == null) { if (!src.startsWith("http")) { String path = cprops.getProperty("image_path"); if (path == null) path = ""; src = new File(path, src).getPath(); img = Image.getInstance(src); } else { byte[] buffer; String srcResource = src.substring(src.indexOf("/content", 0)).replaceAll("/content", ""); buffer = getImageStream(URLDecoder.decode(srcResource)); img = Image.getInstance(buffer); } } String align = (String) h.get("align"); String width = (String) h.get("width"); String height = (String) h.get("height"); String border = (String) h.get("border"); String hspace = (String) h.get("hspace"); String vspace = (String) h.get("vspace"); String before = cprops.getProperty("before"); String after = cprops.getProperty("after"); float wp = 0.0f; float lp = 0.0f; if (maxWidth > 0 && ((width != null && Integer.parseInt(width) > maxWidth) || (width == null && (int) img.getWidth() > maxWidth))) { wp = lengthParse(String.valueOf(maxWidth), (int) img.getWidth()); lp = wp; } else { wp = lengthParse(width, (int) img.getWidth()); lp = lengthParse(height, (int) img.getHeight()); } if (wp > 0 && lp > 0) img.scalePercent(wp, lp); else if (wp > 0) img.scalePercent(wp); else if (lp > 0) img.scalePercent(lp); img.setWidthPercentage(0); // border if (border != null && !"".equals(border)) { try { img.setBorderWidth(Integer.parseInt(border)); img.setBorder(Image.BOX); } catch (Exception e) { e.printStackTrace(); } } // horizonatal space if (hspace != null && !"".equals(hspace)) { try { img.setSpacingAfter(Float.parseFloat(hspace)); img.setSpacingBefore(Float.parseFloat(hspace)); } catch (Exception e) { e.printStackTrace(); } } // horizontal alignment if (align != null && (align.equalsIgnoreCase("left") || align.equalsIgnoreCase("right"))) { endElement("p"); int ralign = Image.LEFT; if (align.equalsIgnoreCase("right")) ralign = Image.RIGHT; img.setAlignment(ralign | Image.TEXTWRAP); Img i = null; boolean skip = false; if (interfaceProps != null) { i = (Img) interfaceProps.get("img_interface"); if (i != null) skip = i.process(img, h, cprops, document); } if (!skip) document.add(img); cprops.removeChain(tag); } // vertical alignment (or none) else { img.setAlignment(Image.TEXTWRAP); float bottom = 0.0f; float top = img.getTop(); float prevHeight = 0.0f; float prevRise = 0.0f; if (currentParagraph != null) { ArrayList chunks = currentParagraph.getChunks(); Chunk sibling = null; for (int k = chunks.size() - 1; k >= 0; k--) { if (chunks.get(k) != null) sibling = (Chunk) chunks.get(k); } if (sibling != null) { if (sibling.hasAttributes()) prevRise = sibling.getTextRise(); prevHeight = 0.0f; if (sibling.getFont() != null) { prevHeight = sibling.getFont().getCalculatedSize(); } } } if ("absMiddle".equalsIgnoreCase(align)) { if (prevHeight > 0) bottom += (img.getScaledHeight() / 2.0f) - (prevHeight / 2.0f); else if (img.getScaledHeight() > 0) bottom += img.getScaledHeight() / 2.0f; } else if ("middle".equalsIgnoreCase(align)) { if (img.getScaledHeight() > 0) bottom += (img.getScaledHeight() / 2.0f); } else if ("bottom".equalsIgnoreCase(align) || "baseline".equalsIgnoreCase(align) || "absbottom".equalsIgnoreCase(align)) { //baseline and absbottom should have some slight tweeking from bottom, but not sure what?? } else if ("top".equalsIgnoreCase(align)) { bottom += img.getScaledHeight() - prevHeight; } else if ("texttop".equalsIgnoreCase(align)) { bottom += img.getScaledHeight() - (prevHeight - prevRise); } cprops.removeChain(tag); if (currentParagraph == null) { currentParagraph = FactoryProperties.createParagraph(cprops); bottom = 0f; } else if (currentParagraph.isEmpty()) { bottom = 0f; } currentParagraph.setLeading(2f + bottom, 1.00f); currentParagraph.add(new Chunk(img, 0, 0 - bottom)); } return; } if (tag.equals("blockquote")) { cprops.addToChain(tag, h); inBLOCK = true; if (currentParagraph != null) endElement("p"); currentParagraph = FactoryProperties.createParagraph(cprops); currentParagraph.add(factoryProperties.createChunk("\n", cprops)); return; } endElement("p"); if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5") || tag.equals("h6")) { if (!h.containsKey("size")) { int v = 8 - Integer.parseInt(tag.substring(1)); h.put("size", Integer.toString(v)); } cprops.addToChain(tag, h); return; } if (tag.equals("ul")) { if (pendingLI) endElement("li"); skipText = true; cprops.addToChain(tag, h); com.lowagie.text.List list = new com.lowagie.text.List(false, 10); list.setListSymbol("\u2022"); stack.push(list); return; } if (tag.equals("ol")) { if (pendingLI) endElement("li"); skipText = true; cprops.addToChain(tag, h); com.lowagie.text.List list = new com.lowagie.text.List(true, 10); stack.push(list); return; } if (tag.equals("li")) { if (pendingLI) endElement("li"); skipText = false; pendingLI = true; cprops.addToChain(tag, h); stack.push(FactoryProperties.createListItem(cprops)); return; } if (tag.equals("div") || tag.equals("body")) { cprops.addToChain(tag, h); return; } if (tag.equals("pre")) { if (!h.containsKey("face")) { h.put("face", "Courier"); } cprops.addToChain(tag, h); isPRE = true; return; } if (tag.equals("p")) { cprops.addToChain(tag, h); currentParagraph = FactoryProperties.createParagraph(cprops); if (inBLOCK) { currentParagraph.setIndentationLeft(currentParagraph.getIndentationLeft() + 40.0F); } return; } if (tag.equals("tr")) { if (pendingTR) endElement("tr"); skipText = true; pendingTR = true; cprops.addToChain("tr", h); return; } if (tag.equals("td") || tag.equals("th")) { if (pendingTD) endElement(tag); skipText = false; pendingTD = true; cprops.addToChain("td", h); stack.push(new IncCell(tag, cprops)); return; } if (tag.equals("table")) { cprops.addToChain("table", h); IncTable table = new IncTable(h); stack.push(table); tableState.push(new boolean[] { pendingTR, pendingTD }); pendingTR = pendingTD = false; skipText = true; return; } } catch (Exception e) { e.printStackTrace(); //throw new ExceptionConverter(e); } }
From source file:org.silverpeas.core.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file//ww w. j a v a2s . c om * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new SilverpeasRuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new SilverpeasRuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverLogger.getLogger(PdfUtil.class).error(e); throw new SilverpeasRuntimeException( "A problem has occurred during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.silverpeas.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file/*from w w w . j av a2 s .c o m*/ * @param pdfDestination the destination pdf file, with the image under or over content * @param isBackground indicates if image is addes under or over the content of the pdf source * file */ private static void addImageOnEachPage(InputStream pdfSource, File imageToAdd, OutputStream pdfDestination, final boolean isBackground) { // Verify given arguments if (imageToAdd == null || !imageToAdd.isFile()) { throw new RuntimeException("The image file doesn't exist"); } else if (!FileUtil.isImage(imageToAdd.getPath())) { throw new RuntimeException("The picture to add is not an image file"); } PdfReader reader = null; try { // Get a reader of PDF content reader = new PdfReader(pdfSource); // Obtain the total number of pages int pdfNbPages = reader.getNumberOfPages(); PdfStamper stamper = new PdfStamper(reader, pdfDestination); // Load the image Image image = Image.getInstance(imageToAdd.getPath()); float imageWidth = image.getWidth(); float imageHeigth = image.getHeight(); // Adding the image on each page of the PDF for (int i = 1; i <= pdfNbPages; i++) { // Page sizes Rectangle rectangle = reader.getPageSize(i); // Compute the scale of the image float scale = Math.min(100, (rectangle.getWidth() / imageWidth * 100)); image.scalePercent(Math.min(scale, (rectangle.getHeight() / imageHeigth * 100))); // Setting the image position for the current page image.setAbsolutePosition(computeImageCenterPosition(rectangle.getWidth(), image.getScaledWidth()), computeImageCenterPosition(rectangle.getHeight(), image.getScaledHeight())); // Adding image PdfContentByte imageContainer = isBackground ? stamper.getUnderContent(i) : stamper.getOverContent(i); imageContainer.addImage(image); } // End of the treatment : closing the stamper stamper.close(); } catch (Exception e) { SilverTrace.error("util", "PdfUtil.stamp", "EX_ERROR_PDF_ADD_WATERWARK", e); throw new RuntimeException("A problem has occured during the adding of an image into a pdf file", e); } finally { if (reader != null) { reader.close(); } } }
From source file:org.sipfoundry.faxrx.FaxProcessor.java
License:Open Source License
private File tiff2Pdf(File tiffFile) { Pattern pattern = Pattern.compile("(.*).tiff"); Matcher matcher = pattern.matcher(tiffFile.getName()); boolean matchFound = matcher.find(); // check if tiffFile is actually a TIFF file, just in case if (matchFound) { // located at default tmp-file directory File pdfFile = new File(System.getProperty("java.io.tmpdir"), matcher.group(1) + ".pdf"); try {// www. j a v a 2s. c om // read TIFF file RandomAccessFileOrArray tiff = new RandomAccessFileOrArray(tiffFile.getAbsolutePath()); // get number of pages of TIFF file int pages = TiffImage.getNumberOfPages(tiff); // create PDF file Document pdf = new Document(PageSize.LETTER, 0, 0, 0, 0); PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(pdfFile)); writer.setStrictImageSequence(true); // open PDF filex pdf.open(); PdfContentByte contentByte = writer.getDirectContent(); // write PDF file page by page for (int page = 1; page <= pages; page++) { Image temp = TiffImage.getTiffImage(tiff, page); temp.scalePercent(7200f / temp.getDpiX(), 7200f / temp.getDpiY()); pdf.setPageSize(new Rectangle(temp.getScaledWidth(), temp.getScaledHeight())); temp.setAbsolutePosition(0, 0); contentByte.addImage(temp); pdf.newPage(); } // close PDF file pdf.close(); } catch (Exception e) { LOG.error("faxrx::tiff2Pdf error " + e.getMessage()); e.printStackTrace(); return null; } return pdfFile; } else { return null; } }