List of usage examples for com.lowagie.text Image getInstance
public static Image getInstance(Image image)
From source file:org.sakaiproject.evaluation.tool.reporting.EvalPDFReportBuilder.java
License:Educational Community License
/** * @param question/* w ww .j a va 2 s . c o m*/ * the question text * @param choices * the text for the choices * @param values * the count of answers for each choice (same order as choices) * @param responseCount * the number of responses to the question * @param showPercentages * if true then show the percentages * @param answersAndMean * the text which will be displayed above the chart (normally the answers count and * mean) * @param lastElementIsHeader * If the last element was a header, the extra spacing paragraph is not needed. */ public void addLikertResponse(String question, String[] choices, int[] values, int responseCount, boolean showPercentages, String answersAndMean, boolean lastElementIsHeader) { ArrayList<Element> myElements = new ArrayList<>(); try { if (!lastElementIsHeader) { Paragraph emptyPara = new Paragraph(" "); this.addElementWithJump(emptyPara, false); } Paragraph myPara = new Paragraph(question, questionTextFont); myPara.setSpacingAfter(SPACING_AFTER_HEADER); myElements.add(myPara); EvalLikertChartBuilder chartBuilder = new EvalLikertChartBuilder(); chartBuilder.setValues(values); chartBuilder.setResponses(choices); chartBuilder.setShowPercentages(showPercentages); chartBuilder.setResponseCount(responseCount); JFreeChart chart = chartBuilder.makeLikertChart(); /* The height is going to be based off the number of choices */ int height = 15 * choices.length; PdfContentByte cb = pdfWriter.getDirectContent(); PdfTemplate tp = cb.createTemplate(200, height); Graphics2D g2d = tp.createGraphics(200, height, new DefaultFontMapper()); Rectangle2D r2d = new Rectangle2D.Double(0, 0, 200, height); chart.draw(g2d, r2d); g2d.dispose(); Image image = Image.getInstance(tp); // put image in the document myElements.add(image); if (answersAndMean != null) { Paragraph header = new Paragraph(answersAndMean, paragraphFont); header.setSpacingAfter(SPACING_BETWEEN_LIST_ITEMS); myElements.add(header); } this.addElementArrayWithJump(myElements); } catch (BadElementException e) { // TODO Auto-generated catch block LOG.warn(e); } }
From source file:org.sakaiproject.tool.assessment.pdf.itext.HTMLWorker.java
License:Mozilla Public License
public void startElement(String tag, HashMap h) { if (!tagsSupported.containsKey(tag)) return;// w w w . jav a2 s . c om try { style.applyStyle(tag, h); String follow = (String) FactoryProperties.followTags.get(tag); if (follow != null) { HashMap prop = new HashMap(); prop.put(follow, null); cprops.addToChain(follow, prop); return; } FactoryProperties.insertStyle(h); if (tag.equals("a")) { cprops.addToChain(tag, h); if (currentParagraph == null) currentParagraph = new Paragraph(); stack.push(currentParagraph); currentParagraph = new Paragraph(); return; } if (tag.equals("br")) { if (currentParagraph == null) currentParagraph = new Paragraph(); currentParagraph.add(factoryProperties.createChunk("\n", cprops)); return; } if (tag.equals("hr")) { PdfPTable hr = new PdfPTable(1); hr.setHorizontalAlignment(Element.ALIGN_CENTER); hr.setWidthPercentage(100f); hr.setSpacingAfter(0f); hr.setSpacingBefore(0f); PdfPCell cell = new PdfPCell(); cell.setUseVariableBorders(true); cell.setVerticalAlignment(Element.ALIGN_MIDDLE); cell.setHorizontalAlignment(Element.ALIGN_CENTER); cell.setBorder(PdfPCell.BOTTOM); cell.setBorderWidth(1f); cell.setPadding(0); cell.addElement(factoryProperties.createChunk("\n", cprops)); hr.addCell(cell); // paragraphs can't have tables? really? without it hr's may be rendered a bit early.. //if (currentParagraph != null) // currentParagraph.add(hr); //else document.add(hr); return; } if (tag.equals("font") || tag.equals("span")) { cprops.addToChain(tag, h); return; } if (tag.equals("img")) { String src = (String) h.get("src"); if (src == null) return; cprops.addToChain(tag, h); Image img = null; if (interfaceProps != null) { HashMap images = (HashMap) interfaceProps.get("img_static"); if (images != null) { Image tim = (Image) images.get(src); if (tim != null) img = Image.getInstance(tim); } else { if (!src.startsWith("http")) { // relative src references only String baseurl = (String) interfaceProps.get("img_baseurl"); if (baseurl != null) { src = baseurl + src; img = Image.getInstance(src); } } } } if (img == null) { if (!src.startsWith("http")) { String path = cprops.getProperty("image_path"); if (path == null) path = ""; src = new File(path, src).getPath(); img = Image.getInstance(src); } else { byte[] buffer; String srcResource = src.substring(src.indexOf("/content", 0)).replaceAll("/content", ""); buffer = getImageStream(URLDecoder.decode(srcResource)); img = Image.getInstance(buffer); } } String align = (String) h.get("align"); String width = (String) h.get("width"); String height = (String) h.get("height"); String border = (String) h.get("border"); String hspace = (String) h.get("hspace"); String vspace = (String) h.get("vspace"); String before = cprops.getProperty("before"); String after = cprops.getProperty("after"); float wp = 0.0f; float lp = 0.0f; if (maxWidth > 0 && ((width != null && Integer.parseInt(width) > maxWidth) || (width == null && (int) img.getWidth() > maxWidth))) { wp = lengthParse(String.valueOf(maxWidth), (int) img.getWidth()); lp = wp; } else { wp = lengthParse(width, (int) img.getWidth()); lp = lengthParse(height, (int) img.getHeight()); } if (wp > 0 && lp > 0) img.scalePercent(wp, lp); else if (wp > 0) img.scalePercent(wp); else if (lp > 0) img.scalePercent(lp); img.setWidthPercentage(0); // border if (border != null && !"".equals(border)) { try { img.setBorderWidth(Integer.parseInt(border)); img.setBorder(Image.BOX); } catch (Exception e) { e.printStackTrace(); } } // horizonatal space if (hspace != null && !"".equals(hspace)) { try { img.setSpacingAfter(Float.parseFloat(hspace)); img.setSpacingBefore(Float.parseFloat(hspace)); } catch (Exception e) { e.printStackTrace(); } } // horizontal alignment if (align != null && (align.equalsIgnoreCase("left") || align.equalsIgnoreCase("right"))) { endElement("p"); int ralign = Image.LEFT; if (align.equalsIgnoreCase("right")) ralign = Image.RIGHT; img.setAlignment(ralign | Image.TEXTWRAP); Img i = null; boolean skip = false; if (interfaceProps != null) { i = (Img) interfaceProps.get("img_interface"); if (i != null) skip = i.process(img, h, cprops, document); } if (!skip) document.add(img); cprops.removeChain(tag); } // vertical alignment (or none) else { img.setAlignment(Image.TEXTWRAP); float bottom = 0.0f; float top = img.getTop(); float prevHeight = 0.0f; float prevRise = 0.0f; if (currentParagraph != null) { ArrayList chunks = currentParagraph.getChunks(); Chunk sibling = null; for (int k = chunks.size() - 1; k >= 0; k--) { if (chunks.get(k) != null) sibling = (Chunk) chunks.get(k); } if (sibling != null) { if (sibling.hasAttributes()) prevRise = sibling.getTextRise(); prevHeight = 0.0f; if (sibling.getFont() != null) { prevHeight = sibling.getFont().getCalculatedSize(); } } } if ("absMiddle".equalsIgnoreCase(align)) { if (prevHeight > 0) bottom += (img.getScaledHeight() / 2.0f) - (prevHeight / 2.0f); else if (img.getScaledHeight() > 0) bottom += img.getScaledHeight() / 2.0f; } else if ("middle".equalsIgnoreCase(align)) { if (img.getScaledHeight() > 0) bottom += (img.getScaledHeight() / 2.0f); } else if ("bottom".equalsIgnoreCase(align) || "baseline".equalsIgnoreCase(align) || "absbottom".equalsIgnoreCase(align)) { //baseline and absbottom should have some slight tweeking from bottom, but not sure what?? } else if ("top".equalsIgnoreCase(align)) { bottom += img.getScaledHeight() - prevHeight; } else if ("texttop".equalsIgnoreCase(align)) { bottom += img.getScaledHeight() - (prevHeight - prevRise); } cprops.removeChain(tag); if (currentParagraph == null) { currentParagraph = FactoryProperties.createParagraph(cprops); bottom = 0f; } else if (currentParagraph.isEmpty()) { bottom = 0f; } currentParagraph.setLeading(2f + bottom, 1.00f); currentParagraph.add(new Chunk(img, 0, 0 - bottom)); } return; } if (tag.equals("blockquote")) { cprops.addToChain(tag, h); inBLOCK = true; if (currentParagraph != null) endElement("p"); currentParagraph = FactoryProperties.createParagraph(cprops); currentParagraph.add(factoryProperties.createChunk("\n", cprops)); return; } endElement("p"); if (tag.equals("h1") || tag.equals("h2") || tag.equals("h3") || tag.equals("h4") || tag.equals("h5") || tag.equals("h6")) { if (!h.containsKey("size")) { int v = 8 - Integer.parseInt(tag.substring(1)); h.put("size", Integer.toString(v)); } cprops.addToChain(tag, h); return; } if (tag.equals("ul")) { if (pendingLI) endElement("li"); skipText = true; cprops.addToChain(tag, h); com.lowagie.text.List list = new com.lowagie.text.List(false, 10); list.setListSymbol("\u2022"); stack.push(list); return; } if (tag.equals("ol")) { if (pendingLI) endElement("li"); skipText = true; cprops.addToChain(tag, h); com.lowagie.text.List list = new com.lowagie.text.List(true, 10); stack.push(list); return; } if (tag.equals("li")) { if (pendingLI) endElement("li"); skipText = false; pendingLI = true; cprops.addToChain(tag, h); stack.push(FactoryProperties.createListItem(cprops)); return; } if (tag.equals("div") || tag.equals("body")) { cprops.addToChain(tag, h); return; } if (tag.equals("pre")) { if (!h.containsKey("face")) { h.put("face", "Courier"); } cprops.addToChain(tag, h); isPRE = true; return; } if (tag.equals("p")) { cprops.addToChain(tag, h); currentParagraph = FactoryProperties.createParagraph(cprops); if (inBLOCK) { currentParagraph.setIndentationLeft(currentParagraph.getIndentationLeft() + 40.0F); } return; } if (tag.equals("tr")) { if (pendingTR) endElement("tr"); skipText = true; pendingTR = true; cprops.addToChain("tr", h); return; } if (tag.equals("td") || tag.equals("th")) { if (pendingTD) endElement(tag); skipText = false; pendingTD = true; cprops.addToChain("td", h); stack.push(new IncCell(tag, cprops)); return; } if (tag.equals("table")) { cprops.addToChain("table", h); IncTable table = new IncTable(h); stack.push(table); tableState.push(new boolean[] { pendingTR, pendingTD }); pendingTR = pendingTD = false; skipText = true; return; } } catch (Exception e) { e.printStackTrace(); //throw new ExceptionConverter(e); } }
From source file:org.sigmah.server.report.renderer.itext.ItextChartRenderer.java
License:Open Source License
public void render(DocWriter writer, Document doc, PivotChartElement element) { try {//from w w w . j a v a 2 s . c o m doc.add(ThemeHelper.elementTitle(element.getTitle())); ItextRendererHelper.addFilterDescription(doc, element.getContent().getFilterDescriptions()); float width = doc.getPageSize().getWidth() - doc.rightMargin() - doc.leftMargin(); float height = (doc.getPageSize().getHeight() - doc.topMargin() - doc.bottomMargin()) / 3f; if (writer instanceof PdfWriter) { // We can render the chart directly as vector graphics // in the PDF file PdfWriter pdfWriter = (PdfWriter) writer; PdfContentByte cb = pdfWriter.getDirectContent(); Graphics2D g2d = cb.createGraphics(width, height); chartRenderer.render(element, false, g2d, (int) width, (int) height, 72); g2d.dispose(); } else { // For RTF/Html we embed as a GIF width = width / 72f * RESOLUTION; height = height / 72f * RESOLUTION; BufferedImage chartImage = chartRenderer.renderImage(element, false, (int) width, (int) height, RESOLUTION); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(chartImage, "GIF", baos); Image image = Image.getInstance(baos.toByteArray()); image.scalePercent(72f / RESOLUTION * 100f); doc.add(image); } } catch (Exception e) { e.printStackTrace(); } }
From source file:org.sigmah.server.report.renderer.itext.ItextMapRenderer.java
License:Open Source License
public void renderMap(DocWriter writer, MapElement element, Document doc) { try {/*w w w. j av a 2 s .c o m*/ ByteArrayOutputStream baos = new ByteArrayOutputStream(); this.render(element, baos); Image image = Image.getInstance(baos.toByteArray()); image.scalePercent(72f / 92f * 100f); doc.add(image); } catch (Exception e) { throw new RuntimeException(e); } }
From source file:org.signserver.module.pdfsigner.PDFSignerParameters.java
License:Open Source License
private void extractAndProcessConfigurationProperties() throws IllegalRequestException, SignServerException { // The reason shown in the PDF signature if (config.getProperties().getProperty(PDFSigner.REASON) != null) { reason = config.getProperties().getProperty(PDFSigner.REASON); }//from w ww . j a v a 2 s . c o m LOG.debug("Using reason: " + reason); // The location shown in the PDF signature if (config.getProperties().getProperty(PDFSigner.LOCATION) != null) { location = config.getProperties().getProperty(PDFSigner.LOCATION); } LOG.debug("Using location: " + location); // are we adding visible or invisible signature // note : ParseBoolean returns false for everything but "True" if (config.getProperties().getProperty(PDFSigner.ADD_VISIBLE_SIGNATURE) != null) { add_visible_signature = Boolean .parseBoolean(config.getProperties().getProperty(PDFSigner.ADD_VISIBLE_SIGNATURE).trim()); } LOG.debug("Using visible signature: " + add_visible_signature); // timestamp url if (config.getProperties().getProperty(PDFSigner.TSA_URL) != null) { tsa_url = config.getProperties().getProperty(PDFSigner.TSA_URL); use_timestamp = true; LOG.debug("Using tsa url : " + tsa_url); } else if (config.getProperties().getProperty(PDFSigner.TSA_WORKER) != null) { tsa_worker = config.getProperties().getProperty(PDFSigner.TSA_WORKER); use_timestamp = true; } if (use_timestamp && config.getProperties().getProperty(PDFSigner.TSA_USERNAME) != null && config.getProperties().getProperty(PDFSigner.TSA_PASSWORD) != null) { tsa_username = config.getProperties().getProperty(PDFSigner.TSA_USERNAME); tsa_password = config.getProperties().getProperty(PDFSigner.TSA_PASSWORD); use_timestamp_authorization = true; } // should we embed crl inside the cms package if (config.getProperties().getProperty(PDFSigner.EMBED_CRL) != null) { embed_crl = Boolean.parseBoolean(config.getProperties().getProperty(PDFSigner.EMBED_CRL).trim()); } LOG.debug("Using embed crl inside cms package : " + isEmbed_crl()); // should we embed ocsp response inside the cms package if (config.getProperties().getProperty(PDFSigner.EMBED_OCSP_RESPONSE) != null) { embed_ocsp_response = Boolean .parseBoolean(config.getProperties().getProperty(PDFSigner.EMBED_OCSP_RESPONSE).trim()); } LOG.debug("Using embed ocsp inside cms package : " + isEmbed_ocsp_response()); // should we refuse PDF documents that contains multiple // indirect objects with the same name if (config.getProperties().getProperty(PDFSigner.REFUSE_DOUBLE_INDIRECT_OBJECTS) != null) { refuseDoubleIndirectObjects = Boolean .parseBoolean(config.getProperties().getProperty(PDFSigner.REFUSE_DOUBLE_INDIRECT_OBJECTS)); } // Reject permissions String rejectPermissionsValue = config.getProperties().getProperty(PDFSigner.REJECT_PERMISSIONS); if (rejectPermissionsValue != null) { String[] array = rejectPermissionsValue.split(","); rejectPermissions.addAll(Arrays.asList(array)); } // Set permissions String setPermissionsValue = config.getProperties().getProperty(PDFSigner.SET_PERMISSIONS); if (setPermissionsValue != null) { String[] array = setPermissionsValue.split(","); try { setPermissions = Permissions.fromSet(Arrays.asList(array), true); } catch (UnknownPermissionException ex) { throw new SignServerException("Signer " + workerId + " missconfigured: " + ex.getMessage()); } } // Remove permissions String removePermissionsValue = config.getProperties().getProperty(PDFSigner.REMOVE_PERMISSIONS); if (removePermissionsValue != null) { String[] array = removePermissionsValue.split(","); removePermissions = new HashSet<String>(); removePermissions.addAll(Arrays.asList(array)); } // Set ownerpassword setOwnerPassword = config.getProperties().getProperty(PDFSigner.SET_OWNERPASSWORD); // if signature is chosen to be visible proceed with setting visibility // properties if (add_visible_signature) { // page to draw visible signature at if (config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_PAGE) != null) { visible_sig_page = config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_PAGE); } LOG.debug("Using visible signature page: " + visible_sig_page); // The location of the visible signature rectangle(llx, lly, urx, // ury) // llx = lower left x coordinate, lly = lower left y coordinate, urx // = upper right x coordinate, ury = upper right y coordinate if (config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_RECTANGLE) != null) { visible_sig_rectangle = config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_RECTANGLE); } LOG.debug("Using rectangle: " + visible_sig_rectangle); String[] rect = visible_sig_rectangle.split(","); if (rect.length < 4) { throw new IllegalRequestException( "RECTANGLE property must contain 4 comma separated values with no spaces."); } visible_sig_rectangle_llx = Integer.valueOf(rect[0]); visible_sig_rectangle_lly = Integer.valueOf(rect[1]); visible_sig_rectangle_urx = Integer.valueOf(rect[2]); visible_sig_rectangle_ury = Integer.valueOf(rect[3]); // custom image to use with signature // base64 encoded byte[] if (config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_BASE64) != null) { visible_sig_custom_image_base64 = config.getProperties() .getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_BASE64); LOG.debug("base64 encoded custom image is set"); } // custom image path. Do not set if base64 encoded image is // specified if (visible_sig_custom_image_base64 == null || visible_sig_custom_image_base64.isEmpty()) { if (config.getProperties().getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_PATH) != null) { visible_sig_custom_image_path = config.getProperties() .getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_PATH); LOG.debug("using custom image path : " + visible_sig_custom_image_path); } } boolean use_image_from_base64_string = visible_sig_custom_image_base64 != null && !visible_sig_custom_image_base64.isEmpty(); boolean use_image_from_path = visible_sig_custom_image_path != null && !visible_sig_custom_image_path.isEmpty(); use_custom_image = use_image_from_base64_string || use_image_from_path; // custom image resizing (if we are using custom image) if (use_custom_image) { // retrieve custom image byte[] imageByteArray; if (use_image_from_base64_string) { imageByteArray = Base64.decode(visible_sig_custom_image_base64.getBytes()); } else { try { imageByteArray = readFile(visible_sig_custom_image_path); } catch (IOException e) { throw new SignServerException("Error reading custom image data from path specified", e); } } try { custom_image = Image.getInstance(imageByteArray); } catch (BadElementException e) { throw new SignServerException("Problem constructing image from custom image data", e); } catch (MalformedURLException e) { throw new SignServerException("Problem constructing image from custom image data", e); } catch (IOException e) { throw new SignServerException("Problem constructing image from custom image data", e); } if (config.getProperties() .getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_SCALE_TO_RECTANGLE) != null) { visible_sig_custom_image_scale_to_rectangle = Boolean.parseBoolean(config.getProperties() .getProperty(PDFSigner.VISIBLE_SIGNATURE_CUSTOM_IMAGE_SCALE_TO_RECTANGLE).trim()); LOG.debug("resize custom image to rectangle : " + visible_sig_custom_image_scale_to_rectangle); } // if we are using custom image and the // VISIBLE_SIGNATURE_CUSTOM_IMAGE_SCALE_TO_RECTANGLE is set to // true resize image to fit to rectangle specified // If set to false calculate urx and ury coordinates from image if (visible_sig_custom_image_scale_to_rectangle) { resizeImageToFitToRectangle(); } else { calculateUpperRightRectangleCoordinatesFromImage(); } } } // Certification level final String level = config.getProperty(PDFSigner.CERTIFICATION_LEVEL); if (level != null) { if (level.equalsIgnoreCase("NO_CHANGES_ALLOWED")) { certification_level = PdfSignatureAppearance.CERTIFIED_NO_CHANGES_ALLOWED; } else if (level.equalsIgnoreCase("FORM_FILLING_AND_ANNOTATIONS")) { certification_level = PdfSignatureAppearance.CERTIFIED_FORM_FILLING_AND_ANNOTATIONS; } else if (level.equalsIgnoreCase("FORM_FILLING")) { certification_level = PdfSignatureAppearance.CERTIFIED_FORM_FILLING; } else if (level.equalsIgnoreCase("NOT_CERTIFIED")) { certification_level = PdfSignatureAppearance.NOT_CERTIFIED; } else { throw new SignServerException("Unknown value for CERTIFICATION_LEVEL"); } } if (LOG.isDebugEnabled()) { LOG.debug("using certification level: " + certification_level); } }
From source file:org.silverpeas.core.util.PdfUtil.java
License:Open Source License
/** * Add a image under or over content on each page of a PDF file. * @param pdfSource the source pdf file, this content is not modified by this method * @param imageToAdd the image file// ww w .j a v a2 s . co 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/*from ww w . j av a 2 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.sonar.report.pdf.builder.ComplexityDistributionBuilder.java
License:Open Source License
public Image getGraphic(final ComplexityDistribution complexityDistribution) { Image image = null;// ww w . j a va 2 s . c om try { if (complexityDistribution.getyValues().length != 0) { image = Image.getInstance(sonarBaseUrl + "/chart?cht=cvb&chdi=300x200&chca=" + complexityDistribution.formatXValues() + "&chov=y&chrav=y&chv=" + complexityDistribution.formatYValues() + "&chorgv=y&chcaaml=0.05&chseamu=0.2&chins=5&chcaamu=0.05&chcav=y&chc=777777,777777,777777,777777,777777,777777,777777"); image.setAlignment(Image.ALIGN_MIDDLE); } } catch (BadElementException e) { LOG.error("Can not generate complexity distribution image", e); } catch (MalformedURLException e) { LOG.error("Can not generate complexity distribution image", e); } catch (IOException e) { LOG.error("Can not generate complexity distribution image", e); } return image; }
From source file:org.sonar.report.pdf.builder.RadarGraphicBuilder.java
License:Open Source License
public Image getGraphic(final RadarGraphic radarGraphic) { Image image = null;//from www.ja va 2 s. c o m try { String requestUrl = sonarBaseUrl + "/chart?ck=xradar&w=210&h=110&c=777777|F8A036&m=100&g=0.25&" + "l=Eff.(" + radarGraphic.getEfficiency() + "%25),Mai.(" + radarGraphic.getMaintainability() + "%25),Por.(" + radarGraphic.getPortability() + "%25),Rel.(" + radarGraphic.getReliavility() + "%25),Usa.(" + radarGraphic.getUsability() + "%25)&" + "v=" + radarGraphic.getEfficiency() + "," + radarGraphic.getMaintainability() + "," + radarGraphic.getPortability() + "," + radarGraphic.getReliavility() + "," + radarGraphic.getUsability(); LOG.debug("Getting radar graphic: " + requestUrl); image = Image.getInstance(requestUrl); image.setAlignment(Image.ALIGN_MIDDLE); } catch (BadElementException e) { LOG.error("Can not generate radar graphic", e); } catch (MalformedURLException e) { LOG.error("Can not generate radar graphic", e); } catch (IOException e) { LOG.error("Can not generate radar graphic", e); } return image; }
From source file:org.sonar.report.pdf.DefaultPDFReporter.java
License:Open Source License
@Override protected void printFrontPage(Document frontPageDocument, PdfWriter frontPageWriter) throws org.dom4j.DocumentException, ReportException { try {/*from w w w . j a v a 2s . c om*/ URL largeLogo; if (super.getConfigProperty("front.page.logo").startsWith("http://")) { largeLogo = new URL(super.getConfigProperty("front.page.logo")); } else { largeLogo = this.getClass().getClassLoader() .getResource(super.getConfigProperty("front.page.logo")); } Image logoImage = Image.getInstance(largeLogo); Rectangle pageSize = frontPageDocument.getPageSize(); float positionX = pageSize.getWidth() / 2f - logoImage.getWidth() / 2f; logoImage.setAbsolutePosition(positionX, pageSize.getHeight() - logoImage.getHeight() - 100); frontPageDocument.add(logoImage); PdfPTable title = new PdfPTable(1); title.getDefaultCell().setHorizontalAlignment(PdfPCell.ALIGN_CENTER); title.getDefaultCell().setBorder(Rectangle.NO_BORDER); String projectRow = super.getTextProperty("general.project") + ": " + super.getProject().getName(); SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd"); String dateRow = df.format(super.getProject().getMeasures().getDate()); String descriptionRow = super.getProject().getDescription(); title.addCell(new Phrase(projectRow, Style.FRONTPAGE_FONT_1)); title.addCell(new Phrase(descriptionRow, Style.FRONTPAGE_FONT_2)); title.addCell(new Phrase(dateRow, Style.FRONTPAGE_FONT_3)); title.setTotalWidth( pageSize.getWidth() - frontPageDocument.leftMargin() - frontPageDocument.rightMargin()); title.writeSelectedRows(0, -1, frontPageDocument.leftMargin(), pageSize.getHeight() - logoImage.getHeight() - 150, frontPageWriter.getDirectContent()); } catch (IOException e) { e.printStackTrace(); } catch (BadElementException e) { e.printStackTrace(); } catch (DocumentException e) { e.printStackTrace(); } }