PDF image rendering in java swing - java

I am using JPedal free version jar to render PDF in my java swing program. The normal PDF is getting rendered properly but while rendering the PDF image(Image file converted to PDF file) the quality drops considerably(not readable at all).
Example code :
public OpenViewer() {
//create and initialise JPedal viewer component
final Viewer myViewer =new Viewer();
myViewer.setupViewer();
//code to open when required
final File file=null; //example is commented out below
final InputStream stream = null;
//open the stream or File
try {
file = new File("/Users/markee/Desktop/myfile.pdf"); // This PDF is converted from tiff
} catch (Exception e) {
e.printStackTrace();
}
if(file!=null) {
myViewer.executeCommand(Commands.OPENFILE, new Object[]{file});
}
}

Related

How to convert FITS to JPG in Java?

I need to convert a fits file to jpg in java. I've tried with imageJ but I need a simple library without GUI. I'm developing a web page in java and I need to convert the file in background (headlessly).
Alex solved it by doing this:
public void fitsToJpg(String source, String destination, String image){
try {
ImagePlus imageP = openImage(source+image);
final File out = new File(destination+"preview.jpg");
BufferedImage imagen = imageP.getBufferedImage();
ImageIO.write(imagen, "jpg", out);
} catch (IOException ex) {
Logger.getLogger(Fits.class.getName()).log(Level.SEVERE, null, ex);
}
}

Create a PDF file using LaTex templates and Java

I need to create a report system using LaTex templates and Java like programming language. I use JLR library but it's freeeware, this is my code:
File workingDirectory = new File("./config/output");
File desktop = new File("./config/desktop");
File invoice1 = new File("./config/templates/template1.tex");
File invoice2 = new File("./config/templates/template2.tex");
JLRGenerator pdfGen = new JLRGenerator();
pdfGen.deleteTempTexFile(false);
if (!pdfGen.generate(invoice1, desktop, workingDirectory)) {
System.out.println(pdfGen.getErrorMessage());
}
JLROpener.open(pdfGen.getPDF());
if (!pdfGen.generate(invoice2, desktop, workingDirectory)) {
System.out.println(pdfGen.getErrorMessage());
}
JLROpener.open(pdfGen.getPDF());
Searching into the Web I find JLatexMath but, as far as I know, only generates equations in LaTex and not the entire PDF. Do you know a library in Java which generates an entire PDF file using a LaTex template?
Update: I execute de .tex file using Runtime.getRuntime().exec("pdflatex.exe...") command. But I don't achive save the PDF file.
Thanks in advance
I think I have the solution, here is the code:
public void generateReport()
{
Process p;
try {
p = Runtime.getRuntime().exec("C:\\pdflatex.exe -synctex=1 -interaction=nonstopmode ./config/log/document.tex");
p.waitFor();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
It generates a .PDF and .dvi file in the same place of your .tex file. Thank you much for your help :)

write multiple images to outputstream in java

I have a folder called images under resources folder in eclipse.
And I have multiple images in images folder.
I want to display all the images in my browser by calling a web-service.
I have tried the following code.I am able to retrieve only one image.I want this for multiple images.How can I do this?
ClassLoader classLoader = getClass().getClassLoader();
File file = new File(classLoader.getResource("images/").getPath());
final String[] EXTENSIONS = new String[]{
"png","jpg"// and other formats you need
};
// filter to identify images based on their extensions
final FilenameFilter IMAGE_FILTER = new FilenameFilter()
{
#Override
public boolean accept(final File dir, final String name) {
for (final String ext : EXTENSIONS) {
if (name.endsWith("." + ext)) {
return (true);
}
}
return (false);
}
};
if (file.isDirectory())
{
//list of files I get
for (final File fi : file.listFiles(IMAGE_FILTER))
{
OutputStream out =null;
OutputStream out1 =null;
BufferedImage bi =null;
try
{
System.out.println("file" +fi);
//I get different files from images folder and add that to bufferedImage.
bi= ImageIO.read(fi);
response.setContentType("image/jpeg");
out= response.getOutputStream();
ImageIO.write(bi, "png", out);
ImageIO.write(bi, "jpg", out);
out.close();
}
catch (final IOException e)
{
// handle errors here
e.printStackTrace();
}
}
}
Resources are not files. There is no guarantee that they will even exist in a filesystem, only inside a JAR or WAR file. So using File methods isn't going to work.
In any case just serializing a stream of images to a browser isn't going to work either. You should be generating an HTML page with <img> elements in it, with URLs for the images, and organizing that those URLs are downloadable. Probably using the resource mechanism isn't appropriate in the first place.

Displaying Base64-Encoded String of raw PDF data using ThinkFree PDF Viewer

The problem:
I'm getting a Base64-Encoded String of raw PDF data from a web service (this data is housed in my String array pdfData). I have to use this data display the PDF in a PDF viewer (I happen to be using the included 'ThinkFree PDF Viewer' since I'm working on an Android application, but lets generalize and say any PDF viewer will do). Note that I'm accessing the 0th element of this array just for testing purposes (to make sure I can at least pull up 1 PDF before writing the code to pull up all the PDFs).
The code is within a class. First the method createFile is called, then intentOpenPDF:
import org.apache.commons.codec.binary.Base64;
File file;
FileOutputStream outputStream;
private byte[] decodedContent;
private String[] pdfData;
private String[] pdfFileName;
public void createFile() {
decodedContent = Base64.decodeBase64(pdfData[0].getBytes());
try {
File path = new File(getFilesDir(), "PDFs");
if (!path.exists()) {
path.mkdirs();
}
file = new File(path, pdfFileName[0]);
outputStream = new FileOutputStream(file);
outputStream.write(decodedContent);
outputStream.close();
}
catch (FileNotFoundException ex) {
ex.printStackTrace();
}
catch (IOException ex) {
ex.printStackTrace();
}
finally {
// Make absolutely certain the outputStream is closed
try {
if (outputStream != null) {
outputStream.close();
}
}
catch (IOException ex) {
ex.printStackTrace();
}
}
}
public void intentOpenPDF() {
// Make sure the file exists before accessing it:
if (file.exists()) {
Uri targetUri = Uri.fromFile(file);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setDataAndType(targetUri, "application/pdf");
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
}
}
The error:
Error opening file. It does not exist or cannot be read.
I have a break point set inside the conditional statement that checks if the file exists (within the intentOpenPDF method), and it IS passing this check.
The path produced by calling getFilesDir() leads a protected directory (file:///data/data/), where only files created with openFileOutput(String, int) are stored. I am not creating the file this way. The solution in my case is to use getExternalFilesDir(null).getAbsolutePath() instead, which will give you a path a directory internal to the application (/storage/emulated/0/Android/data/). No permissions are required to read or write to this path.
Considering your error message:
It does not exist or cannot be read.
as you verified it exists (first possible cause), it's certainly not readable (second possible cause).

Inserting image loses PDF content

I'm trying to insert an image in an existing PDF file but iText puts it on the first page and I'm losing the rest of the page content. How can I insert it without losing existing content?
I used this code:
public static void main(String[] args) {
Document document = new Document(PageSize.A4);
try {
PdfWriter.getInstance(document, new FileOutputStream(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/1.pdf"));
document.open();
Image image = Image.getInstance(
"/home/amira/work/APPS-579/word/generatedMergedDocs/FinalTest/a.jpg");
document.add(image);
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException ioe) {
ioe.printStackTrace();
}
document.close();
}
You're adding the image to an empty document, because you're not reading the original document, just overwriting it.
To modify an existing document with itext with an image, please see the following tutorial which explains it perfectly.

Categories