I never worked with postscript before... And I need to replace a tool that:
Converts a string to postscript
Generates a pdf file based on a postscript file (done)
My issue is: I have no idea how to achieve step 1. By the way, I would preferably do in a similar way to the one I did on step (2).
I was wondering if I can just replace the parameters, but how? Could you please assist me?
The code to item (2) is below:
public byte[] convertPostScriptToPDF() throws IOException {
//get Ghostscript instance
Ghostscript gs = Ghostscript.getInstance();
File file= new File (this.getClass().getResource( "/resources/employer_report_last_page2.ps").getFile());//(Config.EMP_REPORT.REPORT_LAST_PAGE_STORE_PATH);
File pdfGenerated = File.createTempFile("output", "pdf");
System.out.println("Path for temp file -> " + pdfGenerated.getAbsolutePath());
//prepare Ghostscript interpreter parameters
//refer to Ghostscript documentation for parameter usage
String[] gsArgs = new String[10];
gsArgs[0] = "-ps2pdf";
gsArgs[1] = "-dNOPAUSE";
gsArgs[2] = "-dBATCH";
gsArgs[3] = "-dSAFER";
gsArgs[4] = "-sDEVICE=pdfwrite";
// gsArgs[5] = "-sOutputFile=output2.pdf";//output file name
gsArgs[5] = "-sOutputFile=" + pdfGenerated.getAbsolutePath();
// gsArgs[5] = "-sOutputFile=" + file.getAbsolutePath();
gsArgs[6] = "-c";
gsArgs[7] = ".setpdfwrite";
gsArgs[8] = "-f";
// gsArgs[9] = "input.ps";//input file name
gsArgs[9] = file.getAbsolutePath();//input file name
//execute and exit interpreter
try {
gs.initialize(gsArgs);
gs.exit();
} catch (GhostscriptException e) {
System.out.println("ERROR: " + e.getMessage());
}
FileInputStream fis = new FileInputStream(pdfGenerated);
return IOUtils.toByteArray(fis);
}
Thank you in advance!
I got no solution, so I realized I could try a workaround...
I changed the application logic. At the end it would convert everything to pdf, so instead of :
convert string to ps
add ps content other ps
convert ps to string
I did:
onvertd string to pdf
convert ps to pdf
merged both using the PDFMergerUtility
Related
I have a Java method that takes byte array and String value as arguments and returns a File object. This is the code
public File createTempFile(byte[] byteArray, String fileName) throws IOException {
String prefix = FilenameUtils.getBaseName(fileName);
String suffix = getMimeType(byteArray);
File tempFile = File.createTempFile(prefix, suffix, null);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(tempFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
fos.write(byteArray);
fos.close();
return tempFile;
}
When I try to run it like this
File myFile = tiedostoService.createTempFile(tiedosto.getContent(), attachment.getFileName());
I get an IOException like this
java.io.IOException: Unable to create temporary file, C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
at java.io.File$TempDirectory.generateFile(File.java:1921)
at java.io.File.createTempFile(File.java:2010)
From the stacktrace. it can be seen that it's trying to create a file like C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image\png
and not C:\Users\ROSHAN~1\AppData\Local\Temp\kuva1068864619970584773image.png
How can I fix this? I'd really appreciate any sort of help.
'image/png' is a Mime Type. See all MimeTypes in java here
Write a util which converts mimetype to file extension. Hopefully this will help.
I think there is an extra \ in your suffix string, could you try debug and see the actual value of the suffix?
I tried to run:
String suffix = "\\png";
and got the same error, but if I do
String suffix = ".png";
no error creating the temp file, notice that you need to add a dot in the suffix...
I tried to create 3 empty files in my home directory, using this:
this.mainpath = System.getenv("HOME"+"/");
this.single = new File(mainpath + "sin.r");
this.complete = new File (mainpath + "com.r");
this.ward = new File (mainpath+"w.r");
I was unter the impression that this would give me the files desired. However, if I search my home directory, or any other directory, for this files, none of them exists. What am I doing wrong?
Edit: I just find out: I do get a file, but not in my home directory, but the path to it would be /home/myname/NetBeansProjects/myorojectname/nullsin.r.
However, I specifically wanted to create the file in my home!
Well, my code now reads:
this.mainpath = System.getenv("user.home");
this.mainpath = this.mainpath + "/";
this.single = new File(mainpath + "sin.r");
this.single.createNewFile();
System.out.println(this.single.getAbsolutePath());
this.complete = new File (mainpath + "comp.r");
this.complete.createNewFile();
this.ward = new File (mainpath+"w.r");
this.ward.createNewFile();
The "success" of this, however, is that I get an IOException at the first createNeWFile(): File not found.
as for my code how I tried to write sth into those file, there it is:
FileWriter writer1 = null;
FileWriter writer2 = null;
FileWriter writer3 = null;
try {
writer1 = new FileWriter(single);
writer2 = new FileWriter(complete);
writer3 = new FileWriter(ward);
writer1.write("x = cbind(1,2,3)");
writer2.write("x = cbind(1,2,3)");
writer3.write("x = cbind(1,2,3)");
writer1.flush();
writer2.flush();
writer3.flush();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
} finally {
try {
writer1.close();
writer2.close();
writer3.close();
} catch (IOException ex) {
System.out.println(ex.getStackTrace());
}
You need to use getProperty() instead
System.getProperty("user.home");
Also, the / should be appended after getting the directory path.
this.mainpath = System.getProperty("user.home");
this.single = new File(mainpath + "/sin.r");
this.complete = new File (mainpath + "/com.r");
this.ward = new File (mainpath+"/w.r");
You can call the "createNewFile"-method for each of the objects you've declared to actually create them.
I'm making a fairly basic site for my mother, and seeing as I did some stuff in Java EE and with EJB during college last semester, I'm going to stick to this.
The only issue I am having is uploading images - I can't seem to find any examples.
I'm using entity classes and parameterised queries. This is the code for writing to the database, which is working fine, I'm just setting the blob image value to null for the moment.
#Override
public void addClothes(String designer, String cname, String ctype, String desc) {
Clothes c = new Clothes();
em.persist(c);
c.setDesigner(designer);
c.setCname(cname);
c.setCtype(ctype);
c.setDescript(desc);
c.setImage(null);
}
I have a servlet that takes a file, I'm just not sure how the file, when passed, should be sorted and what I should write to the database (from what I'm seeing, it's byte[])
A hand in the right direction would be appreciated!
Once you have the file on the server, either in memory or in a local or temp file (that depends on the framework or libraries that you're using), you will have a reference of a wrapper type.
If you are using Apache Commons File Upload, you have a FileItem reference. For request all contents of the file as byte array:
byte[] contents = fileItem.get();
If you are using Tomahawk of Trinidad, you have a org.apache.myfaces.trinidad.model.UploadedFile reference. For request all contents of the file as byte array, you can use class IOUtils of the Apache Commons IO:
byte[] contents = IOUtils.toByteArray(uploadedFile.getInputStream());
Of if you have a reference of org.apache.myfaces.custom.fileupload.UploadedFile, is more simple:
byte[] contents = uploadedFile.getBytes();
UPDATE
If you are using Java EE 6, you can use new features of Server 3.0 specification for upload files without extra libraries. See the excellent tutorial of BalusC in The BalusC Code: Uploading files in Servlet 3.0
To work with hibernatehttp://www.mkyong.com/hibernate/hibernate-save-image-into-database/
To work with JDBC:
To Write image into database BLOB using Jdbc , You need to Convert the File into Inputstream. statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length())); PreparedStatement statement offer method setBinaryStream() which is used to write binary stream into database BLOB column.
Here is a code snippet to help you:
File image = new File("C:/test.jpg");
inputStream = new FileInputStream(image);
Prepared statement = //define as per your table
// set the file binary stream
statement.setBinaryStream(2, (InputStream) inputStream,(int) (image.length()));
statement.executeUpdate();
In your Clothes class, you can add:
#Lob
private byte[] image;
// Getter/Setter methods
Got it working ! Somewhat, with this code:
public void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
out = response.getWriter();
final String path = "clothesImages" + File.separator + request.getParameter("designer") + File.separator + request.getParameter("ctype") + File.separator + request.getParameter("cname");
out.println(path);
String currentDir = new File(".").getAbsolutePath();
out.println(currentDir);
final Part filePart = request.getPart("image");
final String filename = "image.jpg";
File file = new File(path);
if (!file.exists()){
out.println("Dir Doesn't Exist");
file.mkdirs();
}
OutputStream outstream = null;
InputStream filestream = null;
try{
outstream = new FileOutputStream(new File(path + File.separator + filename));
filestream = filePart.getInputStream();
int read = 0;
final byte[] bytes = new byte[1024];
while(( read = filestream.read(bytes)) != -1){
outstream.write(bytes, 0, read);
}
out.println("New file " + filename + " created at " + path);
}catch (FileNotFoundException fne) {
out.println("You either did not specify a file to upload or are "
+ "trying to upload a file to a protected or nonexistent "
+ "location.");
out.println("<br/> ERROR: " + fne.getMessage());
}finally {
if (out != null) {
out.close();
}
if (filestream != null) {
filestream.close();
}
if (outstream != null) {
outstream.close();
}
}
}
The only issue I have is setting the file path. The path is
C:\Users\Chris\AppData\Roaming\NetBeans\7.2.1\config\GF3\domain1\
But I want it to save in
Project-war/web/images
Any ideas?
I have a file which is needed for running tests - this file needs to be personalized (name and password) by whomever is running the test. I do not want to store this file in Eclipse (since it would need to be changed by whomever runs the test; also it would be storing personal info in the repo), so I have it in my home folder (/home/conrad/ssl.properties). How can I point my program to this file?
I've tried:
InputStream sslConfigStream = MyClass.class
.getClassLoader()
.getResourceAsStream("/home/" + name + "/ssl.properties");
I've also tried:
MyClass.class.getClassLoader();
InputStream sslConfigStream = ClassLoader
.getSystemResourceAsStream("/home/" + name + "/ssl.properties");
Both of these give me a RuntimeException because the sslConfigStream is null. Any help is appreciated!
Use a FileInputStream to read data from a file. The constructor takes a string path (or a File object, which encapsulates string path).
Note 1: A "resource" is a file which is in the classpath (alongside your java/class files). Since you don't want to store your file as a resource because you don't want it in your repo, ClassLoader.getSystemResourceAsStream() is not what you want.
Note 2: You should use a cross-platform way of getting a file in a home directory, as follows:
File homeDir = new File(System.getProperty("user.home"));
File propertiesFile = new File(homeDir, "ssl.properties");
InputStream sslConfigStream = new FileInputStream("/home/" + name + "/ssl.properties")
You can simplify your work, using Java's 7 method:
public static void main(String[] args) {
String fileName = "/path/to/your/file/ssl.properties";
try {
List<String> lines = Files.readAllLines(Paths.get(fileName),
Charset.defaultCharset());
for (String line : lines) {
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
}
You can also improve your way of reading properties file, using Properties class and forget about reading and parsing your .properties file:
http://www.mkyong.com/java/java-properties-file-examples/
Is this a graphics program (ie. using the Swing library)? If so it is a pretty simple task of using a JFileChooser.
http://docs.oracle.com/javase/6/docs/api/javax/swing/JFileChooser.html
JFileChooser f = new JFileChooser();
int rval = f.showOpenDialog(this);
if (rval == JFileChooser.APPROVE_OPTION) {
// Do something with file called f
}
You can also use Scanner to read the file.
String fileContent = "";
try {
Scanner scan = new Scanner(
new File( System.getProperty("user.home")+"/ssl.properties" ));
while(scan.hasNextLine()) {
fileContent += scan.nextLine();
}
scan.close();
} catch(FileNotFoundException e) {
}
I have this problem: I am choosing a file from JFileChooser and if i take a system print i get this path: C:\Users\Joakim\Desktop\dude.txt and when i want to use this link to copy this file to another location i need to have the path like this: C://Users/Joakim/Desktop/dude.txt
How can i do this?
public void upload(String username) throws RemoteException, NullPointerException{
JFileChooser chooser = new JFileChooser(getProperty + "/desktop/");
int returnVal = chooser.showOpenDialog(parent);
if (returnVal == JFileChooser.APPROVE_OPTION) {
System.out.println("You chose to open this file: " + chooser.getSelectedFile().getName());
} try {
String fileName = chooser.getSelectedFile().getName();
System.out.println(fileName); //name of the file
File selectedFile = chooser.getSelectedFile();
System.out.println(selectedFile); //path of the file
//File path= selectedFile.replaceAll('/','/');
String serverDirectory = ("C://Users/Joakim/Dropbox/Project RMI/SERVER/");
byte[] filedata = cf.downloadFile(selectedFile);
BufferedOutputStream output = new BufferedOutputStream(new FileOutputStream(serverDirectory + fileName));
output.write(filedata, 0, filedata.length);
output.flush();
output.close();
} catch (Exception e) {
System.err.println("FileServer exception: " + e.getMessage());
e.printStackTrace();
}
}
Thanks in Advance :)
Edit: So this did not work out as i planed. I wanted to change the path to C://Users/Joakim/Desktop/dude.txt but thats not enough. I need to have //C://Users/Joakim/Desktop/dude.txt. The problem i have now is to get that and still use it as a File. I did test out
File newFil = new File("//" + selectedFile);
byte[] filedata = cf.downloadFile(nyFil);
This do not work for me. I still get out C://Users/Joakim/Desktop/dude.txt
Do someone have a tip or two? :)
You should really be using the system properties file.separator:
Character that separates components of a file path. This is "/" on
UNIX and "\" on Windows.
String fileSeparator = System.getProperty("file.separator");
You can also access the file separator as File.separator
Consider breaking up your path to incorporate the use of this property in lieu of forward or backward slashes.
It's simple, try this :
String first = "C:\\Mine\\Java";
String second = first.replace("\\", "/");
second = second.replaceFirst("/", "//");
System.out.println(second);
OUTPUT :
Hope this might help in some way.
Regards
This should work: C:\Users use double \
Try with this
/**
* Prepare dropbox path from the path.
*
* #param path
* that is to be formated.
* #return
* Return dropbox formated path.
*/
public static String createDropboxPathFormat(String path) {
// Replaced all \ with / of the path.
String dropboxPath = path.replaceAll("[\\\\]", "/");
// Finally replaced all // with /
dropboxPath = dropboxPath.replaceAll("[//]", "/");
return dropboxPath;
}