How to print PDF file in a Java application? - java

How do I print a PDF file from a Java application?

Here some source code that will allow you print any text file:
public void print() {
//The desktop api can help calling other applications in our machine
//and also many other features...
Desktop desktop = Desktop.getDesktop();
try {
//desktop.print(new File("DocXfile.docx"));
desktop.print(new File("Docfile.pdf"));
} catch (IOException e) {
e.printStackTrace();
}
}
Maybe it suit your needs since you did not give more details.

Try PDF Renderer. It's open source and there are a couple of examples on the site on how to render to a printer device.

I've used PDFBox before for a similar task like yours.
It's an excellent library from the Apache Software Foundation.
The class you are probably going to use is called: PDFTextStripper .
The javadoc for the class can be found here.

Related

How to execute Python codes from Java code in Android Studio?

I am building an Android application in Android studio with Java. I want to use Speech to text and Text to speech and some Machine Learning based python programs that I had already written.
Is it possible to do this? What is the technology stack that I need to accomplish this?
I came across various solutions like using sl4A, Jython, QPython and running the python code on the server.I have also gone through the following but I haven't found a solution yet
Execute python script from android App in Java
How to execute Python script from Java code in Android
Execute python script from android App in Java
Please explain with an example. As an example if I want to use the following python code (Speech to Text conversion using Google Speech recognition API) to run in my android app:
import speech_recognition as sr
r = sr.Recognizer()
with sr.Microphone() as src:
print("speak....")
audio = r.listen(src, 2)
print("over")
try:
print("you said: "+r.recognize_google(audio))
except:
print("cannot recognize")
What steps am I supposed to follow? What is the best way to achieve it?
Thank you in advance.
EDIT 1: Can it be achieved using azure services?
I've been using JEP as a bridge between java and python, I've never actually tried this on android apps, only webapps. (in the FAQS of the project they state that it could work)
private RunOutputModel run(RunInputModel model, String path) throws Exception {
RunOutputModel retVal = new RunOutputModel();
try (SharedInterpreter jep = new SharedInterpreter()) {
jep.eval("import sys");
jep.eval("sys.path.append('" + path + "')");
jep.eval("import master_main");
jep.set("well", model.getWell());
jep.set("startDate", model.getStartDate());
jep.set("endDate", model.getEndDate());
//other vars
jep.eval("objClass = master_main.master()");
jep.eval("x = objClass.main(path, well, startDate, endDate,/*vars*/)");
Object result1 = jep.getValue("x");
//manager result
}
} catch (Exception e) {
retVal.setStatus(e.getMessage());
Utils.log("error", e.getMessage(), path);
}
return retVal;
}
And here's python:
class master:
def __init__(self):
self.SETVARIABLES = ''
def main(self, path, well, startDate, endDate):
#stuff
By searching I've found this, they even have project examples of mixed source code app (both python and java).

Is it possible to interact with JavaPOS device using PHP POS in a simplistic manner?

