PdfStamp of IText 5.4.4 causes exception when calling Close() - itext

The simple code below causes exception "Data at the root level is invalid. Line 1, position 1" AS LONG AS the pdf producer is "Mac OSX 10.8.5 Quartz PDFCOntext" 1.4 (Arcobat 5.x). Any other pdf works without err.
PdfReader reader = new PdfReader(fullInputPath);
using (FileStream fs = new FileStream(fullOutputPath, FileMode.Create))
{
using (stamper = new PdfStamper(reader, fs))
{
} <= got err here!
}
Please help!
Thank you in advance

Related

Synchronize files from Box.com to AEM DAM

I am trying to sync the files from my Box.com account to AEM(CQ5) DAM. I have written a service where I am able to authenticate to Box.com and get the files. But in order for me to upload those into AEM DAM, I need the files as InputStream. On Box.com documentation(https://github.com/box/box-java-sdk/blob/master/doc/files.md), I find the code snippet for Downloading a file.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
FileOutputStream stream = new FileOutputStream(info.getName());
file.download(stream);
stream.close();
But I could not find anything where I can get the file in Inputstream so that I can use it to upload it into AEM DAM. When I tried to convert from OutputStream to Inputstream, its just not really working and creating ZERO bytes files in AEM.
Any pointers and help greatly appreciated !
Thanks in advance.
I had a similar problem where I tried to create a CSV within CQ and store it in JCR. The solutions are piped Streams:
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream(pis);
Though I then used an OutputStreamWriter to write into the output stream, but the FileOutputStream.download should work as well.
To actually write into JCR you need the ValueFactory, which you can get from a JCR Session (here the example for my CSV):
ValueFactory valueFactory = session.getValueFactory();
Node fileNode = logNode.addNode("log.csv", "nt:file");
Node resNode = fileNode.addNode("jcr:content", "nt:resource");
resNode.setProperty("jcr:mimeType", "text/plain");
resNode.setProperty("jcr:data", valueFactory.createBinary(pis));
session.save();
EDIT: untested example with BoxFile:
try {
AssetManager assetManager = resourceResolver.adaptTo(AssetManager.class);
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
final PipedInputStream pis = new PipedInputStream();
final PipedOutputStream pos = new PipedOutputStream(pis);
Executors.newSingleThreadExecutor().submit(new Runnable() {
#Override
public void run() {
file.download(pos);
}
});
Asset asset = assetManager.createAsset(info.getName(), pis, info.getMimeType(), true);
IOUtils.closeQuietly(pos);
IOUtils.closeQuietly(pis);
} catch (IOException e) {
LOGGER.error("could not download file: ", e);
}
If i understand the code correctly you are downloading the file to a file named info.getName(). Try using FileInputStream(info.getName()) to get the input stream from the downloaded file.
BoxFile file = new BoxFile(api, "id");
BoxFile.Info info = file.getInfo();
FileOutputStream stream = new FileOutputStream(info.getName());
file.download(stream);
stream.close();
InputStream inStream=new FileInputStream(info.getName());

Rebuild failed using PDF compression

Im trying to use the methods described bt kuujinbo here.
PDF Compression with iTextSharp
This is my code, and it results in this error:
"Rebuild failed: trailer not found.; Original message: PDF startxref not found."
PdfReader reader = new PdfReader(output.ToArray());
ReduceResolution(reader, 9);
// Save altered PDF. then you can pass the btye array to a database, etc
using (MemoryStream ms = new MemoryStream())
{
using (PdfStamper stamper = new PdfStamper(reader, ms))
{
}
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("Content-Disposition", string.Format("attachment;filename=Produktark-{0}.pdf", myItem.Key));
Response.BinaryWrite(output.ToArray());
}
What might I be missing?
An exception stating Rebuild failed: ...; Original message: ... is thrown by iText only during PdfReader initialization, i.e. in your case in the line
PdfReader reader = new PdfReader(output.ToArray());
and it indicates that the read data, i.e. output.ToArray(), does not constitute a valid PDF. You should write output.ToArray() to some file, too, and inspect it.
If you wonder why the message indicates that some Rebuild failed... you actually don't get the initial error but a follow-up one, the PDF digesting code has multiple blocks like this
try {
read some part of the PDF;
} catch(Exception) {
try {
try to repair that part of the PDF and read it;
} catch(Exception) {
throw "Rebuild failed: ...; Original message: ...";
}
}
In your case the part of interest was the cross reference table/stream and the issue was that the PDF startxref (a statement containing the offset of the cross reference start in the document) was not found.
When I receive this error message it is caused by not closing the PDFStamper that I am using to edit the form fields.
Stamper.Close();
Must call before closing the PDF or will throw specified error.

Error in uploading a file using Jersey rest service

I am using jersey for building rest service which will upload a file. But I am facing problem in writing a file to required location. Java throws a system cannot find specified path error. Here is my Web service :
#POST
#Path("/fileupload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response uploadFile(#FormDataParam("file")InputStream fileUploadStream, #FormDataParam("file")FormDataContentDisposition fileDetails) throws IOException{
StringBuilder uploadFileLocation= new StringBuilder();
uploadFileLocation.append("c:/logparser/webfrontend/uploads");
uploadFileLocation.append("/"+dateFormat.format(Calendar.getInstance().getTime()));
uploadFileLocation.append("/"+fileDetails.getFileName());
writeToFile(fileUploadStream, uploadFileLocation.toString());
return Response.status(200).entity("File saved to " + uploadFileLocation).build();
}
private void writeToFile(InputStream uploadInputStream, String uploadFileLocation)
{
log.debug("UploadService , writeToFile method , start ()");
try{
int read = 0;
byte[] bytes = new byte[uploadInputStream.available()];
log.info("UploadService, writeToFile method , copying uploaded files.");
OutputStream out = new FileOutputStream(new File(uploadFileLocation));
while ((read = uploadInputStream.read(bytes)) != -1)
{
out.write(bytes, 0, read);
}
out.flush();
out.close();
}
catch(Exception e)
{
log.error("UploadService, writeToFile method, error in writing to file "+e.getMessage());
}
}
From looking at just the code (it's usually helpful to include the exception and stack trace), you're trying to write to a directory based on a timestamp which doesn't exist yet. Try adding a call to File.mkdir/mkdirs. See this question/answer: FileNotFoundException (The system cannot find the path specified)
Side note - Unless you have a reason not to, I'd consider using something like Apache commons-io(FileUtils.copyInputStreamToFile) to do the writing.

Populate database from internal project textfile wp7

I implemented a mango database in my windows phone project.
I want to add data from an internal project file.
I tried to use the StreamReader
StreamReader L= new StreamReader ("/Data/info.txt");
But the problem still exists.
Is there a solution to resolve this problem?
Cordially
The file 'File.txt' should be referenced as internal ressource.
In this case, 'test' is the project name.
var resource = App.GetResourceStream(new Uri(#"/test;component/File.txt", UriKind.Relative));
try
{
StreamReader streamReader = new StreamReader(resource.Stream);
string x = streamReader.ReadToEnd();
MessageBox.Show(x);
}
catch(Exception e)
{
MessageBox.Show(e.ToString());
}

Lucene.net read past EOF error during IndexWriter creation

I'm trying to implement Lucene.net in my C# application.
At this point i'm still at the very start: creating an index.
I use the following code:
var directory = new Lucene.Net.Store.SimpleFSDirectory(new System.IO.DirectoryInfo("d:\\tmp\\lucene-index\\"));
var analyzer = new Lucene.Net.Analysis.Standard.StandardAnalyzer(Lucene.Net.Util.Version.LUCENE_29);
var writer = new Lucene.Net.Index.IndexWriter(directory, analyzer, true, Lucene.Net.Index.IndexWriter.MaxFieldLength.UNLIMITED);
I get an IOException on the writer initialization line.
The error message is "Read past EOF" and it occurs in the IndexInput class in the ReadInt() method.
The code does produce some files in the lucene-index directory (segments.gen and write.lock) but both are 0 bytes.
I tried to google for this problem but i can't find any good info about it.
Is there a Lucene.Net expert here who can help me?
Here's some code that I've used before. I think the problem that you are experiencing is with the SimpleFSDirectory.
var writer = new IndexWriter("SomePath", new StandardAnalyzer());
writer.SetMaxBufferedDocs(100);
writer.SetRAMBufferSizeMB(256);
// add your document here
writer.AddDocument( ... );
writer.Flush();
// the Optimize method is optional and is used by lucene to combine multiple index files
writer.Optimize();
writer.Close();