List of usage examples for com.lowagie.text Image scalePercent
public void scalePercent(float percentX, float percentY)
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;//from w w w . java 2s.c o m 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.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 w w w .ja va2 s .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; } }
From source file:ugh.fileformats.pdf.PortableDocumentFormat.java
License:Open Source License
/*************************************************************************** * @param document/* ww w. ja va 2 s . com*/ * @param cf * @return **************************************************************************/ private boolean writeTIFFImage(com.lowagie.text.Document document, ContentFile cf) { RenderedOp inImage = null; RenderedOp outImage = null; Image itextimg = null; // Read metadata. String xresolution_string = null; String yresolution_string = null; String samples_string = null; String bitspersamples_string = null; String height_string = null; String width_string = null; long orig_width = 0; long orig_height = 0; List<Metadata> allMD = cf.getAllMetadata(); // No metadata available. if (allMD == null) { return false; } Iterator<Metadata> it = allMD.iterator(); while (it.hasNext()) { Metadata md = it.next(); if (md.getType().getName().equals("ugh_height")) { height_string = md.getValue(); } if (md.getType().getName().equals("ugh_width")) { width_string = md.getValue(); } if (md.getType().getName().equals("ugh_xresolution")) { xresolution_string = md.getValue(); } if (md.getType().getName().equals("ugh_yresolution")) { yresolution_string = md.getValue(); } if (md.getType().getName().equals("ugh_samples")) { samples_string = md.getValue(); } if (md.getType().getName().equals("ugh_bitspersamples")) { bitspersamples_string = md.getValue(); } } if (xresolution_string == null || yresolution_string == null || height_string == null || width_string == null || samples_string == null || bitspersamples_string == null) { System.err .println("ERROR: Can't get all needed technical metadata for contentfile " + cf.getLocation()); return false; } int xresolution = Integer.parseInt(xresolution_string); int yresolution = Integer.parseInt(yresolution_string); // Read tiff file and convert it to Buffered Images. try { FileSeekableStream ffs = new FileSeekableStream(cf.getLocation()); // Create an image for Java Advanced Imaging. inImage = JAI.create("stream", ffs); orig_width = inImage.getWidth(); orig_height = inImage.getHeight(); } catch (IOException ioe) { System.err.println("Can't read contentfile " + cf.getLocation()); return false; } // Set scaling factor; usually we had to calculate it. int scale = 100; ParameterBlock params = new ParameterBlock(); params.addSource(inImage); params.add(scale); params.add(scale); params.add(0.0F); params.add(0.0F); params.add(new InterpolationNearest()); outImage = JAI.create("scale", params); // Create buffered image. BufferedImage newbi = outImage.getAsBufferedImage(); try { itextimg = Image.getInstance(newbi, null, true); } catch (IOException ioe) { } catch (BadElementException bee) { } // Define page size. int page_w = 210; int page_h = 297; // Scale image, if it doesn't fit on page. float page_w_pixel = (float) (page_w * xresolution / 25.4); float page_h_pixel = (float) (page_h * yresolution / 25.4); // Calculate actual scale factor. // // Check, if image will fit on page. if ((orig_width > page_w_pixel) || (orig_height > page_h_pixel)) { // Does not fit on page. float scalefactor = 0; float scalefactor_w = page_w_pixel / orig_width; float scalefactor_h = page_h_pixel / orig_height; if (scalefactor_h < scalefactor_w) { scalefactor = scalefactor_h; } else { scalefactor = scalefactor_w; } // orig_width = (long) (orig_width * scalefactor); // orig_height = (long) (orig_height * scalefactor); // Do scaling. itextimg.scalePercent((72f / xresolution * 100) * scalefactor, (72f / yresolution * 100) * scalefactor); } else { // Do scaling. itextimg.scalePercent((72f / xresolution * 100), (72f / yresolution * 100)); } // Add page. try { document.add(itextimg); // Create new page. document.newPage(); } catch (DocumentException de) { System.err.println("PortableDocumentFormat: DocumentException for Contentfile " + cf.getLocation()); } return true; }