We have a POS written in PHP which needs to interact with a POS printer. The printer support JavaPOS. The state of PHP POS is that it generates a bill and waits for a user to select a printer.
The issue now is, the JavaPOS printer doesn't show up. I am able to interact with using test Java code which has the necessary drivers & jpos.xml. I wish to 'install' this.
From my understanding for past four days going through JavaPOS manuals from different manufactures [EPSON, Starmicronics, Diebold Nixdorfag ], it is not possible. JavaPOS is meant for POS system written in Java [JavaFX to Spring].
But I find it very odd to believe this. I believe this shouldn't be the case because if this true, it would make very hard for POS not written in Java or .Net to interact with plethora of POS devices and terminal out there.
Hence, is it possible to interact with non Java & non .Net POS to send print command to JavaPOS device?
Please note, simply installing the device and sending a print command doesn't fix the issue. Say, if I want to add a logo to the receipt along with dynamic data in the footer of the receipt, Java code will be required for .Net to make it 'rich'. Now, where does this Java code specifically sit? Is it some virtual device which runs in the background and pretends to be a printer and shows up in the print dialog in a, say PHP POS?
Sample Java code written to interact with JavaPOS with jpos.xml file as reference.
public static void main(String[] args) {
File f = new File(PrintFTest.class.getClassLoader().getResource("jpos.xml").getPath());
System.setProperty(JposPropertiesConst.JPOS_POPULATOR_FILE_PROP_NAME, f.getAbsolutePath());
//System.getProperties().list(System.out);
FiscalPrinter fiscalPrinter = new FiscalPrinter();
// Get Access to it
try {
fiscalPrinter.open("printf");
fiscalPrinter.claim(1000);
fiscalPrinter.setDeviceEnabled(true);
} catch (JposException e) {
System.out.println("Exception at Access");
e.printStackTrace();
}
// Print
try {
fiscalPrinter.resetPrinter();
fiscalPrinter.beginFiscalReceipt(true);
fiscalPrinter.printRecItem("Salame", 40000, 0, 0, 0, "");
fiscalPrinter.printRecTotal(40000, 40000, "CONTANTI");
fiscalPrinter.endFiscalReceipt(false);
} catch (JposException e) {
System.out.println("Exception at Print");
}
try {
System.out.println("1FP - Fiscal Printer disabling");
fiscalPrinter.setDeviceEnabled(false);
System.out.println("2FP - Fiscal Printer releasing");
fiscalPrinter.release();
System.out.println("2FP - Fiscal Printer closing");
fiscalPrinter.close();
} catch (JposException e) {
System.out.println("Exception at Close");
}
}
}
It should contain the installation/setup/configuration method in the JavaPOS provided by each printer vendor and its user's manual.
Please install and configure equipment and software accordingly.
However, in general, JavaPOS printers are rarely recognized as standard printer devices for their respective operating systems.
For example, there is such an article.
Getting started with Java POS development
JavaPOS Working Group
Next, it is recommended that you use these programs to operate and verify the printer only in the Java environment.
emigonza/POStest
ntsggr/JavaPOS-POStest-2
There are several ways to use Java from PHP as follows.
PHP/Java Integration
Using PHP-Java Bridges with WebLogic Server
What is the PHP/Java Bridge?
How it works
Java Bridge
How to call custom java methods from PHP?
There is no problem if it can be solved by the above method, but I recommend the following method.
Combine the Java program and JavaPOS to create a program that runs standalone.
The program provides functions similar to POS processing units such as "receipt printing".
This program communicates with PHP's POS in a simple and light way such as a bare TCP/IP socket, so that request issuance, completion notification or completion confirmation can be performed asynchronously.
In Addition:
The following is an example of a POS application that is entirely made in Java.
Since these are open source, it seems to be a reference for programming.
However, it is unknown whether JavaPOS control is used or not.
Openbravo Java POS
Floreant POS
The following is an example of an open source POS application written in PHP.
Probably JavaPOS will not be used.
OpenSourcePOS
WallacePOS

Sqoop, export HDFS to MySQL in Java

I'm trying to export from HDFS into MySql and have only been able to find the following technique:
public static boolean exportHDFSToSQL() throws InstantiationException, IllegalAccessException, ClassNotFoundException {
try {
SqoopOptions options = new SqoopOptions();
options.setConnectString("jdbc:mysql://localhost:3306/dbName");
options.setUsername("user_name");
options.setPassword("pwd");
options.setExportDir("path of file to be exported from hdfs");
options.setTableName("table_name");
options.setInputFieldsTerminatedBy(',');
options.setNumMappers(1);
new ExportTool().run(options);
} catch (Exception e) {
return false;
}
return true;
}
The problem I have is with the ExportTool().run() method. I am using Sqoop 1.4.2 and this method has apparently been deprecated. Wanting to know the new way of achieving this? Or point me to a documented source that will assist.
Thanks
Sqoop currently do not exposes any Java API and thus such usage is not supported. It might work, however future versions might break this behavior.
I would expect that you see the deprecation because you are using ExportTool class from package com.cloudera.sqoop.tool, whereas the functionality was moved to package org.apache.sqoop.tool and the original instance was left there for backward compatibility. You can learn more about the namespace migration on appropriate Sqoop wiki page.

Java: load shared libraries with dependencies

