List of usage examples for com.lowagie.text Image getDpiY
public int getDpiY()
From source file:AppletViewer.java
License:Open Source License
/** * Metodo que crea un PDF a partir del archivo TIF con sus anotaciones * @param docid// www . j a va 2 s . co m */ public void convertDocument(String docid) { try { File dir = new File(descargados); if (!dir.exists()) { dir.mkdirs(); } dir = new File(transferencias); if (!dir.exists()) { dir.mkdirs(); } // CARGAR TIF CON ANOTACIONES String tmpFileName = "TMP" + String.valueOf(System.currentTimeMillis()) + ".tif"; OutputStream output = new FileOutputStream(descargados + File.separator + tmpFileName); myGenDocViewer.exportDocument(output, true, false, "image/tiff"); output.close(); // CONVERTIR TIF A PDF RandomAccessFileOrArray myTiffFile = new RandomAccessFileOrArray( descargados + File.separator + tmpFileName); int numberOfPages = TiffImage.getNumberOfPages(myTiffFile); Document TifftoPDF = new Document(); TifftoPDF.setMargins(0, 0, 0, 0); PdfWriter.getInstance(TifftoPDF, new FileOutputStream(transferencias + File.separator + type + "-AN.pdf")); TifftoPDF.open(); for (int i = 1; i <= numberOfPages; i++) { Image tempImage = TiffImage.getTiffImage(myTiffFile, i); float dpiX = tempImage.getDpiX() == 0 ? 200 : tempImage.getDpiX(); float dpiY = tempImage.getDpiY() == 0 ? 200 : tempImage.getDpiY(); float factorX = 72 / dpiX; float factorY = 72 / dpiY; tempImage.scaleAbsolute(factorX * tempImage.getWidth(), factorY * tempImage.getHeight()); TifftoPDF.add(tempImage); } myTiffFile.close(); TifftoPDF.close(); // BORRAR EL TIFF File file = new File(descargados + File.separator + tmpFileName); if (file.delete()) { System.out.println(file.getName() + " eliminado"); } else { file.deleteOnExit(); ; System.out.println("Eliminacion fallo"); } System.out.println("Fin de la creacion del PDF con anotaciones"); } catch (Exception e) { e.printStackTrace(); } }
From source file:convert.Convertings.java
public void convertTif2PDF(String tifPath, String path) { System.out.println("one"); String arg[] = { tifPath };//from ww w.j av a 2s . co m System.out.println("one2"); if (arg.length < 1) { System.out.println("Usage: Tiff2Pdf file1.tif [file2.tif ... fileN.tif]"); System.exit(1); } String tiff; String pdf; System.out.println("two"); for (int i = 0; i < arg.length; i++) { tiff = arg[i]; pdf = path + ".pdf"; Document document = new Document(PageSize.LETTER, 0, 0, 0, 0); try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf)); int pages = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); RandomAccessFileOrArray ra = null; int comps = 0; try { ra = new RandomAccessFileOrArray(tiff); comps = TiffImage.getNumberOfPages(ra); } catch (Throwable e) { System.out.println("Exception in " + tiff + " " + e.getMessage()); continue; } System.out.println("Processing: " + tiff); for (int c = 0; c < comps; ++c) { try { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { System.out.println("page " + (c + 1)); System.out.println("img.getDpiX() : " + img.getDpiX()); System.out.println("img.getDpiY() : " + img.getDpiY()); img.scalePercent(6200f / img.getDpiX(), 6200f / img.getDpiY()); //img.scalePercent(img.getDpiX(), img.getDpiY()); //document.setPageSize(new Rectangle(img.getScaledWidth(), img.getScaledHeight())); img.setAbsolutePosition(0, 0); cb.addImage(img); document.newPage(); ++pages; } } catch (Throwable e) { System.out.println("Exception " + tiff + " page " + (c + 1) + " " + e.getMessage()); } } ra.close(); document.close(); } catch (Throwable e) { e.printStackTrace(); } System.out.println("done"); } }
From source file:cz.incad.kramerius.pdf.impl.AbstractPDFRenderSupport.java
License:Open Source License
public static ScaledImageOptions insertJavaImage(Document document, float percentage, BufferedImage javaImg) throws IOException, BadElementException, MalformedURLException, DocumentException { ByteArrayOutputStream bos = new ByteArrayOutputStream(); writeImageToStream(javaImg, "jpeg", bos); com.lowagie.text.Image img = com.lowagie.text.Image.getInstance(bos.toByteArray()); Float ratio = ratio(document, percentage, javaImg); int fitToPageWidth = (int) (javaImg.getWidth(null) * ratio); int fitToPageHeight = (int) (javaImg.getHeight(null) * ratio); int offsetX = ((int) document.getPageSize().getWidth() - fitToPageWidth) / 2; int offsetY = ((int) document.getPageSize().getHeight() - fitToPageHeight) / 2; img.scaleAbsoluteHeight(ratio * img.getHeight()); img.scaleAbsoluteWidth(ratio * img.getWidth()); img.setAbsolutePosition((offsetX),/*from ww w . j a va 2s . c o m*/ document.getPageSize().getHeight() - offsetY - (ratio * img.getHeight())); document.add(img); ScaledImageOptions options = new ScaledImageOptions(); options.setXdpi(img.getDpiX()); options.setYdpi(img.getDpiY()); options.setXoffset(offsetX); options.setYoffset(offsetY); options.setWidth(fitToPageWidth); options.setHeight(fitToPageHeight); options.setScaleFactor(ratio); return options; }
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 ww w . java2s. c o 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:mx.randalf.digital.ocr.hocrtopdf.HocrToPdf.java
License:Open Source License
public void hocrToPdf(File fImg, File fHtml, File fPdf) throws IOException, DocumentException, Exception { URL inputHOCRFile = null;/* ww w . j ava 2 s .co m*/ FileOutputStream outputPDFStream = null; // The resolution of a PDF file (using iText) is 72pt per inch float pointsPerInch = 72.0f; Source source = null; StartTag pageTag = null; Pattern imagePattern = null; Matcher imageMatcher = null; // Load the image Image pageImage = null; float dotsPerPointX; float dotsPerPointY; float pageImagePixelHeight; Document pdfDocument = null; PdfWriter pdfWriter = null; Font defaultFont = null; PdfContentByte cb = null; Pattern bboxPattern = null; Pattern bboxCoordinatePattern = null; StartTag ocrLineTag = null; try { try { inputHOCRFile = new URL("file://" + fHtml.getAbsolutePath()); } catch (MalformedURLException e) { throw e; } try { outputPDFStream = new FileOutputStream(fPdf); } catch (FileNotFoundException e) { throw e; } // Using the jericho library to parse the HTML file source = new Source(inputHOCRFile); // Find the tag of class ocr_page in order to load the scanned image pageTag = source.findNextStartTag(0, "class", "ocr_page", false); imagePattern = Pattern.compile("image\\s+([^;]+)"); imageMatcher = imagePattern.matcher(pageTag.getElement().getAttributeValue("title")); if (!imageMatcher.find()) { throw new Exception("Could not find a tag of class \"ocr_page\", aborting."); } try { pageImage = Image.getInstance(new URL("file://" + fImg.getAbsolutePath())); } catch (MalformedURLException e) { throw e; } dotsPerPointX = pageImage.getDpiX() / pointsPerInch; dotsPerPointY = pageImage.getDpiY() / pointsPerInch; pageImagePixelHeight = pageImage.getHeight(); pdfDocument = new Document( new Rectangle(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY)); pdfWriter = PdfWriter.getInstance(pdfDocument, outputPDFStream); pdfDocument.open(); // first define a standard font for our text defaultFont = FontFactory.getFont(FontFactory.HELVETICA, 8, Font.BOLD, CMYKColor.BLACK); // Put the text behind the picture (reverse for debugging) cb = pdfWriter.getDirectContentUnder(); //PdfContentByte cb = pdfWriter.getDirectContent(); pageImage.scaleToFit(pageImage.getWidth() / dotsPerPointX, pageImage.getHeight() / dotsPerPointY); pageImage.setAbsolutePosition(0, 0); // Put the image in front of the text (reverse for debugging) pdfWriter.getDirectContent().addImage(pageImage); //pdfWriter.getDirectContentUnder().addImage(pageImage); // In order to place text behind the recognised text snippets we are interested in the bbox property bboxPattern = Pattern.compile("bbox(\\s+\\d+){4}"); // This pattern separates the coordinates of the bbox property bboxCoordinatePattern = Pattern.compile("(\\d+)\\s+(\\d+)\\s+(\\d+)\\s+(\\d+)"); // Only tags of the ocr_line class are interesting ocrLineTag = source.findNextStartTag(0, "class", "ocr_line", false); while (ocrLineTag != null) { au.id.jericho.lib.html.Element lineElement = ocrLineTag.getElement(); Matcher bboxMatcher = bboxPattern.matcher(lineElement.getAttributeValue("title")); if (bboxMatcher.find()) { // We found a tag of the ocr_line class containing a bbox property Matcher bboxCoordinateMatcher = bboxCoordinatePattern.matcher(bboxMatcher.group()); bboxCoordinateMatcher.find(); int[] coordinates = { Integer.parseInt((bboxCoordinateMatcher.group(1))), Integer.parseInt((bboxCoordinateMatcher.group(2))), Integer.parseInt((bboxCoordinateMatcher.group(3))), Integer.parseInt((bboxCoordinateMatcher.group(4))) }; String line = lineElement.getContent().extractText(); // float bboxWidthPt = (coordinates[2] - coordinates[0]) / dotsPerPointX; float bboxHeightPt = (coordinates[3] - coordinates[1]) / dotsPerPointY; // Put the text into the PDF cb.beginText(); // Comment the next line to debug the PDF output (visible Text) cb.setTextRenderingMode(PdfContentByte.TEXT_RENDER_MODE_INVISIBLE); // TODO: Scale the text width to fit the OCR bbox cb.setFontAndSize(defaultFont.getBaseFont(), Math.round(bboxHeightPt)); cb.moveText((float) (coordinates[0] / dotsPerPointX), (float) ((pageImagePixelHeight - coordinates[3]) / dotsPerPointY)); cb.showText(line); cb.endText(); } ocrLineTag = source.findNextStartTag(ocrLineTag.getEnd(), "class", "ocr_line", false); } } catch (NumberFormatException e) { throw e; } catch (MalformedURLException e) { throw e; } catch (FileNotFoundException e) { throw e; } catch (BadElementException e) { throw e; } catch (IOException e) { throw e; } catch (DocumentException e) { throw e; } catch (Exception e) { throw e; } finally { if (pdfDocument != null) { pdfDocument.close(); } if (outputPDFStream != null) { outputPDFStream.close(); } } }
From source file:org.eclipse.birt.report.engine.emitter.pdf.PDFPage.java
License:Open Source License
protected void drawBackgroundImage(float x, float y, float width, float height, float imageWidth, float imageHeight, int repeat, String imageUrl, byte[] imageData, float offsetX, float offsetY) throws Exception { contentByte.saveState();//from w ww.j a v a 2 s .c o m clip(x, y, width, height); PdfTemplate image = null; if (imageUrl != null) { if (pageDevice.getImageCache().containsKey(imageUrl)) { image = pageDevice.getImageCache().get(imageUrl); } } if (image == null) { Image img = Image.getInstance(imageData); if (imageHeight == 0 || imageWidth == 0) { int resolutionX = img.getDpiX(); int resolutionY = img.getDpiY(); if (0 == resolutionX || 0 == resolutionY) { resolutionX = 96; resolutionY = 96; } imageWidth = img.getPlainWidth() / resolutionX * 72; imageHeight = img.getPlainHeight() / resolutionY * 72; } image = contentByte.createTemplate(imageWidth, imageHeight); image.addImage(img, imageWidth, 0, 0, imageHeight, 0, 0); if (imageUrl != null && image != null) { pageDevice.getImageCache().put(imageUrl, image); } } boolean xExtended = (repeat & BackgroundImageInfo.REPEAT_X) == BackgroundImageInfo.REPEAT_X; boolean yExtended = (repeat & BackgroundImageInfo.REPEAT_Y) == BackgroundImageInfo.REPEAT_Y; imageWidth = image.getWidth(); imageHeight = image.getHeight(); float originalX = offsetX; float originalY = offsetY; if (xExtended) { while (originalX > 0) originalX -= imageWidth; } if (yExtended) { while (originalY > 0) originalY -= imageHeight; } float startY = originalY; do { float startX = originalX; do { drawImage(image, x + startX, y + startY, imageWidth, imageHeight); startX += imageWidth; } while (startX < width && xExtended); startY += imageHeight; } while (startY < height && yExtended); contentByte.restoreState(); }
From source file:org.eclipse.birt.report.engine.layout.pdf.emitter.ImageLayout.java
License:Open Source License
/** * get intrinsic dimension of image in pixels. Now only support png, bmp, * jpg, gif./* ww w .j av a2s . c o m*/ * * @return * @throws IOException * @throws MalformedURLException * @throws BadElementException */ protected Dimension getIntrinsicDimension(IImageContent content, Image image) throws BadElementException, MalformedURLException, IOException { if (image != null) { // The DPI resolution of the image. // the preference of the DPI setting is: // 1. the resolution restored in content. // 2. the resolution in image file. // 3. use the DPI in render options. // 4. the DPI in report designHandle. // 5. the JRE screen resolution. // 6. the default DPI (96). int contentResolution = content.getResolution(); if (contentResolution != 0) { resolutionX = contentResolution; resolutionY = contentResolution; } else { resolutionX = PropertyUtil.getImageDpi(content, image.getDpiX(), context.getDpi()); resolutionY = PropertyUtil.getImageDpi(content, image.getDpiY(), context.getDpi()); } return new Dimension((int) (image.getPlainWidth() * 1000 / resolutionX * 72), (int) (image.getPlainHeight() * 1000 / resolutionY * 72)); } return null; }
From source file:org.eclipse.birt.report.engine.nLayout.area.impl.ContainerArea.java
License:Open Source License
protected void updateBackgroundImage() { BackgroundImageInfo bgi = boxStyle.getBackgroundImage(); Image img = null; if (bgi != null) { img = bgi.getImageInstance();/*from w ww .j a v a 2s .co m*/ if (img != null) { int resolutionX = img.getDpiX(); int resolutionY = img.getDpiY(); if (0 == resolutionX || 0 == resolutionY) { resolutionX = 96; resolutionY = 96; } float imageWidth = img.getPlainWidth() / resolutionX * 72; float imageHeight = img.getPlainHeight() / resolutionY * 72; if (content != null) { IStyle style = content.getComputedStyle(); int ox = getDimensionValue(style.getProperty(IStyle.STYLE_BACKGROUND_POSITION_X), (width - (int) (imageWidth * PDFConstants.LAYOUT_TO_PDF_RATIO))); int oy = getDimensionValue(style.getProperty(IStyle.STYLE_BACKGROUND_POSITION_Y), (height - (int) (imageHeight * PDFConstants.LAYOUT_TO_PDF_RATIO))); bgi.setXOffset(ox); bgi.setYOffset(oy); } } } }
From source file:org.eclipse.birt.report.engine.nLayout.area.impl.PageArea.java
License:Open Source License
protected BackgroundImageInfo createBackgroundImage(String url) { ResourceLocatorWrapper rl = null;//from w w w . j a v a 2 s.co m ExecutionContext exeContext = ((ReportContent) content.getReportContent()).getExecutionContext(); if (exeContext != null) { rl = exeContext.getResourceLocator(); } IStyle cs = pageContent.getComputedStyle(); BackgroundImageInfo backgroundImage = new BackgroundImageInfo(url, cs.getProperty(IStyle.STYLE_BACKGROUND_REPEAT), 0, 0, 0, 0, rl); Image img = backgroundImage.getImageInstance(); IStyle style = pageContent.getStyle(); String widthStr = style.getBackgroundWidth(); String heightStr = style.getBackgroundHeight(); if (img != null) { int resolutionX = img.getDpiX(); int resolutionY = img.getDpiY(); if (0 == resolutionX || 0 == resolutionY) { resolutionX = 96; resolutionY = 96; } float imageWidth = img.getPlainWidth() / resolutionX * 72 * PDFConstants.LAYOUT_TO_PDF_RATIO; float imageHeight = img.getPlainHeight() / resolutionY * 72 * PDFConstants.LAYOUT_TO_PDF_RATIO; int actualWidth = (int) imageWidth; int actualHeight = (int) imageHeight; if (widthStr != null && widthStr.length() > 0 || heightStr != null && heightStr.length() > 0) { if ("contain".equals(widthStr) || "contain".equals(heightStr)) { float rh = imageHeight / height; float rw = imageWidth / width; if (rh > rw) { actualHeight = height; actualWidth = (int) (imageWidth * height / imageHeight); } else { actualWidth = width; actualHeight = (int) (imageHeight * width / imageWidth); } } else if ("cover".equals(widthStr) || "cover".equals(heightStr)) { float rh = imageHeight / height; float rw = imageWidth / width; if (rh > rw) { actualWidth = width; actualHeight = (int) (imageHeight * width / imageWidth); } else { actualHeight = height; actualWidth = (int) (imageWidth * height / imageHeight); } } else { DimensionType widthDim = DimensionType.parserUnit(widthStr); DimensionType heightDim = DimensionType.parserUnit(heightStr); if (widthDim != null) { actualWidth = PropertyUtil.getDimensionValue(content, widthDim); if (heightDim == null) { actualHeight = (int) (imageHeight * actualWidth / imageWidth); } else { actualHeight = PropertyUtil.getDimensionValue(content, heightDim); } } else if (heightDim != null) { actualHeight = PropertyUtil.getDimensionValue(content, heightDim); if (widthDim == null) { actualWidth = (int) (imageWidth * actualHeight / imageHeight); } else { actualWidth = PropertyUtil.getDimensionValue(content, widthDim); } } else { actualHeight = (int) imageHeight; actualWidth = (int) imageWidth; } } } backgroundImage.setXOffset( getDimensionValue(cs.getProperty(IStyle.STYLE_BACKGROUND_POSITION_X), width - actualWidth)); backgroundImage.setYOffset( getDimensionValue(cs.getProperty(IStyle.STYLE_BACKGROUND_POSITION_Y), height - actualHeight)); backgroundImage.setHeight(actualHeight); backgroundImage.setWidth(actualWidth); return backgroundImage; } return null; }
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 {/*w w w .ja va 2 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; } }