I need to write a Java program that opens a PDF file at a named destination. The file test.pdf contains the named destination "DestinationX" on page 2. The program opens the PDF file but does not go to the named destination. How do I get to the named destination?
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
public class MyLauncher {
static void openFileAtNamedDest(){
if (Desktop.isDesktopSupported()) {
try {
URI myURI = new URI("file:///C:/test.pdf#nameddest=DestinationX");
Desktop.getDesktop().browse( myURI );
} catch (IOException e) {
e.printStackTrace();
}
catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
openFileAtNamedDest();
}
}
According to the spec, the format of your URL is correct. The only question is what application you are actually launching via browse(). I think it acts the same way as if you had double-clicked the file's icon on your desktop: it will launch whatever application is registered as the default handler for PDFs.
Acrobat should be able to handle a URL with a named destination, but other PDF viewers may not support it.
Related
I am trying to convert the image to a searchable pdf using tesseract. The below command line option working fine for me.
Exploring a similar option in java. But not sure what to pass in the arguments. Below is my java code
import java.io.File;
import java.util.Arrays;
import java.util.List;
import net.sf.saxon.expr.instruct.ValueOf;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
public class Mask2 {
public static void main(String[] args) {
File image = new File("D:\\ML\\Java\\img3.PNG");
Tesseract tesseract = new Tesseract();
tesseract.setDatapath("C://Program Files//Tesseract-OCR//tessdata");
tesseract.setLanguage("eng");
tesseract.setPageSegMode(1);
tesseract.setOcrEngineMode(1);
try {
// Not sure what to pass in arguments
tesseract.createDocumentsWithResults()
} catch (TesseractException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Any Suggestions / Solutions would be much helpful.
you can create a list of renderFormats like this ( you can add others)
List<RenderedFormat> renderFormats = new ArrayList<RenderedFormat>();
renderFormats.add(RenderedFormat.PDF);
and then you can pass the path of the input filename (PDF or IMG), the path of the output filename with no extension, and the render format you want to use.
tesseract.createDocuments("a/b/c/inputfile.PNG", "a/b/c/outputfile", renderFormats);
Ciao!
I want to include a font as a resource file in my deployed application.
To use it in swing, I know that I can import a font like this:
InputStream is_regular = Resources.class.getResourceAsStream("Lato-Regular.ttf");
Font regular_font = Font.createFont(Font.TRUETYPE_FONT, is_regular);
But how can I register also the bold variant, which is stored in a file called "Lato-Bold.ttf"?
I also know that I can access the variant weights via the attributes field. But how do I register these?
The Lato Font comes in 18 different variants such as light, semibold, hairline, etc.
You write a FontManager. The solution to almost any Java problem is either a manager or a factory. Sometimes you need a manager-factory.
One way would be like this.
package com.ggl.testing;
import java.awt.Font;
import java.awt.FontFormatException;
import java.io.IOException;
import java.io.InputStream;
import javax.annotation.Resources;
public class FontManager {
public static Font getNormalFont() {
return getFont("Lato-Regular.ttf");
}
public static Font getBoldFont() {
return getFont("Lato-Bold.ttf");
}
private static Font getFont(String fontFileName) {
InputStream is = Resources.class.getResourceAsStream(fontFileName);
try {
return Font.createFont(Font.TRUETYPE_FONT, is);
} catch (FontFormatException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
You write a getter method for the 18 variations of your font.
The return null at the end of the getFont method can be changed to return a standard font.
If you want to deploy the fonts with your application, you need to copy the font files into a resource folder in your application. You add the application resource folder to your Java build path (classpath). This line in the code would change to
InputStream is = getClass().getResourceAsStream("/" + fontFileName);
I am try to open a javadoc html file with my new application, however I can not get the javadoc file to open, I have a class name OpenUri, which when called is supposed to open the javadoc:
package gui;
import java.awt.Desktop;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import javax.swing.JFrame;
public class OpenUri extends JFrame {
public static void openWebpage(URI uri) {
Desktop desktop = Desktop.isDesktopSupported() ? Desktop.getDesktop() : null;
if (desktop != null && desktop.isSupported(Desktop.Action.BROWSE)) {
try {
desktop.browse(uri);
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void openWebpage(URL url) {
try {
openWebpage(url.toURI());
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
}
I am then calling and using this class from another class called Menu, where the help button has an action listener, etc. However when I run the code and press the help button, no javadoc appears, ie, it doesn't open the document, ie, nothing happens, no window, nothing ?
The only way I can open it is manually, by clicking on it in eclipse, here is the specific code from the Menu class I am Using:
//Help
JMenu helpMenu = new JMenu("Help");
helpMenu.setMnemonic(KeyEvent.VK_H);
helpMenu.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent event) {
try {
URI uri = new URI("file:///C:/Users/howhowhows/workspace/OPTICS_DROP_MENU/doc/index.html");
OpenUri.openWebpage(uri);
} catch (URISyntaxException e) {
e.printStackTrace();
}
}
});
If anyone has any ideas as to what I am doing wrong, ie what I need to add/change, it would be greatly appreciated.
Have you downloaded and tried the demo code from the Swing tutorial on How to Integrate With the Desktop Class.
When I used that code and pasted your URI into the text field no window is displayed and I get a "System cannot find the file" message as expected.
When I then enter a simple URI that I know exists: "c:/java/a.html" the browser opens as expected.
So I suggest you start with known working code and see if your URI works. If it does work then the problem is your code, so compare the working code to your code to see what the difference is. If it doesn't work then the problem is the URI.
If you still have problems then post a proper SSCCE that demonstrates the problem. Given that your OPenURI class extends JFrame for no reason we don't know what other strange things you might be doing in your code.
I am getting a stream of data from a server (in binary format). This data is serialised using Google protocol buffers. I'm attempting to do a daily rollover (i.e. if next day occurs write to new file containing the new Date with the compressed data inside).
I've attempted to do this via log4j, however, log4j doesn't account for binary (as far as I know I can only get text via it). When log4j writes the files, it doesn't write them in binary, but in text (human readable) format.
I went over this question to create a custom binary appender in log4j How to Create Binary Log File in Java using Log4J
However, I only started with log4j a couple of days ago and I'm not too sure how to go about doing this.
Is there any other way to do the rollover for binary data? I'm not even sure if log4j is the best solution. I'm more than happy to try any solution you can come up with!
I want log4j to write the data in Binary not Text.
Is there any way to do a daily rollover for binary files in java?
I don't think log4j is necessary here. If you need just file rollover small stream wrapper would be enough.
Jetty project has implementation of such FileOuputStream in it's util classes RolloverFileRotator which I think fits perfectly here.
You can extend the default log4j DailyRollingFileAppender and include it in your classpath
package test.com;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.log4j.DailyRollingFileAppender;
import org.apache.log4j.spi.LoggingEvent;
public class BinaryRollingFileAppender extends DailyRollingFileAppender {
FileOutputStream fout;
public BinaryRollingFileAppender(){
}
#Override
public void setFile(String file) {
super.setFile(file);
try {
fout = new FileOutputStream(file);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
#Override
public void append(LoggingEvent le) {
try {
fout.write((byte[])le.getMessage());
} catch (Exception ex) {
ex.printStackTrace();
}
}
#Override
public boolean requiresLayout() {
return false;
}
#Override
public void close() {
try {
fout.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
}
then configure the appender via log4j properties file
log4j.appender.app=test.com.BinaryRollingFileAppender
log4j.appender.app.File=/tmp/binary.bin
log4j.appender.app.DatePattern='.'yyyy-MM-dd
log4j.logger.app.com=DEBUG, app
and test it
package test.com;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import org.apache.log4j.Logger;
public class TestBinary {
private static final Logger LOGGER = Logger.getLogger(TestBinary.class);
public static void main(String[] args) {
Path path = Paths.get("c://tmp/binary-example-file.bin");
try {
LOGGER.debug(Files.readAllBytes(path));
} catch (Exception e) {
e.printStackTrace();
}
}
}
I don't know if this is what you want, but is a good start point, hope this helps you.
You can use RotatingFileOutputStream with DailyRotationPolicy provided by rotating-fos Java library.
I am working on a concept of a filesystem for a program. I am writing in Java (using JDK 7 u17).
To get started I built off of some tutorial that were showing my how to create a zip based filesystem using the FileSystemProvider class.
When I execute the code I have it do similar task to the examples which is copy a text file from the my desktop and place it in the zip file. The problem is once it copies the file it does not write it into the zip file, it seems to leave the file in memory which is destroyed when the program is terminated.
The problem is I cannot understand why, as far as I can tell everything looks to be in order but something is clearly not!
Oh yeah the same thing goes for directories too. If I tell the filesystem to make a new directory it just creates it in memory and there is nothing in the zip file.
Anyhow here is my working code;
import java.io.IOException;
import java.net.URI;
import java.nio.file.FileSystem;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.HashMap;
import java.util.Map;
public class Start {
public static void main(String[] args) {
Map <String, String> env = new HashMap<>();
env.put("create", "true");
env.put("encoding", "UTF-8");
FileSystem fs = null;
try {
fs = FileSystems.newFileSystem(URI.create("jar:file:/Users/Ian/Desktop/test.zip"), env);
} catch (IOException e) {
e.printStackTrace();
}
Path externalTxtFile = Paths.get("/Users/Ian/Desktop/example.txt");
Path pathInZipFile = fs.getPath("/example.txt");
try {
Files.createDirectory(fs.getPath("/SomeDirectory"));
} catch (IOException e) {
e.printStackTrace();
}
if (Files.exists(fs.getPath("/SomeDirectory"))) {
System.out.println("Yes the directory exists in memory.");
} else {
System.out.println("What directory?");
}
// Why is the file only being copied into memory and not written out the jar/zip archive?
try {
Files.copy(externalTxtFile, pathInZipFile);
} catch (IOException e) {
e.printStackTrace();
}
// The file clearly exists just before the program ends, what is going on?
if (Files.exists(fs.getPath("/example.txt"))) {
System.out.println("Yes the file has been copied into memory.");
} else {
System.out.println("What file?");
}
}
}
I just want to add something.
Perhaps the example that you found was incomplete (I can not check since you do not references it) but in all examples I found the FileSystem instance is closed properly.
The FileSystem abstract class implements Closeable, so the close() method is called (automatically) leaving the try in the following code:
try (final FileSystem fs = FileSystems.newFileSystem(theUri, env)) {
/* ... do everything you want here ; do not need to call fs.close() ... */
}
http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html