I am trying to split a pdf document through org.apache.pdfbox.multipdf.Splitter and need to perform certain file operations on this single page PDDocument,
How can I convert PDDocument to File Object in java?
Very simple. I am using 1.8.16
try {
PDDocument document = PDDocument.load(new File(filename));
// do what ever you want
document.save(newfilename);
} catch (IOException | BadSecurityHandlerException | CryptographyException e) {
e.printStackTrace();
}
finally {
if(document != null )
try {
document.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//return tmpFile != null ? tmpFile.getAbsolutePath() : null;
return tmpFilename;
}
with Apache commons
InputStream is = null
try {
PDDocument document = PDDocument.load(filePath);
File targetFile = new File("nameoffile.pdf");
PDStream ps = new PDStream(document);
is = ps.createInputStream();
FileUtils.copyInputStreamToFile(is, targetFile);
} catch (IOException io) {} finally {
if (is != null)
IOUtils.closeQuietly(is);
}
Related
So I am new in programing and i adding a feature in my app which save all sharedpreference key in value in Device internal data folder by using fileoutputStream like this add all data in map and store in jsonobject
private String maptojson(){
Map<String, ?> map = prf.getAll();
JSONObject object = new JSONObject();
for (Map.Entry<String,?> entry : map.entrySet()){
try {
object.put( entry.getKey(), entry.getValue());
} catch (JSONException e) {
e.printStackTrace();
}
}
return object.toString();
}
Now Use FileOutputStream for write file in internal Storage "data'
public void backupSetting() {
Throwable th;
FileOutputStream fileOutputStream;
IOException e;
FileOutputStream fileOutputStream2 = null;
File externalStorageDirectory = Environment.getExternalStorageDirectory();
if (externalStorageDirectory.exists() && externalStorageDirectory.canWrite()) {
if (externalStorageDirectory.getUsableSpace() >= 1048576) {
File file = new File(externalStorageDirectory.toString() + "/data/MyApp/" + "MyAppSetting.ma");
try {
new File(file.getParent()).mkdirs();
file.createNewFile();
fileOutputStream = new FileOutputStream(file);
try {
fileOutputStream.write(maptojson().getBytes());
fileOutputStream.flush();
fileOutputStream.close();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e2) {
e2.printStackTrace();
}
}
} catch (IOException e3) {
e = e3;
try {
e.printStackTrace();
if (fileOutputStream != null) {
}
} catch (Throwable th2) {
th = th2;
fileOutputStream2 = fileOutputStream;
if (fileOutputStream2 != null) {
try {
fileOutputStream2.close();
} catch (IOException e4) {
e4.printStackTrace();
throw th;
}
}
throw th;
}
}
} catch (IOException e5) {
e = e5;
fileOutputStream = null;
e.printStackTrace();
if (fileOutputStream != null) {
try {
fileOutputStream.close();
} catch (IOException e6) {
e6.printStackTrace();
}
}
} catch (Throwable th3) {
th = th3;
if (fileOutputStream2 != null) {
}
try {
throw th;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
}
}
}
Now i want to add restore setting means restore setting by using that file "MyAppSetting.ma". I know i can do it by using FileInputStream but I don't understand how to do? please help if you could
doing the merge of 2 or + pdf I lose some information that imposed in the upload phase of the files (ALT tags on the images). This is the method:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
PDFMergerUtility ut = new PDFMergerUtility();
try {
for (int i = 0; i < filesTBM.length; i++) {
ut.addSource(filesTBM[i]);
}
ut.setDestinationFileName(mergedFileLocation);
ut.mergeDocuments();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (COSVisitorException e) {
e.printStackTrace();
}
}
If the PDF with the ALT tags were in the list of files to be merged, the result is correct, otherwise not. So far I've tried max with 3 PDFs including 1 with ALT tags.
The questions:
How can I not lose the alt tag after the merge of the files?
Thanks to those who want to help me
Daniele
N.b. I have also tried iText pdf:
public static void mergeFiles(ArrayList<String> filesToBeMerged, String mergedFileLocation) {
String[] filesTBM = filesToBeMerged.toArray(new String[filesToBeMerged.size()]);
Document document = new Document();
PdfCopy copy = null;
try {
copy = new PdfCopy(document, new FileOutputStream(mergedFileLocation));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
document.open();
PdfReader[] reader = new PdfReader[filesTBM.length];
for (int i = 0; i < filesTBM.length; i++) {
try {
reader[i] = new PdfReader(filesTBM[i]);
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.addDocument(reader[i]);
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
try {
copy.freeReader(reader[i]);
} catch (IOException e) {
e.printStackTrace();
}
reader[i].close();
}
document.close();
}
I'm trying to parse SVG file to get paths using Xpath within android application. Native java parse the path in following way.
try {
Document document = builder.parse(
new FileInputStream("c:\\employees.xml"));
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
I try to do using FileDescriptor as follows.
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
AssetManager assetManager = getBaseContext().getAssets();
AssetFileDescriptor assetFileDescriptor = null;
try {
assetFileDescriptor = assetManager.openFd("android.svg");
} catch (IOException e) {
e.printStackTrace();
}
FileDescriptor fileDescriptor = assetFileDescriptor.getFileDescriptor();
FileInputStream stream = new FileInputStream(fileDescriptor);
try {
Document document = builder.parse(stream);
} catch (SAXException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
However my app stopped working. What's wrong in my code?
You do not need FileDescriptor. Try as follows.
InputStream input = assetManager.open("android.svg"); //From your asset folder
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = factory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
e.printStackTrace();
}
And parse your input to builder.
Document document = builder.parse(input);
I am trying to create kmz file from kml file on the fly and render it as a stream of bytes in web application.
But when I downloaded generated kmz file, I couldn't open it using archive manager on Ubuntu.
I view similar questions on this site, but it don't work.
Can someone help me and explain what I do wrong?!
This is my code.
#Public public void retrieveKmlInOldFormat() {
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(
kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
String zippedFileName = "old_fmt_map.kmz";
String zippedKml = compressKmlFile(kmlFileContent,zippedFileName);
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
renderBinary(new ByteArrayInputStream(zippedKml.getBytes()),zippedFileName);
return;
}
Compress method code:
private String compressKmlFile(String kmlFileContent,String zipEntryName){
String zippedContent = null;
ByteArrayOutputStream byteStream = new ByteArrayOutputStream();
ZipOutputStream zipStream = new ZipOutputStream(new
BufferedOutputStream(byteStream));
ZipEntry zipEntry = null;
zipEntry = new ZipEntry("doc.kml");
try {
zipEntry.setSize(kmlFileContent.getBytes("UTF-8").length);
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes("UTF-8"));
zipStream.closeEntry();
zippedContent = new String(byteStream.toByteArray(),"UTF-8");
} catch (IOException e) {
logger.error("Error while zipping kml file content");
}
finally {
try {
byteStream.close();
zipStream.close();
} catch (IOException e) {
logger.error(e.getMessage());
}
}
return zippedContent;
}
The problem is about downloaded corrupted kmz archive. This problem can be resolved by using output stream of http response as constructor argument for ZipOutputStream class.
Solution is in this code.
#Public public void retrieveKmlInOldFormat(){
File file = new File(Play.applicationPath+"/"+Play.configuration.getProperty("web.content", "../bspb-web")+"/map/map.kml");
String kmlFileContent = null;
try {
String kmlUrl = file.toURI().toURL().toString();
kmlFileContent = BSPBKml2OldFormatConverter.toOldKml(kmlParserLocal.load(kmlUrl));
} catch (MalformedURLException e) {
e.printStackTrace();
}
response.setContentTypeIfNotSet("application/vnd.google-earth.kmz");
response.setHeader("Content-Disposition", "attachment; filename=\"old_fmt_map.kmz\"");
renderAsKmz(response, kmlFileContent,"old_fmt_map.kml");
return;
}
private void renderAsKmz(Response response,String kmlFileContent,String zipEntryName){
ZipOutputStream zipStream = new ZipOutputStream(response.out);
ZipEntry zipEntry = new ZipEntry(zipEntryName);
try {
zipStream.putNextEntry(zipEntry);
zipStream.write(kmlFileContent.getBytes());
} catch (IOException e) {
logger.error("Error while zipping kml file content : " + e.getMessage());
}
finally {
try {
zipStream.closeEntry();
zipStream.close();
} catch (IOException e) {
logger.error("Error while closing zipped stream : " + e.getMessage());
}
}
I'm still receiving 1st file my app generated for me.
First , I thought it's because the file exists so I wrote
File file=new File(getCacheDir(), "Competition.xls");
if (file.exists()) {file.delete(); file =new File(getCacheDir(), "Competition.xls");}
But that didn't help me-I still receive first file that was made
I'm new to working with files so I decided to copy entire method here. Sorry for a lot of text.
private void createFileTosend() {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend=null;
try {
toSend = getFile();
} catch (WriteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
inputStream = new FileInputStream(toSend);
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
try {
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} catch (IOException ioe) {
/* ignore */
}
} catch (FileNotFoundException fnfe) {
/* ignore */
} finally {
try {
inputStream.close();
} catch (IOException ioe) {
/* ignore */
}
try {
outputStream.close();
} catch (IOException ioe) {
/* ignore */
}
}
}
public File getFile() throws IOException, WriteException{
File file=new File(getCacheDir(), "Competition.xls");
if (file.exists()) {file.delete(); file =new File(getCacheDir(), "Competition.xls");}
WritableWorkbook workbook = Workbook.createWorkbook(file);
//then goes long block with creating a .xls file which is not important
workbook.write();
workbook.close();
return file;
}
Help on understanding where the problem is
You should never have a structure like :
catch(Exception ex ) {
//ignore (or log only)
}
Exception are there to tell you something went wrong. What you do is called (in french) "eating/hiding exceptions". You are loosing this very important information that something went abnormally.
You should always either throw the exception you catch to your caller, or process it locally. At the very least, and this is a poor practice, you should log it. But doing nothing is just very wrong.
Here, put the whole try catch in a method for instance :
private void createFileTosend() throws IOException {
InputStream inputStream = null;
FileOutputStream outputStream = null;
try {
File toSend = getFile();
inputStream = new FileInputStream(toSend);
outputStream = openFileOutput("Competition.xls",
Context.MODE_WORLD_READABLE | Context.MODE_APPEND);
byte[] buffer = new byte[1024];
int length = 0;
while ((length = inputStream.read(buffer)) > 0){
outputStream.write(buffer, 0, length);
}
} finally {
try {
if( inputStream != null ) {
inputStream.close();
}
} catch (IOException ioe) {
Log.e( ioe );
}
try {
if( outputStream != null ) {
outputStream.close();
}
} catch (IOException ioe) {
Log.e( ioe );
}
}
}
And now, when you call createFileToSend, do that in a try/catch structure and toast a message, or something if you catch an exception.