I am trying to edit a run using Apache POI, and I want this edit to show up as a tracked revision (so that I can accept/reject this suggestion) in a .docx file.
package apache;
import java.io.FileOutputStream;
import java.util.List;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
public class Main {
public static void main(String[] args) throws Exception {
XWPFDocument doc = new XWPFDocument(OPCPackage.open("input.docx"));
doc.setTrackRevisions(true);
for (XWPFParagraph p : doc.getParagraphs()) {
List<XWPFRun> runs = p.getRuns();
if (runs != null) {
for (XWPFRun r : runs) {
String text = r.getText(0);
if (text != null && text.contains("needle")) {
text = text.replace("needle", "haystack");
r.setText(text, 0);
}
}
}
doc.write(new FileOutputStream("/Users/srt/Desktop/output.docx"));
}
}
This code is able to replace the text perfectly, but I cannot show this edit as a tracked revision. I made use of the doc.setTrackRevisions(true) method, but it still does not track the revision. Any help here will be really appreciated!
Related
How do you add attachments from a generic filetype using Apose.Slides using java?
The manual PowerPoint operation I’m trying to do programmatically is:
Insert -> Object -> From file
Is this possible with Aspose.Slides insert an Excel file as a link using java?
The below code is working fine for attaching the Excel file using aspose slides
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;
import com.aspose.slides.IOleEmbeddedDataInfo;
import com.aspose.slides.IOleObjectFrame;
import com.aspose.slides.OleEmbeddedDataInfo;
import com.aspose.slides.Presentation;
import com.aspose.slides.SaveFormat;
public class SetFileTypeForAnEmbeddingObject2 {
public static void main(String[] args) throws IOException {
Presentation pres = new Presentation();
try {
// Add known Ole objects
byte[] fileBytes = Files.readAllBytes(Paths.get("C:\\work\\Demo uploadt.xlsm"));
// Create Ole embedded file info
IOleEmbeddedDataInfo dataInfo = new OleEmbeddedDataInfo(fileBytes, "xls");
// Create OLE object
IOleObjectFrame oleFrame = pres.getSlides().get_Item(0).getShapes().addOleObjectFrame(150, 420, 250, 50,
dataInfo);
oleFrame.setObjectIcon(true);
pres.save("C:\\work\\" + "SetFileTypeForAnEmbeddingObject7.pptx", SaveFormat.Pptx);
} finally {
if (pres != null)
pres.dispose();
}
}
}
Hi guys i Searched Every Where Solution For But Can't Find. Why Am Getting Null Pointer Exception For This i Dunno. Please Sort Me This Out. It is Showing as Path is Only Wrong But i Specified it Correctly only.
My Code :
package UsingExcel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import com.sun.rowset.internal.Row;
public class Demo
{
public void ReadExcel(String filepath,String filename,String Sheetname) throws IOException
{
File file = new File(filepath); // line 21
FileInputStream stream = new FileInputStream(file);
Workbook Mybook = null;
String FileExtensionnname = filename.substring(filename.indexOf("."));
if(FileExtensionnname.equals(".xlsx"))
{
Mybook = new XSSFWorkbook(stream);
}
else if(FileExtensionnname.equals(".xls"))
{
Mybook = new HSSFWorkbook(stream);
}
Sheet filesheet = Mybook.getSheet(Sheetname);
int rowcount = filesheet.getLastRowNum()-filesheet.getFirstRowNum();
for(int i=0;i<rowcount+1;i++)
{
org.apache.poi.ss.usermodel.Row row =filesheet.getRow(i);
for(int j=0;j<row.getLastCellNum();j++)
{
System.out.println(row.getCell(j).getStringCellValue()+ "||");
}
System.out.println();
}
}
public static void main(String[] args) throws IOException
{
Demo excelfile = new Demo();
String filepath = System.getProperty("E:\\Mybook.xlsx");
excelfile.ReadExcel(filepath, "Mybook.xlsx", "DemoExcel");
}
}
My Error is :
Exception in thread "main" java.lang.NullPointerException
at java.io.File.<init>(Unknown Source)
at UsingExcel.Demo.ReadExcel(Demo.java:21)
at UsingExcel.Demo.main(Demo.java:61)
Hope You Have Understood My Problem, Please Sort This out. But When am Testing a Login Page Using Excel That No Problem Will Be Coming, Now i Try To Print on The
Console it is Not Working.
Your filepath should just be
String filepath = "E:\\Mybook.xlsx", don't use System.getProperty.
From docs :
Gets the system property indicated by the specified key
A null is being passed to your method ReadExcel(...), because there is no System property defined as E:\Mybook.xlsx
I have images of codes that I want to decode. How can I use zxing so that I specify the image location and get the decoded text back, and in case the decoding fails (it will for some images, that's the project), it gives me an error.
How can I setup zxing on my Windows machine? I downloaded the jar file, but I don't know where to start. I understand I'll have to create a code to read the image and supply it to the library reader method, but a guide how to do that would be very helpful.
I was able to do it. Downloaded the source and added the following code. Bit rustic, but gets the work done.
import com.google.zxing.NotFoundException;
import com.google.zxing.ChecksumException;
import com.google.zxing.FormatException;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.DecodeHintType;
import com.google.zxing.Reader;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.Result;
import com.google.zxing.LuminanceSource;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import java.io.File;
import java.io.IOException;
import java.util.*;
import com.google.zxing.qrcode.QRCodeReader;
class qr
{
public static void main(String args[])
{
Reader xReader = new QRCodeReader();
BufferedImage dest = null;
try
{
dest = ImageIO.read(new File(args[0]));
}
catch(IOException e)
{
System.out.println("Cannot load input image");
}
LuminanceSource source = new BufferedImageLuminanceSource(dest);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Vector<BarcodeFormat> barcodeFormats = new Vector<BarcodeFormat>();
barcodeFormats.add(BarcodeFormat.QR_CODE);
HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>(3);
decodeHints.put(DecodeHintType.POSSIBLE_FORMATS, barcodeFormats);
decodeHints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
Result result = null;
try
{
result = xReader.decode(bitmap, decodeHints);
System.out.println("Code Decoded");
String text = result.getText();
System.out.println(text);
}
catch(NotFoundException e)
{
System.out.println("Decoding Failed");
}
catch(ChecksumException e)
{
System.out.println("Checksum error");
}
catch(FormatException e)
{
System.out.println("Wrong format");
}
}
}
The project includes a class called CommandLineRunner which you can simply call from the command line. You can also look at its source to see how it works and reuse it.
There is nothing to install or set up. It's a library. Typically you don't download the jar but declare it as a dependency in your Maven-based project.
If you just want to send an image to decode, use http://zxing.org/w/decode.jspx
I was wondering if theres a way to use Java to get the encoding type of a string on the clipboard. (I'd give more details but the question is fairly straight forward).
Ex. I go into a unicode program, copy text, use the Java program to decipher it, and the java program spits out "UTF-16"
To access the clipboard, you can use the awt datatransfer classes.
To detect the charset, you can use the CharsetDetector from ICU project.
Here is the code :
public static String getClipboardCharset () throws UnsupportedCharsetException, UnsupportedFlavorException, IOException {
String clipText = null;
final Clipboard clipboard = Toolkit.getDefaultToolkit().getSystemClipboard();
final Transferable contents = clipboard.getContents(null);
if ((contents != null) && contents.isDataFlavorSupported(DataFlavor.stringFlavor))
clipText = (String) contents.getTransferData(DataFlavor.stringFlavor);
if (contents!=null && clipText!=null) {
final CharsetDetector cd = new CharsetDetector();
cd.setText(clipText.getBytes());
final CharsetMatch cm = cd.detect();
if (cm != null)
return cm.getName();
}
throw new UnsupportedCharsetException("Unknown");
}
Here are the imports needed :
import java.awt.Toolkit;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.datatransfer.UnsupportedFlavorException;
import java.io.IOException;
import java.nio.charset.UnsupportedCharsetException;
import com.ibm.icu.text.CharsetDetector;
import com.ibm.icu.text.CharsetMatch;
hello:
I'm writing code in java for nutch(open source search engine) to remove the movments from arabic words in the indexer.
I don't know what is the error in it.
Tthis is the code:
package com.mycompany.nutch.indexing;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.io.Text;
import org.apache.log4j.Logger;
import org.apache.nutch.crawl.CrawlDatum;
import org.apache.nutch.crawl.Inlinks;
import org.apache.nutch.indexer.IndexingException;
import org.apache.nutch.indexer.IndexingFilter;
import org.apache.nutch.indexer.NutchDocument;
import org.apache.nutch.parse.getData().parse.getData();
public class InvalidUrlIndexFilter implements IndexingFilter {
private static final Logger LOGGER =
Logger.getLogger(InvalidUrlIndexFilter.class);
private Configuration conf;
public void addIndexBackendOptions(Configuration conf) {
// NOOP
return;
}
public NutchDocument filter(NutchDocument doc, Parse parse, Text url,
CrawlDatum datum, Inlinks inlinks) throws IndexingException {
if (url == null) {
return null;
}
char[] parse.getData() = input.trim().toCharArray();
for(int p=0;p<parse.getData().length;p++)
if(!(parse.getData()[p]=='َ'||parse.getData()[p]=='ً'||parse.getData()[p]=='ُ'||parse.getData()[p]=='ِ'||parse.getData()[p]=='ٍ'||parse.getData()[p]=='ٌ' ||parse.getData()[p]=='ّ'||parse.getData()[p]=='ْ' ||parse.getData()[p]=='"' ))
new String.append(parse.getData()[p]);
return doc;
}
public Configuration getConf() {
return conf;
}
public void setConf(Configuration conf) {
this.conf = conf;
}
}
I think that the error is in using parse.getdata() but I don't know what I should use instead of it?
The line
char[] parse.getData() = input.trim().toCharArray();
will give you a compile error because the left hand side is not a variable. Please replace parse.getData() by a unique variable name (e.g. parsedData) in this line and the following lines.
Second the import of
import org.apache.nutch.parse.getData().parse.getData();
will also fail. Looks a lot like a text replace issue.