List of usage examples for com.lowagie.text Image getScaledWidth
public float getScaledWidth()
From source file:com.openkm.util.DocConverter.java
License:Open Source License
/** * TIFF to PDF conversion//w w w .ja va 2s . c om */ 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 {//from ww w . j a va2 s.c o 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:mx.dr.util.report.impl.PdfService.java
License:Open Source License
/** * write a label in pdf document./* ww w . j av a2s . c o m*/ * <br/> * escribe una etiqueta en el documento pdf. * @param doc pdf document / documento pdf. * @param dto object that encompasses the values of the labels to be placed in the document / objeto que engloba los valores de las etiquetas que se colocaran en el documento. * @param offset jump on the Y axis to be given before placing the tag in the document / salto en el eje Y que se dara antes de colocar la etiqueta en el documento. * @param table container table if applicable / contenedor de tabla si es que aplica. * @throws Exception If an error occurs / si ocurre algun error. */ public void estampaEtiqueta(Document doc, Object dto, Float offset, PdfPTable table) throws Exception { List<Field> fields = new ArrayList<Field>(); for (Field m : dto.getClass().getDeclaredFields()) { m.setAccessible(true); if (m.getAnnotation(DRPdfLabel.class) != null) { fields.add(m); } } Collections.sort(fields, new Comparator<Field>() { public int compare(Field o1, Field o2) { DRPdfLabel etiqueta1 = o1.getAnnotation(DRPdfLabel.class); DRPdfLabel etiqueta2 = o2.getAnnotation(DRPdfLabel.class); String uno = int2String(etiqueta1.y()) + "." + int2String(etiqueta1.order()); String dos = int2String(etiqueta2.y()) + "." + int2String(etiqueta2.order()); return uno.compareTo(dos); } private String int2String(int num) { if (num < 10) { return "0" + num; } else { return String.valueOf(num); } } }); DRPdfLabel etiqueta; DRPdfTable etiquetaTabla; int lineaActual = 0; Paragraph pantagram = null; StringBuffer sb = null; Font font; Object valor; String label; DRPdfImage img; int residuo; int adicional = 0; for (Field m : fields) { etiqueta = m.getAnnotation(DRPdfLabel.class); img = m.getAnnotation(DRPdfImage.class); valor = m.get(dto); if (valor != null && valor instanceof List) { etiquetaTabla = m.getAnnotation(DRPdfTable.class); PdfPTable tableDance = null; if (etiquetaTabla != null) { tableDance = new PdfPTable(etiquetaTabla.colsPercentage()); tableDance.setSpacingBefore(etiqueta.offset()); for (String c : etiquetaTabla.columnLabels()) { tableDance.addCell(c); } } if (pantagram != null) { doc.add(pantagram); pantagram = null; } for (int i = 0; i < ((List) valor).size(); i++) { if (i == 0 && etiqueta.offset() > 0) { estampaEtiqueta(doc, ((List) valor).get(i), etiqueta.offset(), tableDance); } else { estampaEtiqueta(doc, ((List) valor).get(i), null, tableDance); } } if (etiquetaTabla != null) { doc.add(tableDance); } } else if (img != null) { /* File file = new File(IMGDIR + valor); FileInputStream inImg = new FileInputStream(file); byte[] b=new byte[(int)file.length()]; inImg.read(b);*/ Image ima = Image.getInstance(IMGDIR + valor); //System.out.println(ima.getPlainWidth()); ima.scaleAbsoluteWidth(img.width()); //System.out.println(ima.getScaledWidth()); ima.scaleAbsoluteHeight(ima.getScaledWidth()); ima.setAlignment(img.style()); ima.setAbsolutePosition(img.x(), img.y()); doc.add(ima); } else if (table != null) { PdfPCell cerda = null; label = value2String(valor); residuo = etiqueta.length() - label.length(); label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label; DRPdfColumn col = m.getAnnotation(DRPdfColumn.class); if (col != null) { cerda = new PdfPCell(new Paragraph(label)); cerda.setColspan(col.colspan()); table.addCell(cerda); } else { table.addCell(label); } } else { if (lineaActual < etiqueta.y()) { if (pantagram != null) { doc.add(pantagram); } if (offset == null || etiqueta.y() > 1) { if (etiqueta.offset() > 0) { pantagram = new Paragraph(etiqueta.offset()); } else { pantagram = new Paragraph(); } } else { pantagram = new Paragraph(offset); } lineaActual = etiqueta.y(); } if (etiqueta.wspacesBefore() > 0) { sb = new StringBuffer(""); fillEmpty(etiqueta.wspacesBefore(), sb); font = new Font(Font.COURIER, 12); pantagram.add(new Chunk(sb.toString(), font)); } sb = new StringBuffer(""); label = value2String(valor); residuo = etiqueta.length() - label.length(); label = etiqueta.length() > 0 && residuo < 0 ? label.substring(0, etiqueta.length()) : label; if (etiqueta.font().equals(BaseFont.COURIER)) { font = new Font(Font.COURIER, etiqueta.fontSize(), etiqueta.style(), new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2])); adicional = 0; } else { font = FontFactory.getFont(TTFDIR + etiqueta.font(), BaseFont.CP1252, BaseFont.EMBEDDED, etiqueta.fontSize(), etiqueta.style(), new Color(etiqueta.color()[0], etiqueta.color()[1], etiqueta.color()[2])); adicional = label.equals("") ? (residuo / 2) + 1 : 0; } if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.DER) && residuo > 0) { fillEmpty(residuo + adicional, sb); } sb.append(label); if (etiqueta.length() > 0 && etiqueta.justified().equals(DRPdfLabel.JUSTIFIED.IZQ) && residuo > 0) { fillEmpty(residuo + adicional, sb); } pantagram.add(new Chunk(sb.toString(), font)); } } if (pantagram != null) { doc.add(pantagram); } }
From source file:org.jrimum.bopepo.pdf.PDFs.java
License:Apache License
/** * <p>//from ww w . j a va 2 s.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 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 www .j av a 2 s . 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 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 va 2s . c o 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; }/*from ww w . j av a 2s.co 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.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/*from ww w . jav a 2s .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 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//w w w .j a va2 s. com * @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 {/*from ww w . ja v a2s . c o m*/ // 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; } }