I am wrapping a shared library (written in C) with Java using JNA. The shared library is written internally, but that library uses functions from another external library, which again depends another external library. So the situation is something like this:
ext1 <- ext2 <- internal
I.e. the internal uses external library ext2 which again uses external library ext1. What I have tried is:
System.loadLibrary("ext1");
System.loadLibrary("ext2");
NativeLIbrary.loadLibrary("internal",xxx.class);
This approach fails with "UnresolvedException" when loading the library "ext2"; the linker complains about symbols which are indeed present in the library "ext1". So it semmes that the System.loadLibrary() function does not make the symbols from "ext1" globally available? When using the stdlib function dlopen() as:
handle = dlopen( lib_name , RTLD_GLOBAL );
All the symbols found in #lib_name will be available for symbol resolution in subsequent loads; I guess what I would like was something similar for the java variety System.loadLibrary()?
Regards - Joakim Hove
It's an old question, but I've found an acceptable solution, which should also be portable, and I thought I should post an answer. The solution is to use JNA's NativeLibrary#getInstance(), because on Linux this will pass RTLD_GLOBAL to dlopen() (and on Windows this is not needed).
Now, if you are using this library to implement a Java native method, you will also need to call System.load() (or Sysem.loadLibrary()) on the same library, after calling NativeLibrary#getInstance().
First, a link to a JNA bug: JNA-61
A comment in there says that basically one should load dependencies before the actual library to use from within JNA, not the standard Java way. I'll just copy-paste my code, it's a typical scenario:
String libPath =
"/path/to/my/lib:" + // My library file
"/usr/local/lib:" + // Libraries lept and tesseract
System.getProperty("java.library.path");
System.setProperty("jna.library.path", libPath);
NativeLibrary.getInstance("lept");
NativeLibrary.getInstance("tesseract");
OcrTesseractInterf ocrInstance = (OcrTesseractInterf)
Native.loadLibrary(OcrTesseractInterf.JNA_LIBRARY_NAME, OcrTesseractInterf.class);
I've written a small library to provide OCR capability to my Java app using Tesseract. Tesseract dependes on Leptonica, so to use my library, I need to load libraries lept and tesseract first. Loading the libraries with the standard means (System.load() and System.loadLibrary()) doesn't do the trick, neither does setting properties jna.library.path or java.library.path. Obviously, JNA likes to load libraries its own way.
This works for me in Linux, I guess if one sets the proper library path, this should work in other OSs as well.
There is yet another solution for that. You can dlopen directly inside JNI code, like this:
void loadLibrary() {
if(handle == NULL) {
handle = dlopen("libname.so", RTLD_LAZY | RTLD_GLOBAL);
if (!handle) {
fprintf(stderr, "%s\n", dlerror());
exit(EXIT_FAILURE);
}
}
}
...
...
loadLibrary();
This way, you will open library with RTLD_GLOBAL.
You can find detailed description here: http://www.owsiak.org/?p=3640
OK;
I have found an acceptable solution in the end, but not without significant amount of hoops. What I do is
Use the normal JNA mechanism to map the dlopen() function from the dynamic linking library (libdl.so).
Use the dlopen() function mapped in with JNA to load external libraries "ext1" and "ext2" with the option RTLD_GLOBAL set.
It actually seems to work :-)
As described at http://www.owsiak.org/?p=3640, an easy but crude solution on Linux is to use LD_PRELOAD.
If that's not acceptable, then I'd recommend the answer by Oo.oO: dlopen the library with RTLD_GLOBAL within JNI code.
Try this, add this function to your code. Call it before you load your dlls. For the parameter, use the location of your dlls.
public boolean addDllLocationToPath(String dllLocation)
{
try
{
System.setProperty("java.library.path", System.getProperty("java.library.path") + ";" + dllLocation);
Field fieldSysPath = ClassLoader.class.getDeclaredField("sys_paths");
fieldSysPath.setAccessible(true);
fieldSysPath.set(null, null);
}
catch (Exception e)
{
System.err.println("Could not modify path");
return false;
}
return true;
}
}
In order to fix your issue you can use this package: https://github.com/victor-paltz/global-load-library. It loads the libraries directly with the RTLD_GLOBAL flag.
Here is an example:
import com.globalload.LibraryLoaderJNI;
public class HelloWorldJNI {
static {
// Loaded with RTLD_GLOBAL flag
try {
LibraryLoaderJNI.loadLibrary("/path/to/my_native_lib_A");
} catch (UnsatisfiedLinkError e) {
System.Println("Couldn't load my_native_lib_A");
System.Println(e.getMessage());
e.printStackTrace();
}
// Not loaded with RTLD_GLOBAL flag
try {
System.load("/path/to/my_native_lib_B");
} catch (UnsatisfiedLinkError e) {
System.Println("Couldn't load my_native_lib_B");
System.Println(e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
new HelloWorldJNI().sayHello();
}
private native void sayHello();
}
It is using the same dlopen() trick as the previous answers, but it is packaged in a standalone code.

Write a File in Phone Memory using J2ME

I have just downloaded the Samsung SDK 1.2 for Java Development.
Now, it's pure based J2ME architecture, so I have a requirement to store some files inside the memory for my application usage.
That file can have a .csv extension, so for that I have tried JSR 75's FileConnection class with following piece of code :
try {
FileConnection fconn = (FileConnection) Connector.open("file:///CFCard/newfile.txt");
if (!fconn.exists()) {
fconn.create(); // create the file if it doesn't exist
}
fconn.close();
} catch (IOException ioe) {
System.out.println("exception = "+ioe);
}
But in this case, it's giving me following exception :
exception = java.io.IOException: Root is not accessible
So, I don't exactly, I am on the right track or not..
Thanks in advance.
The roots available to you vary between devices. Read the JSR 75 documentation -- the method FileSystemRegistry.listRoots() will be of interest to you.
I'm not sure about that "CFCard". For example, on my phone, I think it would be "file:///E:/newfile.txt"
I'll try to do some research about this

Categories