List of usage examples for com.itextpdf.text Image scalePercent
public void scalePercent(final float percent)
From source file:org.durel.mydooble.ImageItem.java
License:Open Source License
@Override public void toPDF(PDF out, int i) { super.toPDF(out, i); try {//w ww . j a va2 s . c o m Image img = Image.getInstance(image); img.setDpi(288, 288); img.setInterpolation(true); float ih = (float) (img.getHeight()); float iw = (float) (img.getWidth()); if (ih > h || iw > w) { float xratio = iw / w; float yratio = ih / h; float ratio = Math.max(xratio, yratio); log.info("ih: " + ih + " - iw: " + iw + " - xratio: " + xratio + " - yratio: " + yratio + " - ratio: " + ratio + " --> " + (int) (iw / ratio) + "x" + (int) (ih / ratio)); img.scalePercent(100 / ratio); } PdfContentByte cb = out.writer.getDirectContent(); float x = bx + (c * (w + m)) + m; float y = by + (r * (h + m)) + m; img.setAbsolutePosition(x, y); cb.addImage(img); } catch (DocumentException e) { e.printStackTrace(); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } }
From source file:org.opentox.io.publishable.PDFObject.java
License:Open Source License
public void publish(YaqpIOStream stream) throws YaqpException { if (stream == null) { throw new NullPointerException("Cannot public pdf to a null output stream"); }// w ww . ja va2 s.co m try { Document doc = new Document(); try { PdfWriter.getInstance(doc, (OutputStream) stream.getStream()); } catch (ClassCastException ex) { throw new ClassCastException("The stream you provided is not a valid output stream"); } doc.open(); doc.addAuthor(pdfAuthor); doc.addCreationDate(); doc.addProducer(); doc.addSubject(subject); doc.addCreator(pdfCreator); doc.addTitle(pdfTitle); doc.addKeywords(pdfKeywords); doc.addHeader("License", "GNU GPL v3"); Image image = null; try { image = Image.getInstance(new URL(OpenToxLogoUrl)); } catch (Exception ex) {// OpenTox Logo was not found on the web... try {// use the cached image instead YaqpLogger.LOG.log(new Trace(getClass(), "OpenTox Logo not found at " + OpenToxLogoUrl)); image = Image.getInstance(alternativeLogoPath); } catch (Exception ex1) {// if no image at local folder YaqpLogger.LOG.log(new Debug(getClass(), "OpenTox Logo not found at " + alternativeLogoPath + " :: " + ex1)); } } if (image != null) { image.scalePercent(40); image.setAnnotation(new Annotation(0, 0, 0, 0, "http://opentox.org")); Chunk ck_ot = new Chunk(image, -5, -30); doc.add(ck_ot); } try { Image yaqp = Image.getInstance(yaqpLogo); yaqp.scalePercent(30); yaqp.setAnnotation(new Annotation(0, 0, 0, 0, "https://opentox.ntua.gr")); yaqp.setAlt("YAQP(R), yet another QSAR Project"); Chunk ck_yaqp = new Chunk(yaqp, 15, -30); doc.add(ck_yaqp); } catch (Exception ex) { YaqpLogger.LOG .log(new Warning(getClass(), "YAQP Logo not found at " + kinkyDesignLogo + " :: " + ex)); } doc.add(new Paragraph("\n\n\n")); for (Element e : elements) { doc.add(e); } doc.close(); } catch (DocumentException ex) { String message = "Error while generating PDF representation."; YaqpLogger.LOG.log(new Warning(getClass(), message)); throw new YaqpException(XPDF18, message, ex); } }
From source file:org.sharegov.cirm.utils.PDFViewReport.java
License:Apache License
private void addWASDHeader(Chapter chapter) throws DocumentException { try {/*w ww . j a v a2 s.co m*/ String img = StartUp.config.at("workingDir").asString() + "/src/html/images/md-logo.png"; Image logo = Image.getInstance(img); logo.scalePercent(67); PdfPTable table = new PdfPTable(2); table.setWidthPercentage(100); int[] widths = { 50, 50 }; table.setWidths(widths); //table.addCell(logo); //This exactly fits the image to the size of the cell. PdfPCell cell = new PdfPCell(logo); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); String str1 = "Miami-Dade Water and Sewer Department"; String str2 = "P.O.Box 33016 . 3071 SW 38 Ave"; String str3 = "Miami, Florida 33146"; String str4 = "T: 786-552-8974"; String str5 = "www.miamidade.gov"; PdfPTable wasdTable = new PdfPTable(1); addCell(wasdTable, str1, Element.ALIGN_RIGHT, boldFont, null); addCell(wasdTable, str2, Element.ALIGN_RIGHT, normalFont, null); addCell(wasdTable, str3, Element.ALIGN_RIGHT, normalFont, null); addCell(wasdTable, str4, Element.ALIGN_RIGHT, normalFont, null); addCell(wasdTable, str5, Element.ALIGN_RIGHT, boldFont, null); cell = new PdfPCell(wasdTable); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); addSection(chapter).add(table); } catch (Exception e) { e.printStackTrace(); throw new RuntimeException(e.getMessage()); } }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
private void fillTemplate(GlobalVariables gv, AcroFields pdfForm, ArrayList<Result> record, String basePath, String formName, int repeatIndex, String serverRoot, PdfStamper stamper, int oId) throws IOException, DocumentException { try {//from w w w. j a v a 2 s .co m for (Result r : record) { String value = ""; boolean hideLabel = false; String fieldName = getFieldName(formName, repeatIndex, r.name); String fieldNameQR = getFieldName(formName, repeatIndex, r.name + "_qr"); DisplayItem di = new DisplayItem(); try { Form form = survey.forms.get(r.fIdx); Question question = getQuestionFromResult(sd, r, form); setQuestionFormats(question.appearance, di); } catch (Exception e) { // If we can't get the question details for this data then that is ok } /* * Set the value based on the result * Process subforms if this is a repeating group */ if (r.type.equals("form")) { for (int k = 0; k < r.subForm.size(); k++) { fillTemplate(gv, pdfForm, r.subForm.get(k), basePath, fieldName, k, serverRoot, stamper, oId); } } else if (r.type.equals("select1")) { Form form = survey.forms.get(r.fIdx); Question question = form.questions.get(r.qIdx); ArrayList<String> matches = new ArrayList<String>(); matches.add(r.value); value = choiceManager.getLabel(sd, cResults, user, oId, survey.id, question.id, question.l_id, question.external_choices, question.external_table, survey.languages.get(languageIdx).name, languageIdx, matches, survey.ident); } else if (r.type.equals("select")) { String nameValue = r.value; if (nameValue != null) { String vArray[] = nameValue.split(" "); ArrayList<String> matches = new ArrayList<String>(); if (vArray != null) { for (String v : vArray) { matches.add(v); } } Form form = survey.forms.get(r.fIdx); Question question = form.questions.get(r.qIdx); value = choiceManager.getLabel(sd, cResults, user, oId, survey.id, question.id, question.l_id, question.external_choices, question.external_table, survey.languages.get(languageIdx).name, languageIdx, matches, survey.ident); } } else if (r.type.equals("dateTime") || r.type.equals("timestamp")) { value = null; if (r.value != null) { // Convert date to local time DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = df.parse(r.value); df.setTimeZone(TimeZone.getTimeZone(tz)); value = df.format(date); log.info("Convert date to local time (template): " + r.name + " : " + r.value + " : " + " : " + value + " : " + r.type + " : " + tz); } } else { value = r.value; } /* * Add the value to the form * Alternatively remove the fieldName if the value is empty. */ if (value == null || value.trim().equals("")) { try { pdfForm.removeField(fieldName); } catch (Exception e) { log.info("Error removing field: " + fieldName + ": " + e.getMessage()); } } else if (r.type.equals("geopoint") || r.type.equals("geoshape") || r.type.equals("geotrace") || r.type.startsWith("geopolygon_") || r.type.startsWith("geolinestring_")) { PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName); if (ad != null) { Image img = PdfUtilities.getMapImage(sd, di.map, r.value, di.location, di.zoom, gv.mapbox_key, survey.id, user, di.markerColor); PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldName, img); } else { log.info("No field for image (Mapbox not called: " + fieldName); } } else if (r.type.equals("image") || r.type.equals("video") || r.type.equals("audio")) { PdfUtilities.addImageTemplate(pdfForm, fieldName, basePath, value, serverRoot, stamper, defaultFontLink); } else { if (hideLabel) { try { pdfForm.removeField(fieldName); } catch (Exception e) { log.info("Error removing field: " + fieldName + ": " + e.getMessage()); } } else { if (di.isBarcode) { PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName); if (ad != null) { BarcodeQRCode qrcode = new BarcodeQRCode(value.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldName, qrcodeImage); } } else { pdfForm.setField(fieldName, value); } } } /* * Add any QR code values to fields that have been identified using the QR suffix */ if (fieldNameQR != null && value != null && value.trim().length() > 0) { PushbuttonField ad = pdfForm.getNewPushbuttonFromField(fieldName); if (ad != null) { BarcodeQRCode qrcode = new BarcodeQRCode(value.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); PdfUtilities.addMapImageTemplate(pdfForm, ad, fieldNameQR, qrcodeImage); } } } } catch (Exception e) { log.log(Level.SEVERE, "Error filling template", e); } }
From source file:org.smap.sdal.managers.PDFSurveyManager.java
License:Open Source License
private void updateValueCell(Parser parser, String remoteUser, PdfPCell valueCell, DisplayItem di, boolean generateBlank, String basePath, String serverRoot, GlobalVariables gv, int oId) throws Exception { // Questions that append their values to this question ArrayList<String> deps = gv.addToList.get(di.fIdx + "_" + di.rec_number + "_" + di.name); if (di.type.startsWith("select")) { processSelect(parser, remoteUser, valueCell, di, generateBlank, gv, oId); } else if (di.type.equals("image")) { if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) { if (di.isHyperlink) { Anchor anchor = new Anchor(serverRoot + di.value); anchor.setReference(serverRoot + di.value); valueCell.addElement(getPara("", di, gv, deps, anchor)); } else { try { Image img = Image.getInstance(basePath + "/" + di.value); valueCell.addElement(img); } catch (Exception e) { log.info("Error: image " + basePath + "/" + di.value + " not added: " + e.getMessage()); log.log(Level.SEVERE, "Adding image to pdf", e); }// ww w .ja va2s . c om } } else { // TODO add empty image } } else if (di.type.equals("video") || di.type.equals("audio")) { if (di.value != null && !di.value.trim().equals("") && !di.value.trim().equals("Unknown")) { Anchor anchor = new Anchor(serverRoot + di.value); anchor.setReference(serverRoot + di.value); valueCell.addElement(getPara("", di, gv, deps, anchor)); } else { // TODO add empty image } } else if (di.type.equals("geopoint") || di.type.equals("geoshape") || di.type.equals("geotrace") || di.type.startsWith("geopolygon_") || di.type.startsWith("geolinestring_")) { Image img = PdfUtilities.getMapImage(sd, di.map, di.value, di.location, di.zoom, gv.mapbox_key, survey.id, user, di.markerColor); if (img != null) { valueCell.addElement(img); } else { valueCell.addElement(getPara(" ", di, gv, deps, null)); } } else if (di.isBarcode) { BarcodeQRCode qrcode = new BarcodeQRCode(di.value.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); valueCell.addElement((qrcodeImage)); } else { // Todo process other question types String value = null; if (di.value == null || di.value.trim().length() == 0) { value = " "; // Need a space to show a blank row } else { if (di.value != null && di.value.length() > 0) { if (GeneralUtilityMethods.isRtlLanguage(di.value)) { valueCell.setRunDirection(PdfWriter.RUN_DIRECTION_RTL); } } if (di.type.equals("dateTime") || di.type.equals("timestamp")) { // Set date time to local time DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); df.setTimeZone(TimeZone.getTimeZone("UTC")); Date date = df.parse(di.value); df.setTimeZone(TimeZone.getTimeZone(tz)); value = df.format(date); log.info("Convert date to local time: " + di.name + " : " + di.value + " : " + " : " + value + " : " + di.type + " : " + tz); } else { value = di.value; } } valueCell.addElement(getPara(value, di, gv, deps, null)); } }
From source file:org.smap.sdal.managers.PDFTableManager.java
License:Open Source License
private PdfPCell addDisplayItem(Parser parser, KeyValue kv, String basePath, boolean barcode, String type) throws BadElementException, MalformedURLException, IOException { PdfPCell valueCell = new PdfPCell(); valueCell.setBorderColor(BaseColor.LIGHT_GRAY); // Set the content of the value cell try {//from ww w .ja v a 2s .c om if (type != null && type.equals("image")) { Image img = Image.getInstance(kv.v); valueCell.addElement(img); } else if (barcode && kv.v.trim().length() > 0) { BarcodeQRCode qrcode = new BarcodeQRCode(kv.v.trim(), 1, 1, null); Image qrcodeImage = qrcode.getImage(); qrcodeImage.setAbsolutePosition(10, 500); qrcodeImage.scalePercent(200); valueCell.addElement((qrcodeImage)); } else { valueCell.addElement(getPara(kv.v)); } } catch (Exception e) { log.info("Error updating value cell, continuing: " + basePath + " : " + kv.v); log.log(Level.SEVERE, "Exception", e); } return valueCell; }
From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java
License:Apache License
public boolean exportAlert(java.util.List<java.util.List<Alert>> alerts, String fileName, ExtensionAlertReportExport extensionExport) { Document document = new Document(PageSize.A4); try {//from w w w . j ava 2s . c o m // Document documentAdd = null; PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(fileName)); document.open(); boolean attach = false; // add attach document is exist if (!extensionExport.getParams().getDocumentAttach().isEmpty()) { PdfReader reader = new PdfReader(extensionExport.getParams().getDocumentAttach()); int n = reader.getNumberOfPages(); PdfImportedPage page; // Go through all pages for (int i = 1; i <= n; i++) { page = writer.getImportedPage(reader, i); Image instance = Image.getInstance(page); instance.scalePercent(95f); document.add(instance); } attach = true; } if (!attach) { addMetaData(document, extensionExport); addTitlePage(document, extensionExport); } for (int i = 0; i < alerts.size(); i++) { java.util.List<Alert> alertAux = alerts.get(i); addContent(document, alertAux, extensionExport); } document.close(); return true; } catch (Exception e) { logger.error(e.getMessage(), e); document.close(); return false; } }
From source file:org.zaproxy.zap.extension.alertReport.AlertReportExportPDF.java
License:Apache License
/** * Add image a Paragraph/*from w w w. ja v a 2 s . c om*/ * * @param paragraph * @param image * @param path * @throws BadElementException */ private static void addImage(Paragraph paragraph, String imagePath, float scalePercent) throws BadElementException { Image image1; try { if (!imagePath.isEmpty()) { image1 = Image.getInstance(imagePath); if (scalePercent != 0) image1.scalePercent(40f); image1.setAlignment(Image.ALIGN_CENTER); paragraph.add(image1); } } catch (IOException e) { logger.error(e.getMessage(), e); } }
From source file:Output.QuotePDf.java
private Image headerImage() throws BadElementException, IOException { Image image = Image.getInstance(getClass().getClassLoader().getResource("resources/header.jpg")); image.setAlignment(Element.ALIGN_CENTER); image.scalePercent(35f); return image; }
From source file:PDF.PDFTrackGenerator.java
License:Open Source License
/** * Metda generateTrackPDFA4 sli na samotn vygenerovanie PDF dokumentu trasy na formt A4. * @param lineWeight - hrbka ?iary trasy na mape * @param color - farba ?iary trasy na mape * @param width - rka mapy//from www.ja va 2 s .c o m * @param height - vka mapy * @param scale - klovacia kontanta mapy (n x rozlenie mapy) * @param startDate - dtum a ?as prvho bodu trasy * @param endDate - dtum a ?as poslednho bodu trasy * @param activity - aktivita trasy * @param user - pouvate (majite) trasy */ public void generateTrackPDFA4(int lineWeight, String color, int width, int height, int scale, String startDate, String endDate, String activity, String user) { try { Document doc = new Document(); PdfWriter.getInstance(doc, new FileOutputStream(path + fileName + ".pdf")); doc.open(); Font nadpisFont = new Font(Font.FontFamily.HELVETICA, 25, Font.BOLD); Font detailyFont = new Font(Font.FontFamily.HELVETICA, 9, Font.NORMAL); Paragraph nadpisPar = new Paragraph(); nadpisPar.setAlignment(Element.ALIGN_CENTER); Phrase nadpis = new Phrase(fileName, nadpisFont); nadpisPar.add(nadpis); nadpisPar.add(""); doc.add(nadpisPar); doc.add(Chunk.NEWLINE); PdfPTable tabulka = new PdfPTable(2); tabulka.setWidthPercentage(100); float[] columnWidth = { 6f, 4f }; tabulka.setWidths(columnWidth); StaticMapResolver res = new StaticMapResolver(loader); String mapUrl = res.getStaticMapTrackURLWithMultimedia(lineWeight, color, width, height, scale); Image img = Image.getInstance(new URL(mapUrl)); //img.scalePercent(50); PdfPCell riadokSObr = new PdfPCell(img, true); riadokSObr.setBorder(Rectangle.NO_BORDER); riadokSObr.setPaddingBottom(10f); PdfPCell riadokSText = new PdfPCell(new Phrase("Description: " + loader.getTrackDescription() + "\n\n\nTrack activity: " + activity.substring(4) + "\n\n\nStart place: " + loader.getStartAddress() + "\n\n\nEnd Place: " + loader.getEndAddress() + "\n\n\nTrack length: " + loader.getLength() + " km\n\n\nMin elevation: " + loader.getMinElevation() + " m\n\n\nMax elevation: " + loader.getMaxElevation() + " m\n\n\nHeight difference: " + loader.getHeightDiff() + " m\n\n\nStart: " + startDate + "\n\n\nEnd: " + endDate + "\n\n\nDuration: " + loader.getDuration(), detailyFont)); riadokSText.setBorder(Rectangle.NO_BORDER); riadokSText.setPaddingLeft(20f); riadokSText.setPaddingTop(5f); riadokSText.setPaddingBottom(10f); tabulka.addCell(riadokSObr); tabulka.addCell(riadokSText); doc.add(tabulka); //doc.add(new Phrase("\n", detailyFont)); PdfPTable obrTabulka = new PdfPTable(3); obrTabulka.setWidthPercentage(100); ArrayList<String> goodFiles = new ArrayList<String>(); for (int i = 0; i < loader.getMultimediaFiles().size(); i++) { if (!loader.getMultimediaFiles().get(i).getPath().startsWith("YTB")) { String extension = loader.getMultimediaFiles().get(i).getPath().substring( loader.getMultimediaFiles().get(i).getPath().lastIndexOf("."), loader.getMultimediaFiles().get(i).getPath().length()); String newPath = loader.getMultimediaFiles().get(i).getPath().substring(0, loader.getMultimediaFiles().get(i).getPath().lastIndexOf(".")) + "_THUMB" + extension; goodFiles.add(newPath); } } if (!goodFiles.isEmpty()) { int freeCount = 9; if (goodFiles.size() <= 9) { for (int i = 0; i < goodFiles.size(); i++) { Image tempImg = Image.getInstance(goodFiles.get(i)); tempImg.scalePercent(10f); PdfPCell tempCell = new PdfPCell(tempImg, true); tempCell.setPadding(3f); //tempCell.setPaddingTop(5f); tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE); tempCell.setHorizontalAlignment(Element.ALIGN_CENTER); tempCell.setFixedHeight(130f); tempCell.setBackgroundColor(BaseColor.BLACK); tempCell.setBorderColor(BaseColor.WHITE); tempCell.setBorderWidth(4f); //tempCell.setBorder(Rectangle.NO_BORDER); obrTabulka.addCell(tempCell); } for (int i = 0; i < 9 - goodFiles.size(); i++) { PdfPCell tempCell = new PdfPCell(); tempCell.setBorder(Rectangle.NO_BORDER); obrTabulka.addCell(tempCell); } } else if (goodFiles.size() <= 18) { for (int i = 0; i < 9; i++) { Image tempImg = Image.getInstance(goodFiles.get(i)); tempImg.scalePercent(10f); PdfPCell tempCell = new PdfPCell(tempImg, true); tempCell.setPadding(3f); //tempCell.setPaddingTop(5f); tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE); tempCell.setHorizontalAlignment(Element.ALIGN_CENTER); tempCell.setFixedHeight(130f); tempCell.setBackgroundColor(BaseColor.BLACK); tempCell.setBorderColor(BaseColor.WHITE); tempCell.setBorderWidth(4f); //tempCell.setBorder(Rectangle.NO_BORDER); obrTabulka.addCell(tempCell); } } else { for (int i = 0; i < (goodFiles.size() % 9); i++) { goodFiles.remove(goodFiles.size() - 1 - i); } int counting = (goodFiles.size() / 9); for (int i = 0; i < goodFiles.size(); i = i + counting) { Image tempImg = Image.getInstance(goodFiles.get(i)); tempImg.scalePercent(10f); PdfPCell tempCell = new PdfPCell(tempImg, true); tempCell.setPadding(3f); //tempCell.setPaddingTop(5f); tempCell.setVerticalAlignment(Element.ALIGN_MIDDLE); tempCell.setHorizontalAlignment(Element.ALIGN_CENTER); tempCell.setFixedHeight(130f); tempCell.setBackgroundColor(BaseColor.BLACK); tempCell.setBorderColor(BaseColor.WHITE); tempCell.setBorderWidth(4f); //tempCell.setBorder(Rectangle.NO_BORDER); obrTabulka.addCell(tempCell); freeCount--; } for (int i = 0; i < freeCount; i++) { PdfPCell tempCell = new PdfPCell(); tempCell.setBorder(Rectangle.NO_BORDER); obrTabulka.addCell(tempCell); } } } doc.add(obrTabulka); Font lastFont = new Font(Font.FontFamily.HELVETICA, 7, Font.ITALIC); Phrase lastText = new Phrase("This PDF document was generated by gTrax app for user " + user, lastFont); doc.add(lastText); doc.close(); } catch (Exception ex) { FileLogger.getInstance() .createNewLog("ERROR: Cannot CREATE PDF for track " + fileName + " for user " + user + " !!!"); System.out.println("pruser"); } }