Screenshot using PrintScreenand save it in work doc. I tried below but not working. i need a complete code to take screenshot if i press printscreen button and save it in word doc . i need to give doc name dynamically in cmd. until i stop he program, it have to take screen shot and save it in same doc.
public static void main(String[] args) throws ClassNotFoundException, InstantiationException, IllegalAccessException, IOException, AWTException {
try {
// Set the look and feel
UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
// Create a KeyEventDispatcher to listen to keyboard events
KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(new KeyEventDispatcher() {
#Override
public boolean dispatchKeyEvent(KeyEvent e) {
if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_PRINTSCREEN) {
// Take a screenshot when the print screen button is pressed
try {
// Create a Robot object
Robot robot = new Robot();
// Get the size of the screen
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
// Capture the screen image
BufferedImage screenImage = robot.createScreenCapture(screenRect);
// Get the current date and time
SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss");
String fileName = "screenshot_" + dateFormat.format(new Date()) + ".png";
// Save the screenshot to a file
ImageIO.write(screenImage, "png", new File(fileName));
// Create a Word document and add the screenshot
XWPFDocument document = new XWPFDocument();
XWPFParagraph paragraph = document.createParagraph();
// Create a run in the paragraph
XWPFRun run = paragraph.createRun();
// Add the screenshot to the run
FileInputStream stream = new FileInputStream(fileName);
run.addPicture(stream, XWPFDocument.PICTURE_TYPE_PNG, fileName, Units.toEMU(screenImage.getWidth()), Units.toEMU(screenImage.getHeight()));
// Close the stream
stream.close();
// Save the Word document
FileOutputStream out = new FileOutputStream("screenshot_" + dateFormat.format(new Date()) + ".docx");
document.write(out);
out.close();
// Show a message indicating that the screenshot was saved
JOptionPane.showMessageDialog(null, "Screenshot saved in screenshot.docx", "Information", JOptionPane.INFORMATION_MESSAGE);
return false;
}
catch(IOException | AWTException | InvalidFormatException exc){
exc.printStackTrace();}
return false;
}
return false;
}
});
} catch (UnsupportedLookAndFeelException ex) {
ex.printStackTrace();
}
Related
i am new to eclipse plugin development. i created a plugin which loads a unicode saved text file from the folder & displays it on a dialog & also setting it for the Label. If it is, in an English Language, everything is working fine. But if i try to load any other language text, it is displaying empty. How can i get through this.
Here is some code on how i am displaying it on dialog:
Shell shell = Display.getCurrent().getActiveShell();
// Loading the file by creating the assets folder & Temp.txt file inside
// Eclipse Plugin
URL url = FileLocator.find(bundle, new Path("assets/Temp.txt"), null);
URL fileUrl = null;
try {
fileUrl = FileLocator.toFileURL(url);
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
File file = new File(fileUrl.getPath());
String Message = "";
try {
if (file.exists()) {
BufferedReader in = new BufferedReader(
new FileReader(file));
String str;
while ((str = in.readLine()) != null) {
if (str.contains(LanguageSelected)) {
System.out.println(str);
Message = Message + "\n" + str;
}
}
}
} catch (IOException e) {
e.printStackTrace();
}
// Creating the dialog
Shell dialog = new Shell(shell, SWT.DIALOG_TRIM | SWT.APPLICATION_MODAL);
...
// Adding Label to dialog
Label LabelMessage = new Label(dialog, SWT.LEFT);
GridData data = new GridData(GridData.FILL_HORIZONTAL);
data.horizontalSpan = 6;
// Adding Message to the dialog
LabelMessage.setLayoutData(data);
LabelMessage.setBackground(new Color(null, 255, 255, 255)); // White
LabelMessage.setText(Message);
In your launch configuration, make sure you are setting the -nl parameter to the language you want to display. See http://help.eclipse.org/indigo/topic/org.eclipse.platform.doc.isv/reference/misc/runtime-options.html for information.
JPanel with 3 JButton and I need only two of them to be captured...
public static void grabScreenShot(JPanel panel) {
BufferedImage image = (BufferedImage) panel.createImage(
panel.getSize().width, panel.getSize().height);
panel.paint(image.getGraphics());
File file = null;
file = new File("Customers");
if (!file.exists()) {
file.mkdir();
}
try {
file = new File("Customers" + File.separator
+ String.valueOf(System.currentTimeMillis()));
ImageIO.write(image, "png", file);
System.out.println("Image was created");
} catch (IOException e) {
System.out.println("Had trouble writing the image.");
e.printStackTrace();
}
}
How to avoid unnecessary components to be captured.?
You can try to override paintComponent() of the buttons and introduce a flag needPaint. The flag is true by default.
if (needPaint) {
super.paintComponent(g);
}
In your grabScreenShot() set the flag to false for the button to be hidden and reset it back after panel.paint(image.getGraphics()); call
I have a program that uses OpenCV to take a picture using your webcam. It works like a charm on windows, yet, it doesn't work on OSx. The Frame where the Webcam view should appear stays empty. And when I take a picture, it just shows a black void, as if it couldnt find the webcam
public void run(){
try {
grabber = new VideoInputFrameGrabber(0);
grabber.start();
while (active) {
IplImage originalImage = grabber.grab();
Label.setIcon(new ImageIcon( originalImage.getBufferedImage() ));
}
grabber.stop();
grabber.flush();
} catch (Exception ex) {
//Logger.getLogger(ChPanel.class.getName()).log(Leve l.SEVERE, null, ex);
}
}
public BufferedImage saveImage(){
IplImage img;
try {
//capture image
img = grabber.grab();
// save to file
File outputfile = new File(Project.getInstance().getFileURLStr() + " capture" + fotoCount++ + ".jpg");
ImageIO.write(img.getBufferedImage(), "jpg", outputfile);
//get file and set it in the project library
BufferedImage ImportFile = ImageIO.read(outputfile);
Project p = Project.getInstance();
MainScreen ms = MainScreen.getInstance();
ImageIcon takenPhoto = new ImageIcon(ImportFile);
p.setNextImage(takenPhoto);
ms.setPanels();
return ImportFile;
} catch (com.googlecode.javacv.FrameGrabber.Exception e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
Does anyone know how to solve this? I suspect something about rights to use the webcam or something like that
grabber = new VideoInputFrameGrabber(0);
Here 0 is specified for Capture device number 0
May be the number 0th device is not available for video capture
Use this code to get the list of devices and number respectively.
import com.googlecode.javacv.cpp.videoInputLib.videoInput;
class Main {
public static void main(String[] args) {
int n=videoInput.listDevices();
for(int i=0;i<n;i++)
{
System.out.println(i+" = "+videoInput.getDeviceName(i));
}
}
}
And then specify the number for that device
grabber = new VideoInputFrameGrabber(1); // 0 or 1 or 2
To interact with webcam I use this library webcam-capture you can easely add openCV dependency with maven. This is a great library
I have a Print Button in my SWT TitleAreaDialog.
viewPDFButton.addSelectionListener(new SelectionAdapter() {
public void widgetSelected(SelectionEvent e) {
try {
startPdfPrintOperation();
}
catch (Exception e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
});
I am getting a existing PDF filename and path from a user selection from a table.
I am then wantinf to print the pdf file out to a local printer. The user needs to be allowed to select the local printer of choice.
public void startPdfPrintOperation() throws Exception {
File file = new File(getPDFFileName());
RandomAccessFile raf;
raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
pdfFile = new PDFFile(buf);
PDFPrintPage pages = new PDFPrintPage(pdfFile);
// Create Print Job
pjob = PrinterJob.getPrinterJob();
pjob.setPrintable(new MyPrintable());
final HashPrintRequestAttributeSet attset;
attset = new HashPrintRequestAttributeSet ();
attset.add (new PageRanges (1, pdfFile.getNumPages ()));
if (pjob.printDialog (attset)) {
try {
pjob.print (attset);
}
catch (PrinterException e) {
e.printStackTrace();
}
}
}
class MyPrintable implements Printable {
public int print (Graphics g, PageFormat format, int index) throws PrinterException {
int pagenum = index+1;
if (pagenum < 1 || pagenum > pdfFile.getNumPages ())
return NO_SUCH_PAGE;
Graphics2D g2d = (Graphics2D) g;
AffineTransform at = g2d.getTransform ();
PDFPage pdfPage = pdfFile.getPage (pagenum);
Dimension dim;
dim = pdfPage.getUnstretchedSize ((int) format.getImageableWidth (),
(int) format.getImageableHeight (),
pdfPage.getBBox ());
Rectangle bounds = new Rectangle ((int) format.getImageableX (),
(int) format.getImageableY (),
dim.width,
dim.height);
PDFRenderer rend = new PDFRenderer (pdfPage, (Graphics2D) g, bounds, null, null);
try
{
pdfPage.waitForFinish ();
rend.run ();
}
catch (InterruptedException ie)
{
MessageDialog.openError(null, "PDF Error Message", "Needs");
}
g2d.setTransform (at);
g2d.draw (new Rectangle2D.Double (format.getImageableX (),
format.getImageableY (),
format.getImageableWidth (),
format.getImageableHeight ()));
return PAGE_EXISTS;
}
}
I am getting the above error from line 315
if (pjob.printDialog (attset)) {
The printer dialog opens the entire application is frozen and goes unresponsive. Then in about 30 secs, I get the above error.
I have tried to use Display.getDefault().asyncExec(new Runnable() ) in multiple spots but that did not help.
Could it be because the base dialog is SWT and the printer dialog is AWT?
Since you didn't define "in multiple spots", I would suggest you refactor the print job in its own class, extends Thread and implement starting the print job in the run method.
I'm not familiar with all classes in above code, you can try simply starting this thread and it will run in parallel with the SWT thread. Try avoiding shared ressources, this may help resolving your deadlock. If you want to have a UI response from this thread, you can wrap e.g. the SWT messagebox ("Printing done!") in a call to Display.getDefault().asyncExec(new Runnable() { ... }.
Furthermore, please test if the printing code without UI code produces the same exception. If it does, the environment may be misconfigured.
I want to read *.icns files in OS X into a BufferedImage. Help
Try this: http://code.google.com/p/appengine-awt/source/browse/trunk/apache-sanselan/src/main/java/org/apache/sanselan/formats/icns/IcnsDecoder.java?spec=svn8&r=8
Which is actually from: http://incubator.apache.org/sanselan/site/index.html
You need to convert ICNS to another image type first, and after load this image you can delete it. This is how to convert PNG to ICNS, so you just need to do in the opposite way:
public static void Png(File png, File icns) throws IOException{
ImageIcon image = new ImageIcon(ImageIO.read(png));
ImageIconAs(image, icns);
}
public static void ImageIconAs(ImageIcon ii, File icns) throws IOException{IconAs((Icon)ii,icns);}
public static void IconAs(Icon icon, File icns) throws IOException{
if (icon != null) {
BufferedImage bi = new BufferedImage(icon.getIconWidth(), icon.getIconHeight(), BufferedImage.TYPE_INT_ARGB );
Graphics2D g = bi.createGraphics();
icon.paintIcon(new Canvas(), g, 0, 0 );
g.dispose();
File outputfile = new File("temp000.png");
ImageIO.write(bi, "png", outputfile);
execTerminal(new String[]{ "sips", "-s", "format", "tiff",
"temp000.png","--out", "temp000.tiff" });
File apaga2 = new File("temp000.png");
apaga2.delete();
execTerminal(new String[]{ "tiff2icns", "-noLarge",
"temp000.tiff", icns.getAbsolutePath()});
File apaga = new File("temp000.tiff");
apaga.delete();
}
}
static void execTerminal(String[] cmd){
int exitCode = 0;
try {
exitCode = Runtime.getRuntime().exec(cmd).waitFor();
}
catch (InterruptedException e) {e.printStackTrace();}
catch (IOException e) {
if (exitCode != 0) System.out.println("ln signaled an error with exit code " + exitCode);
}
}
You just need to use this to call the action:
Png(png_file,icns_file);
You can youse IconManager. It works with following icons formats:
*.ico - Windows Icon
*.icl - Windows Icon Library
*.icns - Macintosh Icon