I have managed to create my own pdf documents with the help of PdfDocument Class.
But what if I already have a pdf in my (let's say) assets folder and I want to e.g. draw something on it. Is it possible?
I have my
PdfDocument document;
But how can i read the powerpoint i have inside my project?
I am guessing i have to use a File but i cannot work this out.
I tried something like this, although I know it is wrong
PdfDocument document = new PdfDocument(getAssets().open("powerpoint"));
From what I understand you ask two questions:
But what if I already have a pdf in my (let's say) assets folder and I
want to e.g. draw something on it. Is it possible?
With the android PdfDocument class, you can create a PDF out of Web content (via WebView), a Canvas (using views or the native Canvas drawing API), or an image. You have to use third-party PDF libraries (like iText or the PDFBox Android port) to change existing PDFs.
But how can i read the powerpoint i have inside my project?
For displaying powerpoint there is a separate project called 'pptviewer-android'. However it is not maintained anymore, so if you have problems you probably have to figure those out by yourself. An examplary use can be found here.
PPTViewer pptViewer = (PPTViewer) findViewById(R.id.pptviewer);
pptViewer.setNext_img(R.drawable.next)
.setPrev_img(R.drawable.prev)
.setSettings_img(R.drawable.settings)
.setZoomin_img(R.drawable.zoomin)
.setZoomout_img(R.drawable.zoomout);
pptViewer.loadPPT(this,"/home/powerpoint.pptx");
Not sure whether I have correctly understood your problem statement:
Please try this out:
if (Desktop.isDesktopSupported()) {
try {
File fileToOpen = new File("/assets/file.pdf");
Desktop.getDesktop().open(fileToOpen);
} catch (IOException ex) {
// log Error
}
}
Related
Good afternoon. I have a JAR file to which I have attached some images as resources in a folder called logos. I am being told to do this due to security restrictions (we don't want the image files to be exposed in the same folder as the JAR). I first tried to load these images in as if they were a File object, but that obviously doesn't work. I am now trying to use an InputStream to load the image into the required PDImageXObject, but the images are not rendering into the PDF. Here is a snippet of the code which I am using:
String logoName = "aLogoName.png";
PDDocument document = new PDDocument();
// the variable "generator" is an object used for operations in generating the PDF
InputStream logoFileAsStream = generator.getClass().getResourceAsStream("/" + logoName);
PDStream logoStream = new PDStream(document, logoFileAsStream);
PDImageXObject logoImage = new PDImageXObject(logoStream, new PDResources());
PDPage page = new PDPage(new PDRectangle(PDRectangle.A4.getHeight(), PDRectangle.A4.getWidth()));
document.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(document, page);
contentStream.drawImage(logoImage, 500, 100);
Note that I have verified that the resource is getting loaded in correctly, as using logoFileAsStream.available() returns a different value for various logos. After running this code, the image does not actually get drawn on the PDF, and upon opening it, the error message "An error exists on this page. Acrobat may not display the page correctly. Please contact the person who created the PDF document to correct the problem." appears. Could someone please help me figure what's wrong with that code snippet/a different solution to load my images in as a resource from the JAR? Thanks so much. Let me know if more details are needed/clarification.
This PDImageXObject constructor is for internal PDFBox use only. You can use
PDImageXObject.createFromByteArray(document, IOUtils.toByteArray(logoFileAsStream), logoName /* optional, can be null */)
for maximum flexibility, or if you know it is always a PNG file
LosslessFactory.createFromImage(document, ImageIO.read(logoFileAsStream))
don't forget to close logoFileAsStream and contentStream.
I am currently developing a game, and have encountered a very burdensome problem.
I want to draw a picture on the screen but every time I try to read the resource / picture I get NULL. I tried 2 kinds of methods to read the picture but still couldn't.
But when I moved the image into the package that contains the class from which I was trying to read the image the image appeared.
So the problem is that i just can't access resources outside of the current package. And i need to know how can i do that, how can i access this resource. It has to be a resource that I can use even after exporting the game to a JAR file.
Code I tried (The first one is buffered image and the second is just image type:
try {
image = ImageIO.read(getClass().getResource("blocks.png"));
} catch (IOException e) {
e.printStackTrace();
}
--------------------------------------------------------------
image = new ImageIcon(getClass().getResource("blocks.png))).getImage();
I hope the question is clear enough.
Try creating a package called "resources", instead of a folder, and then access your image as "resources/blocks.png".
I am using iTextPdf 5.5.3 to create PDF/A documents, I want the user to select custom fonts by uploading the .ttf file of the font, and becuase FontFactory.getFont() method only takes the font name as a string I have to write the uploaded file to the user's drive (I KNOW, I ASKED MY CUSTOMER FOR PERMISSION TO WRITE TO THE DRIVE) and then pass the path of the uploaded file to the getFont() method, after everything is finished I want to delete the uploaded files from the drive. Here is my code:
File fontFile = new File("d:/temp/testFont.ttf");
try {
FileOutputStream outStream = new FileOutputStream(fontFile);
outStream.write(the bytes of the uploaded font file);
outStream.flush();
outStream.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Font font = FontFactory.getFont(fontFile.getAbsolutePath(), BaseFont.CP1250 , BaseFont.EMBEDDED);
fontFile.delete();
This code is not working, somehow the getFont() method is locking the font file and therefore the file is not being deleted. I tried lots of ways to do this, like: fontFile.deleteOnExit(); or FileDeleteStrategy.FORCE.delete("file path"); but nothing is working for me. Please advise. Thanks
I am not going to answer the question mentioned in the title of your post (because it is a secondary). Instead I am going to answer the question in the body (which is the essential question).
You claim that FontFactory.getFont() requires a font file on the file system. That is not incorrect. However, that doesn't mean you can't create a font from a byte[].
You are trying to solve your problem by saving a ttf on disk (which is forbidden by your customer), but that isn't necessary. In a way, your customer is right: it's not a good idea to save the TTF as a temporary file on disk (which is why I'm ignoring your secondary question).
Take a look at the following createFont() method:
public static BaseFont createFont(String name,
String encoding,
boolean embedded,
boolean cached,
byte[] ttfAfm,
byte[] pfb)
throws DocumentException,
IOException
This is how you should interpret the parameters in your case:
name - the name of the font (not the location)
encoding - the encoding to be applied to this font
embedded - true if the font is to be embedded in the PDF
cached - probably false in your case, as you won't be reusing the font in the JVM
ttfAfm - the bytes of the .ttf file
pfb - in your case, this value will benull (it only makes sense in the context of Type1 fonts).
Now you can meet the requirements of your customer and you do not need to introduce a suboptimal workaround.
Note: you are using iText 5.5.3 which is available under the AGPL. Please be aware that your customer will need to purchase a commercial license with iText Software as soon as he starts using iText in a web service, in a product,...
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).