It bothered me a whole day afternoon.
I encounter many problems and by now i cannot overcome them.
my code:
public void pdf2jpg(){
try {
File pdfFile =new File("c://tmp//1.pdf");
PDFDocument document = new PDFDocument();
document.load(pdfFile);
SimpleRenderer renderer = new SimpleRenderer();
renderer.setResolution(300);
List<Image> images = renderer.render(document);
for (int i = 0; i < images.size(); i++) {
Image img= images.get(i);
ImageIO.write((RenderedImage)img, "jpg", new File(i+".jpg"));
}
} catch (IOException | RendererException | DocumentException e) {
e.printStackTrace();
}
}
My box: Windows 7, jdk:1.7.0_45(64bit), GPL ghostscript 9.0.4.
when I use ghost4j 0.4.4, I got error "net.sf.ghost4j.renderer.RendererException: net.sf.ghost4j.GhostscriptException: Cannot initialize Ghostscript interpreter. Error code is -20"
on List<Image> images = renderer.render(document);
Some thread here mentions it's about ghost4j version. so i change to 0.4.6, error 20 disappears, but comes Warning: An error occurred while reading an XREF table. on the same sentence.
I cannot figure out how to get out of this 'mud',
Thanks very much for your help.
I'd guess that the returned bitmap is simply too large for memory, given that you get an out of memory error.
You should try using Ghostscript directly from the command line for 2 reasons, firstly you will be able to see if there is a real error message about the xref, which would indicate your PDF file is damaged, secondly you might reasonably just run a shell command to invoke GhostScript to render the PDF directly to JPEG rather than going through an in-memory bitmap. Its probably faster apart from anything else.
gswin32c -sDEVICE=jpeg -o out.jpg input.pdf
Related
I'm implementing a GUI for a chess program I'm writing for a class. To make it look polished, I want to utilize a Chess Piece Font I obtained from the internet.
The file, chess.ttf, is located at the path Chess/resources/chess.ttf. I utilize the following code per Oracle's instructions (https://docs.oracle.com/javase/tutorial/2d/text/fonts.html):
try {
File file = new File("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, file);
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
ge.registerFont(Font.createFont(Font.TRUETYPE_FONT, file));
//Derive and return a 12 pt version:
//Need to use float otherwise
//it would be interpreted as style
return font.deriveFont(12f);
}
catch (IOException|FontFormatException e) {
System.out.println("-Font Error-");
return null;
}
However, this throws an IOException. I ran getAbsolutePath() on the file and received /Users/[me]/eclipse-workspace/Chess/resources/chess.ttf so I'm assuming the file is being loaded correctly. Does anyone know what's going wrong with my code?
edit: Problem resolved? I tried InputStreams as suggested but that didn't work, yet upon reverting my code the computer finally stopped throwing IOExceptions. Isn't code the best?
You'd better copy the ttf using build script like ant or maven /Users/[me]/eclipse-workspace/Chess/bin/resources
ClassLoader loader = Thread.currentThread().getContextClassLoader();
System.out.println(loader.getResource(".").getPath()); // for tracing the working folder only
java.io.InputStream ins = loader.getResourceAsStream("resources/chess.ttf");
//Returned font is of pt size 1
Font font = Font.createFont(Font.TRUETYPE_FONT, ins);
I have a file called Gate.IC inside my assets in my Android App.
I use this code to measure the length of the file in the assets:
private byte[] Buf = new byte[1024*512];
public int FileLength (String s)
{
int Count = 0;
try {
InputStream s2 = assetManager.open(s);
int tmp = 0;
while ((tmp=s2.read(Buf))>0)
Count+=tmp;
s2.close();
}
catch (IOException e) {
String Message = e.getMessage();
}
return Count;
}
This code works fine for all files except this one.
When it gets to this file, it does open it(and shows the correct file length), but when it reads it I get an IOException and the LogCat says "Error reading asset data" and then "Unable to access asset data: -1"
If I take a different file and change it's name to Gate.IC and don't have the actual Gate.IC file in the assets, it works.
If I change the name of the original Gate.IC into another asset's name, then I get the same error with the "cover" name.
I don't know what it is in this file that it just can't read it.
Here is the Rogue file:
https://dl.dropbox.com/u/8025882/RPG/Gate.IC
you can use this for getting length of the file:
getAssets().openFd( "filename" ).getLength();
I have solved the issue.
Well as I mentioend, it turns out ADT or the Android SDK packaging would compress some fo the assets. My file being my own custom format would be compressed.
Once your file is compressed you cannot read it the same way I did.
There is a program in Android SDK called aapt.exe. It does the packaging of the assets.
All you need to do is call this command with the flag -0 .
Sounds simple, right?
The issue is that eclipse does not let you add flags to this command from within the ADT plugin.
You need to either edit the Android SDK XML build files, or to replace aapt.exe with your own program that calls the original aapt.exe program with the flags you want.
I did the latter.
Here is my devblog entry about it.
http://pompidev.net/2012/10/27/unable-to-access-asset-data-1-and-compressed-assetsandroid/
I am trying to read some image files jpg, tif, gif, png and need to save files and create icons.
And i am getting UnsupportedTypeException.
ImageIO.read(file);
If i use following line, as earlier discuss in form.
BufferedImage img = JPEGCodec.createJPEGDecoder(inputStream).decodeAsBufferedImage();
I get JPEGCodec cannot found symbol.
I am using netbean 7.0.1. I have also added jai-imageio.jar.
By default, ImageIO can only read JPG, GIF and PNG file formats, if I remember right. To add new formats like TIFF, you need to add a plugin, which is a jar file, to your classpath, and to add an ImageIO.scanForPlugins() to you code before you try to read a file.
Example of plugin:
http://ij-plugins.sourceforge.net/plugins/imageio/
Try "ImageIO plugins" in Google.
JAI-ImageIO does include plugins for file formats like TIFF, so in principal what you are trying to do should work. However, to install JAI-ImageIO it's not enough to add it to your classpath. See the complete installation instructions here: http://java.sun.com/products/java-media/jai/INSTALL-jai_imageio_1_0_01.html
Fr detail we can see the like
http://www.randelshofer.ch/blog/2011/08/reading-cmyk-jpeg-images-with-java-imageio/
Image img = null;
ImageInputStream iis = new FileImageInputStream(file);
try {
for (Iterator<ImageReader> i = ImageIO.getImageReaders(iis);
img == null && i.hasNext(); ) {
ImageReader r = i.next();
try {
r.setInput(iis);
img = r.read(0);
} catch (IOException e) {}
}
} finally {
iis.close();
}
return img;
Java advance image io also solve the problem, but its hard to maintain to install on all plateform.
Does anyone know of a way to detect whether a given PDF file is a PDF Portfolio or a PDF Package, rather than a "regular" PDF? I'd prefer Java solutions, although since I haven't yet found any information on detecting the specific type of PDF, I'll take what I can get and they try to figure out the Java solution afterwards.
(In searching past questions, it appears that a bunch of folks don't know that such things as PDF Portfolios and PDF Packages exist. Generally, they're both ways that Adobe allows multiple, discrete PDFs to be packaged into a single PDF file. Opening a PDF Package in Reader shows the user a list of the embedded PDFs and allows further viewing from there. PDF Portfolios appear to be a bit more complicated -- they also include Flash-based browser for the embedded files, and then allow users to extract the discrete PDFs from there. My issue with them, and the reason I'd like to be able to detect them in code, is because OS X's built-in Preview.app can't read these files -- so I'd like to at least warn users of a web app of mine that uploading them can lead to diminished compatibility across platforms.)
This question is old, but in-case someone wants to know, it is possible. It can be done with Acrobat and JavaScript by using the following command.
if (Doc.collection() != null)
{
//It Is Portfolio
}
Acrobat JavaScript API says, "A collection object is obtained from the Doc.collection property. Doc.collection returns a null value when there is no PDF collection (also called PDF package and PDF portfolio).The collection object is used to set the initial document in the collection, set the initial view of the collection, and to get, add, and remove collection fields (or categories)."
I'm also facing same problem while extracting data through kofax, but i got solution and its working fine need to add extra jar for Document class.
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
public class PDFPortfolio {
/**
* #param args
*/
public static void main(String[] args) {
com.aspose.pdf.Document pdfDocument = new com.aspose.pdf.Document("e:/pqr1.pdf");
// get collection of embedded files
com.aspose.pdf.EmbeddedFileCollection embeddedFiles = pdfDocument.getEmbeddedFiles();
// iterate through individual file of Portfolio
for(int counter=1; counter<=pdfDocument.getEmbeddedFiles().size();counter++)
{
com.aspose.pdf.FileSpecification fileSpecification = embeddedFiles.get_Item(counter);
try {
InputStream input = fileSpecification.getContents();
File file = new File(fileSpecification.getName());
// create path for file from pdf
// file.getParentFile().mkdirs();
// create and extract file from pdf
java.io.FileOutputStream output = new java.io.FileOutputStream("e:/"+fileSpecification.getName(), true);
byte[] buffer = new byte[4096];
int n = 0;
while (-1 != (n = input.read(buffer)))
output.write(buffer, 0, n);
// close InputStream object
input.close();
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
I tried both of the following options:
1.
BufferedImage Buffered_Image;
MemoryCacheImageOutputStream MemoryCache_OutputStream =
new MemoryCacheImageOutputStream(new FileOutputStream("C:/Test.mov",false));
while (notFinished) // Main recording loop.
{
Buffered_Image=robot.createScreenCapture(); // Capture Screen image.
try { ImageIO.write(Buffered_Image,"png",MemoryCache_OutputStream); }
catch (Exception e) { e.printStackTrace(); }
}
2.
BufferedImage Buffered_Image;
ImageWriter writer;
try
{
ImageOutputStream ios=ImageIO.createImageOutputStream(new File("C:/Test.mov"));
Iterator writers=ImageIO.getImageWritersByFormatName("png");
while (writers.hasNext())
{
writer=(ImageWriter)writers.next();
writer.setOutput(ios);
Out(writer.toString()+" canInsertImage : "+writer.canInsertImage(0));
// Got this: com.sun.imageio.plugins.png.PNGImageWriter#19fcc69
// canInsertImage : false
}
}
catch (Exception e) { }
cntPics=0;
while (notFinished) // Main recording loop.
{
Buffered_Image=robot.createScreenCapture(); // Capture Screen image.
writer.write(null,new IIOImage(Buffered_Image,null,null),null);
if (writer.canInsertImage(-1)) {
// Append image at highest index
writer.writeInsert(-1,new IIOImage(Buffered_Image,null,null),null);
} else Out("Writer can’t append image Id : "+cntPics);
cntPics++;
}
Neither of them worked, what's the correct way to save multiple PNG images to a file?
Edit:
You are right, I found a java program called Krut that can record screen sessions, but it uses JPEGImageEncoder, the image quality isn't as good as I want, so I wonder if I can use ImageIO to encode the sequence.
If ImageIO can't do it, my next question would be is there a stand alone open source PNGImageEncoder that I can use to encode it? I know there are open source PNGImageEncoders, but they tend to be tangled in projects and hard to get all the supporting files out of it, any ideas? Thanks!
It looks like you're trying to create a video (MOV) file by writing multiple PNG files in a row. This isn't going to work. You'll probably have to find a third-party library for encoding your images into a video file (which is itself may be a good SO question).
EDIT: I should also note that you may actually be able to get video by writing multiple JPG images in a row to get a form of MJPEG (Motion JPEG) but for other formats such as MOV you're going to need an actual encoder.
What are you trying to do? Re-inventing MNG? Even if you can write multiple PNG images in the same file, it makes a compound file understood by no program (except those you might write).
If, as suggested by Marc, you want to make a movie, you might want to look at QuickTime for Java (QTJava). It is the solution used by Processing to make movies out of animations/frames. It has several quality/formats, from the worst (but small files) to the highest quality (high file sizes as result).