Using iText to open PDF documents after writing to them - java

Im using iText and the Document class in a JFrame to write PDFs but if i try to use the Runtime class to run it after creation i get an exception that i cant open it due to the locks still on it and if i run Unlocker on it, my JFrame has a lock token on it. How do i open the PDF if i want to write to it?
Document d = new Document();
.... code
d.close();
Runtime.getRuntime().exec("D:/PDFChartStuff.pdf");
Why does this post not meet stackoverflow's "quality standards"?

If you are using windows you can use rundll32 to launch a pdf file.
Try something like this
String pdfFile="D:/PDFChartStuff.pdf";
if (pdfFile.toString().endsWith(".pdf")) {
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + pdfFile);
} else {
//For cross platform use
Desktop desktop = Desktop.getDesktop();
desktop.open(pdfFile);
}

Related

Is it possible to implement a command in CodenameOne that will display a PDF once a button is pressed without using a URL

I am trying to make a program using the CodenameOne plugin that will display various PDF's when buttons are pressed, but I can't find a way to do this without using a specific URL for each PDF. Is there any possible way to accomplish this by placing the PDF files into a package and calling them when needed? I would assume that I need to use an ActionListener but I really don't know what to do. This is what I have tried so far.
b1L1.addActionListener((e)->File file = new File("/path/to/file.pdf");
Desktop.getDesktop().open(file));
Desktop or other AWT related API's are unavailable. Even java.io.File doesn't make sense on Codename One due to mobile OS restrictions on file systems that java.io wasn't designed to handle see this for the long form explanation.
We have a sample that does exactly this taken from here:
Form hi = new Form("PDF Viewer", BoxLayout.y());
Button devGuide = new Button("Show PDF");
devGuide.addActionListener(e -> {
FileSystemStorage fs = FileSystemStorage.getInstance();
String fileName = fs.getAppHomePath() + "pdf-sample.pdf";
if(!fs.exists(fileName)) {
Util.downloadUrlToFile("http://www.polyu.edu.hk/iaee/files/pdf-sample.pdf", fileName, true);
}
Display.getInstance().execute(fileName);
});
hi.add(devGuide);
hi.show();

I can't import com.itextpdf.text.Document class

I'm building an android app and I want to use iText for creating pdf file, but I can't use Document class. As I seen in tutorials, there should be import com.itextpdf.text.Document for using Document class. For this app, I'm using com.itextpdf:itext-pdfa:5.5.9 library. I want to create a simple pdf file with 2 paragraphs, something like this:
try{
File pdfFolder = new File(Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_DOCUMENTS), "pdfdemo");
if (!pdfFolder.exists()) {
pdfFolder.mkdir();
}
Date date = new Date() ;
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(date);
File myFile = new File(pdfFolder + timeStamp + ".pdf");
OutputStream output = new FileOutputStream(myFile);
Document document = new Document();
PdfAWriter.getInstance(document, output);
document.open();
document.add(new Paragraph(mSubjectEditText.getText().toString()));
document.add(new Paragraph(mBodyEditText.getText().toString()));
document.close();
}catch (Exception e) {}
'
Could anyone help me with this problem? What am I doing wrong?
You say:
I'm using com.itextpdf:itext-pdfa:5.5.9 library
That is wrong for two reasons:
itext-pdfa is an addon to iText that is meant for writing or manipulating PDF/A documents. It requires the core iText libary. Read about the different parts of iText on the official web site: https://developers.itextpdf.com/itext-java
You say you want to use iText on Android, but you are referring to iText for Java. iText for Java contains classes that are not allowed on Android (java.awt.*, javax.nio,...). You should use the Android port for iText, which is called iTextG: https://developers.itextpdf.com/itextg-android
It's as if you're using iText without having visited the official iText web site. How is that even possible?
Just open your app level gradle file and add following code into your dependencies
implementation 'com.itextpdf:itext-pdfa:5.5.9'
It works for me

Open PDF File with Adobe Acrobat inside Java Application (via OLE)

I would like to open a PDF File inside an existing Java(SWT)-Application. The PDF should not opened in an external frame. I tried via the OLE interface but without success.
clientSite = new OleControlSite(frame, SWT.NONE, "AcroExch.App", fileName);
automation = new OleAutomation(clientSite);
clientSite.doVerb(OLE.OLEIVERB_OPEN);
you can use the IE Interface and then navigate to the PDF file.
Pseudocode:
$Obj = ObjCreate("Shell.Explorer.2")
$Obj.Navigate('D:\Test.pdf')
or the Reader Web Interface
Pseudocode:
$oReader = ObjCreate("AcroPDF.PDF.1")
$oReader.Load("D:\Test.pdf")
How you bind the object into your Java-GUI you may ask under java
HTH, Reinhard
PS: the "Shell.Explorer.2" option mostly works for me better.

How to Check A PDF reader Is Installed With Java

I Tried to open a pdf file using a statement
Runtime.getRuntime().exec("rundll32 url.dll,FileProtocolHandler " + "Sample.pdf");.
But I have not installed a pdf reader in my system. So it when I execute this program nothing is showing. No Exceptions are comming . Any idea getting the exception if the Pdf reader is not installed in the system. If the Pdf reader is already installed this program is working perfect.
EDIT
As my previous solution was not working . Here is another one that would sure work for you:
try
{
File file = new File("Sample.pdf");
java.awt.Desktop.getDeskTop().open(file);
System.out.println("File opened successfully");
}catch(Exception ex)
{
System.out.println("Error occurred: "+ex);
}
For that you have to deal with the register key.
Use JNI to do the trick.
String productName = Advapi32Util.registryGetStringValue(
WinReg.HKEY_LOCAL_MACHINE, "SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion", "ProductName");
System.out.printf("Product Name: %s\n", productName);
read/write to Windows Registry using Java

Do any Java OCR tools convert images of text into editable text files?

I'm working on a project that entails photographing text (from any hard copy of text) and converting that text into a text file. Then I'd like to use that text file to do some different things, such as provide hyperlinks to news articles or allow the user to edit the document.
The tool I've tried so far is Java OCR from sourceforge.net, which works fine on the images provided in the package. But when I photograph my own text, it doesnt work at all. Is there some training process I should be implementing? If so, does anybody know how to implement it? Any help will go a long way. Thank you!
I have a java application where I ended up deciding to use Tesseract OCR, and just call out to it using Runtime.exec(). Perhaps not quite the answer you need, but just in case you'd not considered it.
Edit + code added in response to comment reply
On a Windows installation I think I was able to use an installer, or unzip a ready made binary.
On a Linux server, I needed to compile Tesseract myself, but it's not too hard if you're used to that kind of thing (gcc); the only gotcha is that there's a dependency on Leptonica which also needs to be compiled.
// Tesseract can only handle .tif format, so we have to convert it
ImageIO.write( ImageIO.read( new java.io.File(file.getPath())), "tif", tmpFile[0]);
String[] tesseractCmd = new String[]{"tesseract", tmpFile[0].getAbsolutePath(), StringUtils.removeEnd(tmpFile[1].getAbsolutePath(), ".txt")};
final Process process = Runtime.getRuntime().exec(tesseractCmd);
try {
int exitValue = process.waitFor();
if(exitValue == 0) {
final String extractedText = SearchableTextExtractionUtils.extractPlainText(new FileReader(tmpFile[1]));
return extractedText;
}
throw new SearchableTextExtractionException(exitValue, Arrays.toString(tesseractCmd));
} catch (InterruptedException e) {
throw new SearchableTextExtractionException(e);
} finally {
process.destroy();
}

Categories