Can't read Arabic PDF file with custom font - java

I have an Arabic PDF file which contains a custom font, so when I try to read the file I faced some unreadable words and characters replaced with another character or symbol.
Here is the link to the PDF file I'm working on.
public class TikaAnalysis {
public static String extractContentUsingFacade(InputStream stream) throws IOException, TikaException {
Tika tika = new Tika();
String content = tika.parseToString(stream);
try {
WriteOnWordDoc(str);
} catch (Exception e) {
e.printStackTrace();
}
return content;
}
public static void WriteOnWordDoc(String fileContent) throws Exception {
XWPFDocument document = new XWPFDocument();
XWPFParagraph tmpParagraph = document.createParagraph();
XWPFRun tmpRun = tmpParagraph.createRun();
tmpRun.setText(fileContent);
tmpRun.setFontSize(10);
FileOutputStream fos = new FileOutputStream(new File("extractedContent.docx"));
document.write(fos);
fos.close();
}
public static void main(String[] args) {
FileInputStream inputStream = null;
String path ="File.pdf";
try {
File file=new File(path);
inputStream = new FileInputStream(file);
InputStream input = new BufferedInputStream(inputStream);
TikaAnalysis.extractContentUsingFacade(inputStream);
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (inputStream != null) {
try {
System.out.println("close the file ");
inputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}

Related

JavaFX application: printer cannot print file

I am creating a PDF document in tDEST by itext library. Then I am cleaning trailing spaces in resize functions writing a new document to DEST. If I want to print tDest document, it works fine but if I try to print a DEST file, it does not print anything and does not throw any exception.
Here is my main class:
String DEST = System.getProperty("user.home") + "\\Documents\\invoice.pdf";
String tDEST = System.getProperty("user.home") + "\\Documents\\temp.pdf";
public static void main(String... args) {
....
resize();
PDDocument document = null;
try {
document = PDDocument.load(new File(DEST));
} catch (IOException e) {
e.printStackTrace();
}
PrinterJob job = PrinterJob.getPrinterJob();
job.setPageable(new PDFPageable(document));
try {
PrintService myPrintService = findPrintService(Commons.printer.getName());
job.setPrintService(myPrintService);
job.print();
} catch (Exception e) {
e.printStackTrace();
System.out.println("Printer ishlamayapti");
}
....
}
public void resize() {
try {
FileOutputStream fileOutputStream = new FileOutputStream(DEST);
PdfReader reader = new PdfReader(tDEST);
com.itextpdf.text.Rectangle pageSize = reader.getPageSize(1);
PdfStamper stamper = new PdfStamper(reader, fileOutputStream);
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
TextMarginFinder finder = parser.processContent(1, new TextMarginFinder());
PdfDictionary page = reader.getPageN(1);
page.put(PdfName.CROPBOX, new PdfArray(new float[]{pageSize.getLeft(), finder.getLly(), pageSize.getRight(), pageSize.getTop()}));
stamper.markUsed(page);
stamper.flush();
stamper.close();
reader.close();
fileOutputStream.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}

Appending text to existing word file using XWPFDocument

I am trying to append a text and screenshot to the existing word file. But every time I execute the below code I am getting error as :
org.apache.poi.EmptyFileException: The supplied file was empty (zero bytes long) at
org.apache.poi.util.IOUtils.peekFirstNBytes(IOUtils.java:74) at
org.apache.poi.util.IOUtils.peekFirst8Bytes(IOUtils.java:57) at
org.apache.poi.poifs.filesystem.FileMagic.valueOf(FileMagic.java:135)
at
org.apache.poi.openxml4j.opc.internal.ZipHelper.verifyZipHeader(ZipHelper.java:175)
at
org.apache.poi.openxml4j.opc.internal.ZipHelper.openZipStream(ZipHelper.java:209)
at org.apache.poi.openxml4j.opc.ZipPackage.(ZipPackage.java:98)
at org.apache.poi.openxml4j.opc.OPCPackage.open(OPCPackage.java:324)
at org.apache.poi.util.PackageHelper.open(PackageHelper.java:37) at
org.apache.poi.xwpf.usermodel.XWPFDocument.(XWPFDocument.java:116)
at test.tester.(tester.java:44) at
test.tester.main(tester.java:100)
failed to create file Taking first ss
java.lang.NullPointerException at test.tester.setText(tester.java:62)
at test.tester.main(tester.java:103)
Here is the code:
public class tester{
FileOutputStream fos = null;
XWPFDocument doc = null;
// create para and run
XWPFParagraph para = null;
XWPFRun run = null;
File file = null;
public tester() {
try {
file = new File("WordDocWithImage.docx");
writeToWord();
//doc = new XWPFDocument();
doc = new XWPFDocument(OPCPackage.open(file));
//doc = new XWPFDocument(new FileInputStream("WordDocWithImage.docx"));
para = doc.createParagraph();
run = para.createRun();
para.setAlignment(ParagraphAlignment.CENTER);
} catch (Exception e) {
e.printStackTrace();
System.out.println("failed to create file");
}
}
public FileOutputStream writeToWord() throws FileNotFoundException {
fos = new FileOutputStream("WordDocWithImage.docx");
return fos;
}
public void setText(String text) {
run.setText(text);
}
public void takeScreenshot() throws IOException, AWTException, InvalidFormatException {
// Take screenshot
Robot robot = new Robot();
Rectangle screenRect = new Rectangle(Toolkit.getDefaultToolkit().getScreenSize());
BufferedImage screenFullImage = robot.createScreenCapture(screenRect);
// convert buffered image to Input Stream
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(screenFullImage, "jpeg", baos);
baos.flush();
ByteArrayInputStream bis = new ByteArrayInputStream(baos.toByteArray());
baos.close();
// add image to word doc
run.addBreak();
run.addPicture(bis, XWPFDocument.PICTURE_TYPE_JPEG, "image file", Units.toEMU(450), Units.toEMU(250)); // 200x200
// pixels
bis.close();
}
public void writeToFile() {
try {
// write word doc to file
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
tester t = new tester();
try {
System.out.println("Taking first ss");
t.setText("First Text");
t.takeScreenshot();
System.out.println("Taking second ss");
t.setText("Second Text");
t.takeScreenshot();
t.writeToFile();
} catch(Exception e) {
e.printStackTrace();
}
}
}
Please assist.
The supplied file was empty (zero bytes long)
The problem is about getting the WordDocWithImage file in this line.
file = new File("WordDocWithImage.docx");
It could not find the docx file. You should check the location of the file and give the true path in there.
EDIT: You need to change the outputStream to different location. You can create a subfolder. I got ss trying this.
public FileOutputStream writeToWord() throws FileNotFoundException {
fos = new FileOutputStream("path/subFolder/WordDocWithImage.docx");
return fos;
}
Note: I have tried the code.

How can i edit pdf and put it inside zip during stream then download using IText and java?

My use case is this: when the client clicks download on a pdf, I want to edit/write some text on to the pdf using Itext pdf editor, then zip the pdf then let it download, All during the stream. I am aware of memory issue if the pdf is large etc. which won't be an issue since its like 20-50kb. I have the zipping during the stream before downloading working using byte array, now have to make the pdfeditor method also run before zipping, add some text then let the download happen.
Here is my code so far:
public class zipfolder {
public static void main(String[] args) {
try {
System.out.println("opening connection");
URL url = new URL("http://gitlab.itextsupport.com/itext/sandbox/raw/master/resources/pdfs/form.pdf");
InputStream in = url.openStream();
// FileOutputStream fos = new FileOutputStream(new
// File("enwiki.png"));
PdfEditor writepdf = new PdfEditor();
writepdf.manipulatePdf(url, dest, "field"); /// where i belive i
/// should execute the
/// editor function ?
File f = new File("test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
zos.putNextEntry(entry);
System.out.println("reading from resource and writing to file...");
int length = -1;
byte[] buffer = new byte[1024];// buffer for portion of data from
// connection
while ((length = in.read(buffer)) > -1) {
zos.write(buffer, 0, length);
}
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
}
}
public class PdfEditor {
public String insertFields (String field, String value) {
return field + " " + value;
// System.out.println("does this work :" + field);
}
// public static final String SRC = "src/resources/source.pdf";
// public static final String DEST = "src/resources/Destination.pdf";
//
// public static void main(String[] args) throws DocumentException,
// IOException {
// File file = new File(DEST);
// file.getParentFile().mkdirs();
// }
public String manipulatePdf(URL src, String dest, String field) throws Exception {
System.out.println("test");
try {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return field;
}
}
So playing with ByteArrayOutputStream, finally got it work. passing the input stream to 'manipulatepdf' and returning 'bytedata'.
public ByteArrayOutputStream manipulatePdf(InputStream in, String field) throws Exception {
System.out.println("pdfediter got hit");
ByteArrayOutputStream bytedata = new ByteArrayOutputStream();
try {
PdfReader reader = new PdfReader(in);
PdfStamper stamper = new PdfStamper(reader, bytedata);
AcroFields form = stamper.getAcroFields();
Item item = form.getFieldItem("Name");
PdfDictionary widget = item.getWidget(0);
PdfArray rect = widget.getAsArray(PdfName.RECT);
rect.set(2, new PdfNumber(rect.getAsNumber(2).floatValue() + 20f));
String value = field;
form.setField("Name", value);
form.setField("Company", value);
stamper.close();
} catch (Exception e) {
System.out.println("Error in manipulate");
System.out.println(e.getMessage());
throw e;
}
return bytedata;
}
public String editandzip (String data, String Link) {
try {
System.out.println("opening connection");
URL url = new URL(Link);
InputStream in = url.openStream();
System.out.println("in : "+ url);
//String data = "working ok with main";
PdfEditor writetopdf = new PdfEditor();
ByteArrayOutputStream bao = writetopdf.manipulatePdf(in, data);
byte[] ba = bao.toByteArray();
File f = new File("C:/Users/JayAcer/workspace/test/test.zip");
ZipOutputStream zos = new ZipOutputStream(new FileOutputStream(f));
ZipEntry entry = new ZipEntry("newform.pdf");
entry.setSize(ba.length);
zos.putNextEntry(entry);
zos.write(ba);
zos.close();
in.close();
System.out.println("File downloaded");
} catch (Exception e) {
System.out.println("Error");
e.printStackTrace();
}
return data;
}
}

Read and Write text file from my own class in Android Studio

I have been trying to create a class called TextFileReaderWriter I want to use the getters and setters to read and write to a text file in such a way that I can call the class and the method from anywhere in the program by simply using setfileContents(somestring) and somestring = getfileContents() something like this
example:
TextFileReaderWriter trw = new TextFileReaderWriter();
trw.setfileContents(somestring); //this would write 'somestring' to the text file.
String somestring = trw.getfileContents(); //this would return 'somestring' from the text file.
Here's what I have so far but it writes nothing to the file:
public class TextFileReaderWriter extends Activity{
String fileContents;
Context context;
String TAG = "MYTAG";
public TextFileReaderWriter(String fileContents, Context context) {
this.fileContents = fileContents;
this.context = context;
}
public String getFileContents() {
return fileContents;
}
public void setFileContents(String fileContents) {
this.fileContents = fileContents;
FileOutputStream fos = null;
try {
fos = context.openFileOutput("UserInputStore", Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
OutputStreamWriter osw = new OutputStreamWriter(fos);
try {
osw.write(fileContents);
Log.d(TAG, fileContents);
} catch (IOException e) {
e.printStackTrace();
}
}
}
You don't need the OutputStreamWriter--FileOutputStreamwill do the trick just fine.
//what you had before
FileOutputStream fos = null;
try {
fos = context.openFileOutput(filename, Context.MODE_PRIVATE);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
//use just the file output stream to write the data
//data here is a String
if (fos != null) {
try {
fos.write(data.getBytes());
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
Method to save data on disk :
protected static void saveDataOnDisk(String data) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
ObjectOutput objectOutput = new ObjectOutputStream(byteArrayOutputStream);
objectOutput.writeObject(data);
byte[] buffer = byteArrayOutputStream.toByteArray();
File loginDataFile = (new File(filePath)); // file path where you want to write your data
loginDataFile.createNewFile();
FileOutputStream fileOutputStream = new FileOutputStream(loginDataFile);
fileOutputStream.write(buffer);
fileOutputStream.close();
objectOutput.flush();
objectOutput.close();
byteArrayOutputStream.flush();
byteArrayOutputStream.close();
Log.i(“SAVE”, ”———————-DONE SAVING”);
} catch(IOException ioe) {
Log.i(“SAVE”, “———serializeObject|”+ioe);
}
}
Method to fetch data from disk:
private static Object getDataFromDisk() {
try {
FileInputStream fileInputeStream = new FileInputStream(FilePath);
ObjectInputStream objectInputStream = new ObjectInputStream(fileInputeStream);
Object data = (Object) objectInputStream.readObject();
objectInputStream.close();
fileInputeStream.close();
return dataModel;
} catch (Exception error) {
Log.i(“FETCH”, ”—-getDataFromDisk———ERROR while reading|” + error);
}
return null;
}

How to close and delete file in Java

I have written code that should be saved file in the local directory, create zip of that file, send email and delete both files (original and zip), So this is my code:
Method wich send email
public void sendEmail(Properties emailProperties, InputStream inputStream, HttpServletRequest request) throws UnsupportedEncodingException {
MimeMessage mimeMessage = mailSender.createMimeMessage();
try {
MimeMessageHelper mimeMessageHelper = new MimeMessageHelper(mimeMessage, true);
try {
mimeMessageHelper.setFrom(from, personal);
} catch (UnsupportedEncodingException e) {
LOGGER.error(e.getMessage());
throw new SequelException(e.getMessage());
}
mimeMessageHelper.setTo(recipients);
mimeMessageHelper.setSubject(emailProperties.getProperty(PARAM_TITLE));
String message = emailProperties.getProperty(PARAM_EMLMSG);
mimeMessageHelper.setText(message);
InputStreamSource inputStreamSource = null;
if (inputStream != null) {
inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(inputStream));
}
String compressType = COMPRESS_TYPE_ZIP;
String fileName = getAttachFilenameExtension(object, format);
Path filePath = Paths.get(StrUtils.getProperty("temp.email.files.path") + "\\" + fileName);
tempFile = saveTempFile(inputStreamSource.getInputStream(), filePath);
if (tempFile.length() > 0) {
inputStreamSource = compressFile(tempFile, filePath.toString(), compressType);
fileName = StringUtils.substring(fileName, 0, StringUtils.lastIndexOf(fileName, ".")+1) + compressType;
}
mimeMessageHelper.addAttachment(fileName, inputStreamSource);
mailSender.send(mimeMessage);
} catch (MessagingException | IOException e) {
LOGGER.error(e.getMessage());
throw new SequelException(e.getMessage());
} finally {
List<File> files = (List<File>) FileUtils.listFiles(tempFile.getParentFile(), new WildcardFileFilter(
FilenameUtils.removeExtension(tempFile.getName()) + "*"), null);
for (File file : files) {
try {
FileUtils.forceDelete(file);
} catch (IOException e) {
LOGGER.error(e.getMessage());
}
}
}
}
Save file in directory:
private File saveTempFile(InputStream inputStream, Path filePath) throws IOException {
Files.deleteIfExists(filePath);
Files.copy(inputStream, filePath);
return new File(filePath.toString());
}
Compress file:
private InputStreamSource compressFile(File file, String filePath, String compressType) throws IOException {
InputStream is = ZipFile(file, filePath);
InputStreamSource inputStreamSource = new ByteArrayResource(IOUtils.toByteArray(is));
return inputStreamSource;
}
public InputStream ZipFile(File file, String filePath) {
String zipArchiveFileName = StringUtils.substring(filePath, 0, filePath.lastIndexOf(".") + 1) + COMPRESS_TYPE_ZIP;
try (ZipArchiveOutputStream zipOutput = new ZipArchiveOutputStream(new File(zipArchiveFileName));) {
ZipArchiveEntry entry = new ZipArchiveEntry(StringUtils.overlay(file.getName(), "",
StringUtils.lastIndexOf(file.getName(), "_"), StringUtils.lastIndexOf(file.getName(), ".")));
zipOutput.putArchiveEntry(entry);
try (FileInputStream in = new FileInputStream(file);) {
byte[] b = new byte[1024];
int count = 0;
while ((count = in.read(b)) > 0) {
zipOutput.write(b, 0, count);
}
zipOutput.closeArchiveEntry();
}
InputStream is = new FileInputStream(zipArchiveFileName);
return is;
} catch (IOException e) {
LOGGER.error("An error occurred while trying to compress file to zip", e);
throw new SequelException(e.getMessage());
}
}
So the problem is when I try to delete files but zip file does not delete.
I am using Apache commons compress for zipping.
Can you help what's wrong?
For me this code is working perfectly. After compressing you may be trying to delete it without the extension(for eg .7z here).
public static void main(String[] args) {
File file = new File("C:\\Users\\kh1784\\Desktop\\Remote.7z");
file.delete();
if(!file.exists())
System.out.println("Sucessfully deleted the file");
}
Output:-
Sucessfully deleted the file

Categories