List of usage examples for com.itextpdf.text Image getInstance
public static Image getInstance(final java.awt.Image image, final java.awt.Color color) throws BadElementException, IOException
From source file:edu.harvard.mcz.precapture.encoder.LabelEncoder.java
License:Open Source License
public Image getImage() throws BarcodeCreationException { Image image = null;//from w w w.ja v a 2 s .com BitMatrix barcode; try { barcode = getQRCodeMatrix(); BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(barcode); image = Image.getInstance(bufferedImage, null); //image.setDpi(300, 300); } catch (WriterException e) { throw new BarcodeCreationException(e.getMessage()); } catch (BadElementException e) { throw new BarcodeCreationException(e.getMessage()); } catch (IOException e) { throw new BarcodeCreationException(e.getMessage()); } return image; }
From source file:mobac.program.atlascreators.PaperAtlasPdf.java
License:Open Source License
@Override protected void processPage(BufferedImage image, int pageNumber) throws MapCreationException { int imageWidth = image.getWidth(); int imageHeight = image.getHeight(); if (document == null) { double width = UnitSystem.pixelsToPoints(imageWidth, s.dpi); double height = UnitSystem.pixelsToPoints(imageHeight, s.dpi); width += s.marginLeft + s.marginRight; height += s.marginTop + s.marginBottom; Rectangle r = new Rectangle((float) width, (float) height); document = createDocument(r);//from w w w. j a v a 2s.co m } Image iTextImage; try { iTextImage = Image.getInstance(image, Color.WHITE); } catch (BadElementException e) { throw new MapCreationException(map, e); } catch (IOException e) { throw new MapCreationException(map, e); } iTextImage.setCompressionLevel(s.compression); iTextImage.setDpi(s.dpi, s.dpi); float width = (float) UnitSystem.pixelsToPoints(imageWidth, s.dpi); float height = (float) UnitSystem.pixelsToPoints(imageHeight, s.dpi); iTextImage.scaleAbsolute(width, height); try { document.add(iTextImage); } catch (DocumentException e) { throw new MapCreationException(map, e); } document.newPage(); }
From source file:org.admir.pdf.PdfApp.java
public static void main(String[] args) { try {/* w w w.j av a 2s .c o m*/ Document document = new Document(); PdfWriter.getInstance(document, new FileOutputStream(FILE)); document.open(); addMetaData(document); addTitlePage(document); addContent(document); Image image = Image.getInstance(QRHelper.getQRImage("Amrica najljepsa", 200, null), Color.BLACK); document.add(image); document.close(); } catch (Exception e) { e.printStackTrace(); } }
From source file:org.alfresco.extension.countersign.action.executer.PDFSignatureProviderActionExecuter.java
License:Open Source License
/** * @see org.alfresco.repo.action.executer.ActionExecuterAbstractBase#executeImpl(org.alfresco.service.cmr.repository.NodeRef, * org.alfresco.service.cmr.repository.NodeRef) *//*from w w w .j av a2 s .co m*/ protected void executeImpl(Action ruleAction, NodeRef actionedUponNodeRef) { if (serviceRegistry.getNodeService().exists(actionedUponNodeRef) == false) { // node doesn't exist - can't do anything return; } String location = (String) ruleAction.getParameterValue(PARAM_LOCATION); String geolocation = (String) ruleAction.getParameterValue(PARAM_GEOLOCATION); String reason = (String) ruleAction.getParameterValue(PARAM_REASON); String position = (String) ruleAction.getParameterValue(PARAM_POSITION); String keyPassword = (String) ruleAction.getParameterValue(PARAM_KEY_PASSWORD); String signatureJson = (String) ruleAction.getParameterValue(PARAM_SIGNATURE_JSON); Boolean visible = (Boolean) ruleAction.getParameterValue(PARAM_VISIBLE); Boolean graphic = (Boolean) ruleAction.getParameterValue(PARAM_GRAPHIC); boolean useSignatureField = false; String user = AuthenticationUtil.getRunAsUser(); String positionType = "predefined"; String positionLoc = "center"; JSONObject box; int page = -1; // parse out the position JSON JSONObject positionObj = null; try { positionObj = (JSONObject) parser.parse(position); } catch (ParseException e) { logger.error("Could not parse position JSON from Share"); throw new AlfrescoRuntimeException("Could not parse position JSON from Share"); } // get the page page = Integer.parseInt(String.valueOf(positionObj.get("page"))); // get the positioning type positionType = String.valueOf(positionObj.get("type")); // get the position (field or predefined) positionLoc = String.valueOf(positionObj.get("position")); // get the box (if required) box = (JSONObject) positionObj.get("box"); int width = 350; int height = 75; File tempDir = null; // current date, used for both signing the PDF and creating the // associated signature object Calendar now = Calendar.getInstance(); try { // get the keystore, pk and cert chain SignatureProvider signatureProvider = signatureProviderFactory.getSignatureProvider(user); KeyStore keystore = signatureProvider.getUserKeyStore(keyPassword); PrivateKey key = (PrivateKey) keystore.getKey(alias, keyPassword.toCharArray()); Certificate[] chain = keystore.getCertificateChain(alias); // open original pdf ContentReader pdfReader = getReader(actionedUponNodeRef); PdfReader reader = new PdfReader(pdfReader.getContentInputStream()); // create temp dir to store file File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); OutputStream cos = serviceRegistry.getContentService() .getWriter(actionedUponNodeRef, ContentModel.PROP_CONTENT, true).getContentOutputStream(); PdfStamper stamp = PdfStamper.createSignature(reader, cos, '\0', file, true); PdfSignatureAppearance sap = stamp.getSignatureAppearance(); sap.setCrypto(key, chain, null, PdfSignatureAppearance.SELF_SIGNED); // set reason for signature, location of signer, and date sap.setReason(reason); sap.setLocation(location); sap.setSignDate(now); // get the image for the signature BufferedImage sigImage = SignatureToImage.convertJsonToImage(signatureJson, width, height); // save the signature image back to the signatureProvider signatureProvider.saveSignatureImage(sigImage, signatureJson); if (visible) { //if this is a graphic sig, set the graphic here if (graphic) { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.GRAPHIC); sap.setSignatureGraphic(Image.getInstance(sigImage, Color.WHITE)); } else { sap.setRenderingMode(PdfSignatureAppearance.RenderingMode.NAME_AND_DESCRIPTION); } // either insert the sig at a defined field or at a defined position / drawn loc if (positionType.equalsIgnoreCase(POSITION_TYPE_PREDEFINED)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(positionLoc, pageRect, width, height), page, null); } else if (positionType.equalsIgnoreCase(POSITION_TYPE_DRAWN)) { Rectangle pageRect = reader.getPageSizeWithRotation(page); sap.setVisibleSignature(positionBlock(pageRect, box), page, null); } else { sap.setVisibleSignature(positionLoc); useSignatureField = true; } } // close the stamp, applying the changes to the PDF stamp.close(); reader.close(); cos.close(); //delete the temp file file.delete(); // apply the "signed" aspect serviceRegistry.getNodeService().addAspect(actionedUponNodeRef, CounterSignSignatureModel.ASPECT_SIGNED, new HashMap<QName, Serializable>()); // create a "signature" node and associate it with the signed doc addSignatureNodeAssociation(actionedUponNodeRef, location, reason, useSignatureField ? positionLoc : "none", now.getTime(), geolocation, page, positionLoc); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (ContentIOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (KeyStoreException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (UnrecoverableKeyException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (NoSuchAlgorithmException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.alfresco.extension.pdftoolkit.repo.action.executer.PDFWatermarkActionExecuter.java
License:Apache License
/** * Applies an image watermark//from w w w. j av a 2 s .c o m * * @param reader * @param writer * @param options * @throws Exception */ private void imageAction(Action ruleAction, NodeRef actionedUponNodeRef, NodeRef watermarkNodeRef, ContentReader actionedUponContentReader, ContentReader watermarkContentReader, Map<String, Object> options) { PdfStamper stamp = null; File tempDir = null; ContentWriter writer = null; try { // get a temp file to stash the watermarked PDF in before moving to // repo File alfTempDir = TempFileProvider.getTempDir(); tempDir = new File(alfTempDir.getPath() + File.separatorChar + actionedUponNodeRef.getId()); tempDir.mkdir(); File file = new File(tempDir, serviceRegistry.getFileFolderService().getFileInfo(actionedUponNodeRef).getName()); // get the PDF input stream and create a reader for iText PdfReader reader = new PdfReader(actionedUponContentReader.getContentInputStream()); stamp = new PdfStamper(reader, new FileOutputStream(file)); PdfContentByte pcb; // get a com.itextpdf.text.Image object via java.imageio.ImageIO Image img = Image.getInstance(ImageIO.read(watermarkContentReader.getContentInputStream()), null); // get the PDF pages and position String pages = (String) options.get(PARAM_PAGE); String position = (String) options.get(PARAM_POSITION); String depth = (String) options.get(PARAM_WATERMARK_DEPTH); // image requires absolute positioning or an exception will be // thrown // set image position according to parameter. Use // PdfReader.getPageSizeWithRotation // to get the canvas size for alignment. img.setAbsolutePosition(100f, 100f); // stamp each page int numpages = reader.getNumberOfPages(); for (int i = 1; i <= numpages; i++) { Rectangle r = reader.getPageSizeWithRotation(i); // set stamp position if (position.equals(POSITION_BOTTOMLEFT)) { img.setAbsolutePosition(0, 0); } else if (position.equals(POSITION_BOTTOMRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), 0); } else if (position.equals(POSITION_TOPLEFT)) { img.setAbsolutePosition(0, r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_TOPRIGHT)) { img.setAbsolutePosition(r.getWidth() - img.getWidth(), r.getHeight() - img.getHeight()); } else if (position.equals(POSITION_CENTER)) { img.setAbsolutePosition(getCenterX(r, img), getCenterY(r, img)); } // if this is an under-text stamp, use getUnderContent. // if this is an over-text stamp, usse getOverContent. if (depth.equals(DEPTH_OVER)) { pcb = stamp.getOverContent(i); } else { pcb = stamp.getUnderContent(i); } // only apply stamp to requested pages if (checkPage(pages, i, numpages)) { pcb.addImage(img); } } stamp.close(); // Get a writer and prep it for putting it back into the repo //can't use BasePDFActionExecuter.getWriter here need the nodeRef of the destination NodeRef destinationNode = createDestinationNode(file.getName(), (NodeRef) ruleAction.getParameterValue(PARAM_DESTINATION_FOLDER), actionedUponNodeRef); writer = serviceRegistry.getContentService().getWriter(destinationNode, ContentModel.PROP_CONTENT, true); writer.setEncoding(actionedUponContentReader.getEncoding()); writer.setMimetype(FILE_MIMETYPE); // Put it in the repo writer.putContent(file); // delete the temp file file.delete(); } catch (IOException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } catch (DocumentException e) { throw new AlfrescoRuntimeException(e.getMessage(), e); } finally { if (tempDir != null) { try { tempDir.delete(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } if (stamp != null) { try { stamp.close(); } catch (Exception ex) { throw new AlfrescoRuntimeException(ex.getMessage(), ex); } } } }
From source file:org.cidte.sii.negocio.PDFWriter.java
public void writePDF(ArrayList<Writable> list, String directorio, String nombre, java.awt.Image image) throws DocumentException, FileNotFoundException, BadElementException, IOException { Document doc = new Document(); PdfWriter docWriter;/* w w w. j a v a2s . c om*/ // special font sizes Font bfBold12 = new Font(Font.FontFamily.TIMES_ROMAN, 12, Font.BOLD, new BaseColor(0, 0, 0)); Font bf12 = new Font(Font.FontFamily.TIMES_ROMAN, 12); // file path String path = directorio + nombre + ".pdf"; docWriter = PdfWriter.getInstance(doc, new FileOutputStream(new File(path))); // document header attributes doc.addAuthor("sii"); doc.addCreationDate(); doc.addProducer(); doc.addCreator("sii"); doc.addTitle(nombre); doc.setPageSize(PageSize.LETTER); // open document doc.open(); Image img = Image.getInstance(image, null); img.setAlignment(Element.ALIGN_LEFT); doc.add(img); // create a paragraph Paragraph paragraph = new Paragraph("iText is a library that allows you to create and " + "manipulate PDF documents. It enables developers looking to enhance web and other " + "applications with dynamic PDF document generation and/or manipulation."); // create PDF table with the given widths PdfPTable table = new PdfPTable(list.get(0).getNames().length); // set table width a percentage of the page width table.setWidthPercentage(100); table.setSpacingBefore(10f); // Space before table table.setSpacingAfter(10f); // Space after table // insert column headings String[] headings = list.get(0).getNames(); for (String heading : headings) { insertCell(table, heading, Element.ALIGN_CENTER, 1, bfBold12); } table.setHeaderRows(1); // insert the data for (int i = 0; i < list.size(); i++) { Writable w = list.get(i); Object[] arr = w.getAsArray(); for (int j = 0; j < arr.length; j++) { // arr[j] insertCell(table, arr[j].toString(), Element.ALIGN_LEFT, 1, bf12); } } // insert an empty row // insertCell(table, "", Element.ALIGN_LEFT, 4, bfBold12); // add the PDF table to the paragraph paragraph.add(table); // add the paragraph to the document doc.add(paragraph); // close the document doc.close(); // close the writer docWriter.close(); }
From source file:org.kalypso.ogc.gml.map.handlers.utils.PDFExporter.java
License:Open Source License
public IStatus doExport(final File targetFile, IProgressMonitor monitor) { /* If no monitor is given, take a null progress monitor. */ if (monitor == null) monitor = new NullProgressMonitor(); /* The output streams. */ BufferedOutputStream os = null; try {/*from w ww .ja va2s . c o m*/ /* Monitor. */ monitor.beginTask(Messages.getString("PDFExporter_0"), 1000); //$NON-NLS-1$ monitor.subTask(Messages.getString("PDFExporter_1")); //$NON-NLS-1$ /* Create the image. */ final Insets insets = new Insets(10, 10, 10, 10); final BufferedImage image = MapModellHelper.createWellFormedImageFromModel(m_mapPanel, (int) PageSize.A4.getHeight(), (int) PageSize.A4.getWidth(), insets, 1); /* Convert to an itext image. */ final Image img = Image.getInstance(image, null); /* Monitor. */ monitor.worked(500); monitor.subTask(Messages.getString("PDFExporter_2")); //$NON-NLS-1$ /* Create the output stream. */ os = new BufferedOutputStream(new FileOutputStream(targetFile)); /* Create a new document. */ final Document document = new Document( new com.itextpdf.text.Rectangle(PageSize.A4.getHeight(), PageSize.A4.getWidth()), 30, 30, 30, 30); /* Create the pdf writter. */ final PdfWriter writer = PdfWriter.getInstance(document, os); writer.setCompressionLevel(0); /* Open the document. */ document.open(); /* Set the position. */ img.setAbsolutePosition(0, 0); /* Set to the pdf. */ writer.getDirectContent().addImage(img, true); /* Close the document. */ document.close(); /* Monitor. */ monitor.worked(500); return new Status(IStatus.OK, KalypsoGisPlugin.getId(), Messages.getString("PDFExporter_3")); //$NON-NLS-1$ } catch (final Exception ex) { return new Status(IStatus.ERROR, KalypsoGisPlugin.getId(), ex.getLocalizedMessage(), ex); } finally { /* Close the output streams. */ IOUtils.closeQuietly(os); /* Monitor. */ monitor.done(); } }
From source file:org.openscience.cdk.applications.taverna.renderer.DrawPDF.java
License:Open Source License
public static void drawMoleculesAsPDF(List<IAtomContainer> molecules, File file) throws Exception { Document pdf = new Document(); PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(file)); pdf.open();/*from w w w.j a va2 s.c o m*/ Paragraph para = new Paragraph(); Font font = FontFactory.getFont(FontFactory.HELVETICA, 24); para.setFont(font); para.setAlignment(Element.ALIGN_CENTER); para.add("CDK-Taverna 2.0"); pdf.add(para); para = new Paragraph(); font = FontFactory.getFont(FontFactory.HELVETICA, 12); para.setFont(font); para.setAlignment(Element.ALIGN_CENTER); para.add("The open-source chemo-/bioinformatics workflow solution\n\n\n"); pdf.add(para); PdfPTable table = new PdfPTable(ncol); for (IAtomContainer molecule : molecules) { PdfPCell cell = new PdfPCell(); cell.disableBorderSide(PdfPCell.BOTTOM | PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP); BufferedImage image = Draw2DStructure.drawMolecule(molecule, (int) pdf.getPageSize().getWidth(), height, 0.95); java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(image.getSource()); cell.addElement(Image.getInstance(awtImage, null)); table.addCell(cell); cell = new PdfPCell(); cell.disableBorderSide(PdfPCell.LEFT | PdfPCell.RIGHT | PdfPCell.TOP); para = new Paragraph(); font = FontFactory.getFont(FontFactory.HELVETICA, 12); para.setFont(font); para.add("\n"); for (Entry<Object, Object> entry : molecule.getProperties().entrySet()) { try { String key = String.valueOf(entry.getKey()); String value = String.valueOf(entry.getValue()); para.add(key + ":\n" + value + "\n\n"); } catch (Exception e) { // Not a String entry --> skip } } cell.addElement(para); table.addCell(cell); } pdf.add(table); pdf.close(); }
From source file:org.openscience.cdk.applications.taverna.renderer.DrawPDF.java
License:Open Source License
public static void drawReactionAsPDF(List<Reaction> reactions, File file) throws Exception { Document pdf = new Document(); PdfWriter writer = PdfWriter.getInstance(pdf, new FileOutputStream(file)); pdf.open();/* w ww . ja v a 2 s.c om*/ PdfPTable table = new PdfPTable(1); int reactionWitdh = width * (reactions.get(0).getReactantCount() + reactions.get(0).getProductCount() + 1); if (reactionWitdh > width * 5) { reactionWitdh = width * 5; } for (IReaction reaction : reactions) { // shift the molecules not to overlap // TODO remove here Rectangle2D usedBounds = null; usedBounds = null; for (IAtomContainer container : ReactionManipulator.getAllAtomContainers(reaction)) { // now move it so that they don't overlap Rectangle2D bounds = BoundsCalculator.calculateBounds(container); if (usedBounds != null) { double bondLength = GeometryTools.getBondLengthAverage(container); Rectangle2D shiftedBounds = GeometryTools.shiftContainer(container, bounds, usedBounds, bondLength); usedBounds = usedBounds.createUnion(shiftedBounds); } else { usedBounds = bounds; } } PdfPCell cell = new PdfPCell(); BufferedImage image = Draw2DStructure.drawReaction(reaction, reactionWitdh, height); java.awt.Image awtImage = Toolkit.getDefaultToolkit().createImage(image.getSource()); cell.addElement(Image.getInstance(awtImage, null)); table.addCell(cell); } pdf.add(table); pdf.close(); }
From source file:org.opensrp.web.utils.PdfUtil.java
License:Open Source License
public static ByteArrayOutputStream generatePdf(List<String> data, int width, int height, int copiesImage, int columnLimit) { try {// w w w.j a va2s . c o m ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); Document document = new Document(); document.setMargins(MARGINS[0], MARGINS[1], MARGINS[2], MARGINS[3]); PdfWriter.getInstance(document, byteArrayOutputStream); document.open(); PdfPTable table = new PdfPTable(columnLimit); table.setTotalWidth(TABLE_WIDTH); table.setHorizontalAlignment(Element.ALIGN_LEFT); int length = 0; int count = 0; for (String str : data) { if (str.length() > 0 && str.length() <= 5) { length = 54; } else if (str.length() >= 6 && str.length() <= 9) { length = 44; } else if (str.length() >= 10 && str.length() <= 11) { length = 36; } else if (str.length() >= 12 && str.length() <= 14) { length = 27; } else if (str.length() >= 15 && str.length() <= 17) { length = 22; } else { length = 15; } Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>(); hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix byteMatrix = null; byteMatrix = qrCodeWriter.encode(str, BarcodeFormat.QR_CODE, width, height, hintMap); int matrixWidth = byteMatrix.getWidth(); int matrixHeight = byteMatrix.getHeight(); BufferedImage image = new BufferedImage(matrixWidth, matrixHeight, BufferedImage.TYPE_INT_RGB); image.createGraphics(); Graphics2D graphics = (Graphics2D) image.getGraphics(); graphics.setColor(Color.WHITE); graphics.fillRect(0, 0, matrixWidth + 5, matrixHeight + 5); graphics.setFont(graphics.getFont().deriveFont(13f)); graphics.setColor(Color.BLACK); graphics.drawString(str, length, height - 10); for (int i = 0; i < matrixHeight; i++) { for (int j = 0; j < matrixHeight; j++) { if (byteMatrix.get(i, j)) { graphics.fillRect((i), j, 1, 1); } } } Image itextImage = null; itextImage = Image.getInstance(Toolkit.getDefaultToolkit().createImage(image.getSource()), null); for (int i = 0; i < copiesImage; i++) { PdfPCell cell = new PdfPCell(itextImage); cell.setBorder(Rectangle.NO_BORDER); count++; table.addCell(cell); } } for (int i = 0; i < 6; i++) { if (count % columnLimit != 0) { PdfPCell cell = new PdfPCell(new Phrase()); cell.setBorder(Rectangle.NO_BORDER); table.addCell(cell); count++; } } document.add(table); document.close(); return byteArrayOutputStream; } catch (Exception e) { return null; } }