List of usage examples for com.lowagie.text Image scaleToFit
public void scaleToFit(float fitWidth, float fitHeight)
From source file:model.relatorio.java
public void getRelatorioAluno(String idParaProcurar) throws DocumentException, FileNotFoundException, IOException { double totalAulas = 0; Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("Relatorio Aluno ID " + idParaProcurar + ".pdf")); doc.open();//from w ww . j a v a 2 s . co m Image imagem = Image.getInstance(caminhoImagemRelatorio); imagem.scaleToFit(550, 100); doc.add(imagem); doc.add(new Paragraph(" ")); doc.add(new Paragraph(" RELATORIO ALUNO")); doc.add(new Paragraph(" ")); doc.add(new Paragraph(" ")); PreparedStatement stmt = null; Connection conn = null; try { conn = ConexaoBanco.getAbreConexao(); stmt = conn.prepareStatement("select * from aluno where id_aluno = " + idParaProcurar); ResultSet rs = stmt.executeQuery(); while (rs.next()) { doc.add(new Paragraph("ID: " + rs.getInt("id_aluno") + " Nome : " + rs.getString("nome") + "\nCpf : " + rs.getString("cpf") + " Endereo : " + rs.getString("endereco") + "\nTelefone : " + rs.getString("telefone") + " Idade : " + rs.getInt("idade") + " Altura : " + rs.getString("altura") + " Peso : " + rs.getString("peso"))); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, " Erro \n" + e); } doc.add(new Paragraph(" ")); doc.add(new Paragraph(" AULAS MATRICULADAS")); try { conn = ConexaoBanco.getAbreConexao(); stmt = conn.prepareStatement("select matricula.id_matricula, aula.nome from aluno\n" + "inner join matricula\n" + "on aluno.id_aluno = matricula.id_aluno\n" + "inner join aula\n" + "on aula.id_aula = matricula.id_aula\n" + "where aluno.id_aluno =" + idParaProcurar); ResultSet rt = stmt.executeQuery(); while (rt.next()) { doc.add(new Paragraph( "ID: " + rt.getInt("id_matricula") + " | Nome : " + rt.getString("nome") + "\n")); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, " Erro \n" + e); } try { conn = ConexaoBanco.getAbreConexao(); stmt = conn.prepareStatement("select sum(aula.preco) Valor from aluno\n" + "inner join matricula\n" + "on aluno.id_aluno = matricula.id_aluno\n" + "inner join aula\n" + "on aula.id_aula = matricula.id_aula\n" + "where aluno.id_aluno =" + idParaProcurar); ResultSet rt = stmt.executeQuery(); while (rt.next()) { totalAulas += (rt.getDouble("valor")); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, " Erro \n" + e); } doc.add(new Paragraph(" ")); doc.add(new Paragraph(" ")); doc.add(new Paragraph("MENSALIDADE: " + totalAulas)); doc.close(); JOptionPane.showMessageDialog(null, " Arquivo Gerado com Sucesso! "); Desktop.getDesktop().open(new File("Relatorio Aluno ID " + idParaProcurar + ".pdf")); }
From source file:model.relatorio.java
public void getRelatorioProfessor(String idParaProcurar) throws DocumentException, FileNotFoundException, IOException { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream("Relatorio Professor ID " + idParaProcurar + ".pdf")); doc.open();/*from w w w.j av a 2s.co m*/ Image imagem = Image.getInstance(caminhoImagemRelatorio); imagem.scaleToFit(550, 100); doc.add(imagem); doc.add(new Paragraph(" ")); doc.add(new Paragraph(" RELATORIO PROFESSOR")); doc.add(new Paragraph(" ")); doc.add(new Paragraph(" ")); PreparedStatement stmt = null; Connection conn = null; try { conn = ConexaoBanco.getAbreConexao(); stmt = conn.prepareStatement("select * from professor where id_prof = " + idParaProcurar); ResultSet rs = stmt.executeQuery(); while (rs.next()) { doc.add(new Paragraph("ID: " + rs.getInt("id_prof") + " Nome : " + rs.getString("nome") + "\nCpf : " + rs.getString("cpf") + " Endereo : " + rs.getString("endereco") + "\nTelefone : " + rs.getString("telefone") + " Salario : " + rs.getDouble("salario"))); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, " Erro \n" + e); } doc.add(new Paragraph(" ")); doc.add(new Paragraph(" AULAS: ")); try { conn = ConexaoBanco.getAbreConexao(); stmt = conn.prepareStatement("select aula.horario, aula.nome from professor\n" + "inner join aula\n" + "on aula.id_prof = professor.id_prof\n" + "where professor.id_prof = " + idParaProcurar); ResultSet rt = stmt.executeQuery(); while (rt.next()) { doc.add(new Paragraph( "Horario: " + rt.getString("horario") + " | Nome : " + rt.getString("nome") + "\n")); } } catch (SQLException | HeadlessException e) { JOptionPane.showMessageDialog(null, " Erro \n" + e); } doc.close(); JOptionPane.showMessageDialog(null, " Arquivo Gerado com Sucesso! "); Desktop.getDesktop().open(new File("Relatorio Professor ID " + idParaProcurar + ".pdf")); }
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;/*from w w w.j a v a 2 s .c om*/ 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:net.filterlogic.util.imaging.ToPDF.java
License:Apache License
public static void FromTIFF(String[] files, String pdfOutFile) throws OpenCaptureImagingException { String tiff_file;//from w w w . j av a 2 s . c o m String pdf_file = pdfOutFile; try { Document document = new Document(); PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(pdf_file)); writer.setFullCompression(); int pages = 0; document.open(); PdfContentByte cb = writer.getDirectContent(); RandomAccessFileOrArray ra = null; for (int i = 0; i < files.length; i++) { int comps = 0; tiff_file = files[i]; try { ra = new RandomAccessFileOrArray(tiff_file); comps = TiffImage.getNumberOfPages(ra); } catch (Throwable e) { throw new Exception("Exception in " + tiff_file + " " + e.toString()); //continue; } //System.out.println("Processing: " + tiff_file); for (int c = 0; c < comps; ++c) { try { Image img = TiffImage.getTiffImage(ra, c + 1); if (img != null) { //System.out.println("page " + (c + 1)); img.scaleToFit(675, 775); img.setAbsolutePosition(0, 50); // document.add(new Paragraph(tiff_file + " - page " + (c + 1))); cb.addImage(img); document.newPage(); ++pages; } } catch (Throwable e) { throw new Exception("Exception " + tiff_file + " page " + (c + 1) + " " + e.getMessage()); } } ra.close(); } // close pdf document.close(); } catch (Exception e) { throw new OpenCaptureImagingException("ToPDF exception: " + e.toString()); } }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple image files to a {@link File}. * /* ww w .ja va 2 s .c o m*/ * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param files * for the PDF * @throws DocumentException * @throws IOException * @see File * @see Rectangle * @since 0.9.2 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final File... files) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, files)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == files) { throw new RuntimeExceptionIsNull("files"); //$NON-NLS-1$ } if (!HelperArray.isValid(files)) { throw new RuntimeExceptionIsEmpty("files"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); try { PdfWriter.getInstance(document, fos); document.open(); for (final File inputFile : files) { if (null == inputFile) { throw new RuntimeExceptionIsNull("inputFile"); //$NON-NLS-1$ } final Image image = Image.getInstance(inputFile.getAbsolutePath()); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } } finally { document.close(); fos.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.bogatyr.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple {@link java.awt.Image} to a {@link File}. * /* ww w. ja v a2 s.c o m*/ * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param images * for the PDF * @throws DocumentException * @throws IOException * @see File * @see java.awt.Image * @see Rectangle * @since 0.9.2 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final java.awt.Image... images) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, images)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == images) { throw new RuntimeExceptionIsNull("images"); //$NON-NLS-1$ } if (!HelperArray.isValid(images)) { throw new RuntimeExceptionIsEmpty("images"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); final FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file)); try { PdfWriter.getInstance(document, fos); document.open(); for (final java.awt.Image tempImage : images) { if (null == tempImage) { throw new RuntimeExceptionIsNull("tempImage"); //$NON-NLS-1$ } final Image image = Image.getInstance(tempImage, null); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } } finally { document.close(); fos.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple image files to a {@link File}. * //from w ww .jav a2s . com * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param files * for the PDF * @throws DocumentException * @throws IOException * @see File * @see Rectangle * @since 0.0.1 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final File... files) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, files)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == files) { throw new RuntimeExceptionIsNull("files"); //$NON-NLS-1$ } if (!HelperArray.isValid(files)) { throw new RuntimeExceptionIsEmpty("files"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); try (FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { PdfWriter.getInstance(document, fos); document.open(); for (final File inputFile : files) { if (null == inputFile) { throw new RuntimeExceptionIsNull("inputFile"); //$NON-NLS-1$ } final Image image = Image.getInstance(inputFile.getAbsolutePath()); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } document.close(); } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.laubenberger.wichtel.helper.HelperPdf.java
License:Open Source License
/** * Writes a PDF from multiple {@link java.awt.Image} to a {@link File}. * // w w w. jav a 2s .co m * @param pageSize * of the PDF * @param scale * images to fit the page size * @param file * output as PDF * @param images * for the PDF * @throws DocumentException * @throws IOException * @see File * @see java.awt.Image * @see Rectangle * @since 0.0.1 */ public static void writePdfFromImages(final Rectangle pageSize, final boolean scale, final File file, final java.awt.Image... images) throws DocumentException, IOException { // $JUnit$ if (log.isDebugEnabled()) log.debug(HelperLog.methodStart(pageSize, scale, file, images)); if (null == pageSize) { throw new RuntimeExceptionIsNull("pageSize"); //$NON-NLS-1$ } if (null == file) { throw new RuntimeExceptionIsNull("file"); //$NON-NLS-1$ } if (null == images) { throw new RuntimeExceptionIsNull("images"); //$NON-NLS-1$ } if (!HelperArray.isValid(images)) { throw new RuntimeExceptionIsEmpty("images"); //$NON-NLS-1$ } final Document document = new Document(pageSize); document.setMargins(0.0F, 0.0F, 0.0F, 0.0F); try (FilterOutputStream fos = new BufferedOutputStream(new FileOutputStream(file))) { PdfWriter.getInstance(document, fos); document.open(); for (final java.awt.Image tempImage : images) { if (null == tempImage) { throw new RuntimeExceptionIsNull("tempImage"); //$NON-NLS-1$ } final Image image = Image.getInstance(tempImage, null); if (scale) { image.scaleToFit(pageSize.getWidth(), pageSize.getHeight()); } document.add(image); document.newPage(); } } if (log.isDebugEnabled()) log.debug(HelperLog.methodExit()); }
From source file:net.sf.jasperreports.engine.export.JRPdfExporter.java
License:LGPL
/** * *///from w w w . j a va 2s. com protected void exportImage(JRPrintImage printImage) throws DocumentException, IOException, JRException { if (printImage.getMode() == JRElement.MODE_OPAQUE) { pdfContentByte.setRGBColorFill(printImage.getBackcolor().getRed(), printImage.getBackcolor().getGreen(), printImage.getBackcolor().getBlue()); pdfContentByte.rectangle(printImage.getX() + getOffsetX(), jasperPrint.getPageHeight() - printImage.getY() - getOffsetY(), printImage.getWidth(), -printImage.getHeight()); pdfContentByte.fill(); } int topPadding = printImage.getLineBox().getTopPadding().intValue(); int leftPadding = printImage.getLineBox().getLeftPadding().intValue(); int bottomPadding = printImage.getLineBox().getBottomPadding().intValue(); int rightPadding = printImage.getLineBox().getRightPadding().intValue(); int availableImageWidth = printImage.getWidth() - leftPadding - rightPadding; availableImageWidth = (availableImageWidth < 0) ? 0 : availableImageWidth; int availableImageHeight = printImage.getHeight() - topPadding - bottomPadding; availableImageHeight = (availableImageHeight < 0) ? 0 : availableImageHeight; JRRenderable renderer = printImage.getRenderer(); if (renderer != null && availableImageWidth > 0 && availableImageHeight > 0) { if (renderer.getType() == JRRenderable.TYPE_IMAGE) { // Image renderers are all asked for their image data at some point. // Better to test and replace the renderer now, in case of lazy load error. renderer = JRImageRenderer.getOnErrorRendererForImageData(renderer, printImage.getOnErrorType()); } } else { renderer = null; } if (renderer != null) { int xoffset = 0; int yoffset = 0; Chunk chunk = null; float scaledWidth = availableImageWidth; float scaledHeight = availableImageHeight; if (renderer.getType() == JRRenderable.TYPE_IMAGE) { com.lowagie.text.Image image = null; float xalignFactor = getXAlignFactor(printImage); float yalignFactor = getYAlignFactor(printImage); switch (printImage.getScaleImage()) { case JRImage.SCALE_IMAGE_CLIP: { // Image load might fail, from given image data. // Better to test and replace the renderer now, in case of lazy load error. renderer = JRImageRenderer.getOnErrorRendererForDimension(renderer, printImage.getOnErrorType()); if (renderer == null) { break; } int normalWidth = availableImageWidth; int normalHeight = availableImageHeight; Dimension2D dimension = renderer.getDimension(); if (dimension != null) { normalWidth = (int) dimension.getWidth(); normalHeight = (int) dimension.getHeight(); } xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth)); yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight)); int minWidth = Math.min(normalWidth, availableImageWidth); int minHeight = Math.min(normalHeight, availableImageHeight); BufferedImage bi = new BufferedImage(minWidth, minHeight, BufferedImage.TYPE_INT_ARGB); Graphics2D g = bi.createGraphics(); if (printImage.getMode() == JRElement.MODE_OPAQUE) { g.setColor(printImage.getBackcolor()); g.fillRect(0, 0, minWidth, minHeight); } renderer.render(g, new java.awt.Rectangle((xoffset > 0 ? 0 : xoffset), (yoffset > 0 ? 0 : yoffset), normalWidth, normalHeight)); g.dispose(); xoffset = (xoffset < 0 ? 0 : xoffset); yoffset = (yoffset < 0 ? 0 : yoffset); //awtImage = bi.getSubimage(0, 0, minWidth, minHeight); //image = com.lowagie.text.Image.getInstance(awtImage, printImage.getBackcolor()); image = com.lowagie.text.Image.getInstance(bi, null); break; } case JRImage.SCALE_IMAGE_FILL_FRAME: { if (printImage.isUsingCache() && loadedImagesMap.containsKey(renderer)) { image = (com.lowagie.text.Image) loadedImagesMap.get(renderer); } else { try { image = com.lowagie.text.Image.getInstance(renderer.getImageData()); imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0); } catch (Exception e) { JRImageRenderer tmpRenderer = JRImageRenderer.getOnErrorRendererForImage( JRImageRenderer.getInstance(renderer.getImageData()), printImage.getOnErrorType()); if (tmpRenderer == null) { break; } java.awt.Image awtImage = tmpRenderer.getImage(); image = com.lowagie.text.Image.getInstance(awtImage, null); } if (printImage.isUsingCache()) { loadedImagesMap.put(renderer, image); } } image.scaleAbsolute(availableImageWidth, availableImageHeight); break; } case JRImage.SCALE_IMAGE_RETAIN_SHAPE: default: { if (printImage.isUsingCache() && loadedImagesMap.containsKey(renderer)) { image = (com.lowagie.text.Image) loadedImagesMap.get(renderer); } else { try { image = com.lowagie.text.Image.getInstance(renderer.getImageData()); imageTesterPdfContentByte.addImage(image, 10, 0, 0, 10, 0, 0); } catch (Exception e) { JRImageRenderer tmpRenderer = JRImageRenderer.getOnErrorRendererForImage( JRImageRenderer.getInstance(renderer.getImageData()), printImage.getOnErrorType()); if (tmpRenderer == null) { break; } java.awt.Image awtImage = tmpRenderer.getImage(); image = com.lowagie.text.Image.getInstance(awtImage, null); } if (printImage.isUsingCache()) { loadedImagesMap.put(renderer, image); } } image.scaleToFit(availableImageWidth, availableImageHeight); xoffset = (int) (xalignFactor * (availableImageWidth - image.plainWidth())); yoffset = (int) (yalignFactor * (availableImageHeight - image.plainHeight())); xoffset = (xoffset < 0 ? 0 : xoffset); yoffset = (yoffset < 0 ? 0 : yoffset); break; } } if (image != null) { chunk = new Chunk(image, 0, 0); scaledWidth = image.scaledWidth(); scaledHeight = image.scaledHeight(); } } else { double normalWidth = availableImageWidth; double normalHeight = availableImageHeight; double displayWidth = availableImageWidth; double displayHeight = availableImageHeight; double ratioX = 1f; double ratioY = 1f; Rectangle2D clip = null; Dimension2D dimension = renderer.getDimension(); if (dimension != null) { normalWidth = dimension.getWidth(); normalHeight = dimension.getHeight(); displayWidth = normalWidth; displayHeight = normalHeight; float xalignFactor = getXAlignFactor(printImage); float yalignFactor = getYAlignFactor(printImage); switch (printImage.getScaleImage()) { case JRImage.SCALE_IMAGE_CLIP: { xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth)); yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight)); clip = new Rectangle2D.Double(-xoffset, -yoffset, availableImageWidth, availableImageHeight); break; } case JRImage.SCALE_IMAGE_FILL_FRAME: { ratioX = availableImageWidth / normalWidth; ratioY = availableImageHeight / normalHeight; normalWidth *= ratioX; normalHeight *= ratioY; xoffset = 0; yoffset = 0; break; } case JRImage.SCALE_IMAGE_RETAIN_SHAPE: default: { ratioX = availableImageWidth / normalWidth; ratioY = availableImageHeight / normalHeight; ratioX = ratioX < ratioY ? ratioX : ratioY; ratioY = ratioX; normalWidth *= ratioX; normalHeight *= ratioY; xoffset = (int) (xalignFactor * (availableImageWidth - normalWidth)); yoffset = (int) (yalignFactor * (availableImageHeight - normalHeight)); break; } } } PdfTemplate template = pdfContentByte.createTemplate((float) displayWidth, (float) displayHeight); Graphics2D g = forceSvgShapes ? template.createGraphicsShapes((float) displayWidth, (float) displayHeight) : template.createGraphics(availableImageWidth, availableImageHeight, new LocalFontMapper()); if (clip != null) { g.setClip(clip); } if (printImage.getMode() == JRElement.MODE_OPAQUE) { g.setColor(printImage.getBackcolor()); g.fillRect(0, 0, (int) displayWidth, (int) displayHeight); } Rectangle2D rectangle = new Rectangle2D.Double(0, 0, displayWidth, displayHeight); renderer.render(g, rectangle); g.dispose(); pdfContentByte.saveState(); pdfContentByte.addTemplate(template, (float) ratioX, 0f, 0f, (float) ratioY, printImage.getX() + getOffsetX() + xoffset, jasperPrint.getPageHeight() - printImage.getY() - getOffsetY() - (int) normalHeight - yoffset); pdfContentByte.restoreState(); Image image = getPxImage(); image.scaleAbsolute(availableImageWidth, availableImageHeight); chunk = new Chunk(image, 0, 0); } /* image.setAbsolutePosition( printImage.getX() + offsetX + borderOffset, jasperPrint.getPageHeight() - printImage.getY() - offsetY - image.scaledHeight() - borderOffset ); pdfContentByte.addImage(image); */ if (chunk != null) { setAnchor(chunk, printImage, printImage); setHyperlinkInfo(chunk, printImage); ColumnText colText = new ColumnText(pdfContentByte); int upperY = jasperPrint.getPageHeight() - printImage.getY() - topPadding - getOffsetY() - yoffset; int lowerX = printImage.getX() + leftPadding + getOffsetX() + xoffset; colText.setSimpleColumn(new Phrase(chunk), lowerX, upperY - scaledHeight, lowerX + scaledWidth, upperY, scaledHeight, Element.ALIGN_LEFT); colText.go(); } } if (printImage.getLineBox().getTopPen().getLineWidth().floatValue() <= 0f && printImage.getLineBox().getLeftPen().getLineWidth().floatValue() <= 0f && printImage.getLineBox().getBottomPen().getLineWidth().floatValue() <= 0f && printImage.getLineBox().getRightPen().getLineWidth().floatValue() <= 0f) { if (printImage.getLinePen().getLineWidth().floatValue() > 0f) { exportPen(printImage.getLinePen(), printImage); } } else { /* */ exportBox(printImage.getLineBox(), printImage); } }
From source file:optika.sql.java
public void eksportoNePdf(String id) { Document document = new Document() { };// w w w . ja va 2 s .c o m try { PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("receta.pdf")); document.open(); document.setPageSize(PageSize.A3); Image img = Image.getInstance("receta.jpg"); img.setAbsolutePosition(450f, 10f); img.scaleToFit(600, 849); img.setAlignment(Image.LEFT | Image.ALIGN_BOTTOM | Image.ALIGN_BASELINE); img.setAbsolutePosition(0, 0); document.add(img); String[][] receta = merrReceten("select * from recetat where id=" + parseInt(id) + ";"); String[][] tabela = merrReceten("select * from tabela where recetat_id=" + parseInt(id) + ";"); int[] white = new int[tabela.length]; for (int i = 0; i < tabela.length; i++) { white[i] = 0; int bosh = 0; for (int j = 3; j < tabela[i].length; j++) { if (tabela[i][j] == tabela[i][6]) { continue; } if (!tabela[i][j].isEmpty()) { bosh = 1; } } if (bosh == 0) { white[i] = 1; } } Paragraph data = new Paragraph("Data: " + receta[0][7]); data.setSpacingBefore(38); data.setSpacingAfter(40); PdfPTable table = new PdfPTable(7); if (white[0] == 0) { table.addCell(getCellPadding("" + tabela[0][3], 1)); } else { table.addCell(getCellWhite("_", 1, 30)); } table.addCell(getCellPadding("" + tabela[0][4], 1)); table.addCell(getCellPadding("" + tabela[0][5], 1)); table.addCell(getCellPadding("", 1)); table.addCell(getCellPadding("" + tabela[0][7], 1)); table.addCell(getCellPadding("" + tabela[0][8], 1)); table.addCell(getCellPadding("" + tabela[0][9], 1)); table.setWidthPercentage(105); table.setHorizontalAlignment(-100); if (white[1] == 0) { table.addCell(getCellPadding("" + tabela[1][3], 1)); } else { table.addCell(getCellWhite("_", 1, 36)); } table.addCell(getCellPadding("" + tabela[1][4], 1)); table.addCell(getCellPadding("" + tabela[1][5], 1)); table.addCell(getCellPadding("", 1)); table.addCell(getCellPadding("" + tabela[1][7], 1)); table.addCell(getCellPadding("" + tabela[1][8], 1)); table.addCell(getCellPadding("" + tabela[1][9], 1)); table.setWidthPercentage(105); table.setHorizontalAlignment(-100); if (white[2] == 0) { if (white[1] == 0) { table.addCell(getCell("" + tabela[2][3], 1, 30)); } else { table.addCell(getCellWhite("_", 1, 23)); } } else { table.addCell(getCellWhite("_", 1, 28)); } table.addCell(getCell("" + tabela[2][4], 1, 0)); table.addCell(getCell("" + tabela[2][5], 1, 0)); table.addCell(getCell("", 1, 0)); table.addCell(getCell("" + tabela[2][7], 1, 0)); table.addCell(getCell("" + tabela[2][8], 1, 0)); table.addCell(getCell("" + tabela[2][9], 1, 0)); table.setWidthPercentage(105); table.setSpacingBefore(27); table.setHorizontalAlignment(-100); String[][] distanca = merrReceten("select * from distanca where recetat_id=" + parseInt(id) + ";"); PdfPTable largAfer = new PdfPTable(3); if (distanca[0][3].isEmpty()) { PdfPCell larg = getCellWhite("_", 2, 15); largAfer.addCell(larg); } else { PdfPCell larg = new PdfPCell(new Phrase("" + distanca[0][3])); larg.setPadding(0); larg.setHorizontalAlignment(2); larg.setBorder(PdfPCell.NO_BORDER); larg.setPaddingBottom(20); largAfer.addCell(larg); } largAfer.addCell(getCell("", PdfPCell.ALIGN_RIGHT, 25)); if (distanca[0][8].isEmpty()) { largAfer.addCell(getCellWhite("_", PdfPCell.ALIGN_RIGHT, 15)); } else { largAfer.addCell(getCell("" + distanca[0][8], PdfPCell.ALIGN_RIGHT, 25)); } largAfer.setWidthPercentage(75); largAfer.setHorizontalAlignment(350); PdfPTable od_os = new PdfPTable(5); od_os.addCell(getCell("OD= " + distanca[0][4], 0, 195)); od_os.addCell(getCell("OS= " + distanca[0][5], 2, 195)); od_os.addCell(getCell("", 0, 0)); od_os.addCell(getCell("OD= " + distanca[0][9], 0, 0)); od_os.addCell(getCell("OS= " + distanca[0][10], 1, 0)); od_os.setWidthPercentage(90); od_os.setHorizontalAlignment(150); PdfPTable visusi = new PdfPTable(2); if (distanca[0][6].isEmpty()) { PdfPCell od_pa = getCellWhite("_", 2, 17); od_pa.setPaddingRight(45); visusi.addCell(od_pa); } else { PdfPCell od_pa = getCell(distanca[0][6], 2, 17); od_pa.setPaddingRight(45); visusi.addCell(od_pa); } if (distanca[0][11].isEmpty()) { visusi.addCell(getCellWhite("_", 2, 17)); } else { visusi.addCell(getCell(distanca[0][11], 2, 17)); } if (distanca[0][7].isEmpty()) { PdfPCell os_pa = getCellWhite("_", 2, 17); os_pa.setPaddingRight(45); visusi.addCell(os_pa); } else { PdfPCell os_pa = getCell(distanca[0][7], 2, 17); os_pa.setPaddingRight(45); visusi.addCell(os_pa); } if (distanca[0][12].isEmpty()) { visusi.addCell(getCellWhite("_", 2, 17)); } else { visusi.addCell(getCell(distanca[0][12], 2, 0)); } visusi.setWidthPercentage(100); visusi.setHorizontalAlignment(50); String[][] admin = merrReceten("select * from admin where id=1;"); PdfPTable klienti = new PdfPTable(3); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("Emri: " + receta[0][2], 0, 0)); klienti.addCell(getCell("Celular: " + admin[0][4], 0, 0)); klienti.addCell(getCell("", 0, 0)); PdfPCell celReceta = getCell("Celular: " + receta[0][4], 0, 0); celReceta.setPaddingTop(5); klienti.addCell(celReceta); klienti.addCell(getCell("Email: " + admin[0][5], 0, 0)); klienti.addCell(getCell("", 0, 0)); PdfPCell emailReceta = getCell("Email: " + receta[0][5], 0, 0); emailReceta.setPaddingBottom(5); emailReceta.setPaddingTop(5); klienti.addCell(emailReceta); klienti.addCell(getCell("Adresa: " + admin[0][6], 0, 0)); klienti.addCell(getCell("", 0, 0)); klienti.addCell(getCell("Adresa: " + receta[0][6], 0, 0)); klienti.setSpacingBefore(50); PdfPTable kreu = new PdfPTable(1); kreu.addCell(getCell(" ", 0, 0)); document.add(kreu); document.add(klienti); document.add(data); document.add(table); document.add(largAfer); document.add(od_os); document.add(visusi); } catch (DocumentException de) { System.err.println(de.getMessage()); } catch (IOException ioe) { System.err.println(ioe.getMessage()); } document.close(); }