Rebuild failed using PDF compression - itext

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.

Related

File sent by Nearby not opening

I'm starting to work with Nearby, and sending a file over the stream. I see on the sender's side that the file is sent, and on the receiver's side I see both the onPayloadReceived event and 2 onPayloadTransferUpdate events, the second with a status of 1. Once I get that event with status 1, I run the following code:
Payload payload = payloads.remove(id);
try {
Payload.File payloadFile = payload.asFile();
Reader reader;
File file = payloadFile.asJavaFile();
if (file==null)
reader = new FileReader(payloadFile.asParcelFileDescriptor().getFileDescriptor());
else
reader = new FileReader(file);
StringBuilder builder = new StringBuilder();
char[] buff = new char[1024];
do
{
int count = reader.read(buff);
if (count<=0)
break;
builder.append(buff, 0, count);
}while(true);
receivedData.setText(builder);
}
catch (Exception exn){Log.d(TAG, "Exception thrown while receiving",exn);}
The result is that file is null, and the read command throws an IOException with the message read failed: EBADF (Bad file number). How do I fix this?
Could you show the code that corresponds to you "sending a file over the stream"?
I ask because STREAM and FILE are 2 different Payload types, so if you send as a STREAM (regardless of whether the contents of the STREAM came from a file), you will receive as a STREAM.

BizTalk custom pipeline parsing POP3 PDF attachment error

I have a BizTalk custom pipeline component where I'm parsing a PDF attachment using itexsharp into a custom model. The pipeline is bound to a POP3 receiving port.
In the new created message if I return the attachment stream (outputMessage.GetPart("Body").Data = ms), then this is looking good in the BizTalk administration console. I have been able to save the message from here manually and this was parsed correctly using the same parsing method as in the pipeline.
When parsing the PDF directly in the pipeline, then I'm getting the following error: Rebuild failed: trailer not found.; Original message: xref subsection not found at file pointer 1620729
If I remove the default XMLDisassembler component from pipeline, then the parsing error disappeared, but in the console the message Body is empty, although the AttachmentSizeInBytes=1788
public IBaseMessage Execute(IPipelineContext pContext, IBaseMessage pInMsg)
{
return ExtractMessagePartToMessage(pContext, pInMsg);
}
private IBaseMessage ExtractMessagePartToMessage(IPipelineContext pContext, IBaseMessage pInMsg)
{
if (pInMsg.PartCount <= 1)
{
throw new InvalidOperationException("The email had no attachment, apparently.");
}
string partName;
IBaseMessagePart attachmentPart = pInMsg.GetPartByIndex(1, out partName);
Stream attachmentPartStream = attachmentPart.GetOriginalDataStream();
IBaseMessage outputMessage;
outputMessage = pContext.GetMessageFactory().CreateMessage();
outputMessage.AddPart("Body", pContext.GetMessageFactory().CreateMessagePart(), true);
outputMessage.Context = pInMsg.Context;
var ms = new MemoryStream();
attachmentPartStream.CopyTo(ms);
ms.Seek(0L, SeekOrigin.Begin);
Stream orderStream = PdfFormParser.Parse(ms);
outputMessage.GetPart("Body").Data = orderStream;
outputMessage.Context.Write("AttachmentName", "http://schemas.microsoft.com/BizTalk/2003/file-properties", partName);
outputMessage.Context.Write("AttachmentSizeInBytes", "http://schemas.microsoft.com/BizTalk/2003/file-properties", orderStream.Length.ToString());
pContext.ResourceTracker.AddResource(ms);
pContext.ResourceTracker.AddResource(orderStream);
return outputMessage;
}
public static Stream Parse(Stream pdfDocument)
{
using (var reader = new PdfReader(pdfDocument))
{
var outputStream = new MemoryStream();
var pdfForm = ParseInternal(reader);
var xmlDocument = new XmlDocument();
xmlDocument.LoadXml(pdfForm.Serialize());
xmlDocument.Save(outputStream);
return outputStream;
}
In pipelines when you read or write a Stream, you have to rewind the stream back to the beginning if something else is going to use it (especially the final message that you expect BizTalk to process).

PdfStamp of IText 5.4.4 causes exception when calling Close()

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

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());

Thread was being aborted exception in crystal reports

We were getting the Thread was being aborted Exception while exporting a report into PDF.
The below code we were using for export a report into PDF.
Response.Buffer = true;
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
myReportDoc.ExportToHttpResponse(ExportFormatType.PortableDocFormat, Response, true, Session["ReportName"].ToString());
Response.Flush();
Response.Close();
Please help me how to resolve this exception.
SAP explains that:
Cause
The issue has been identified and logged under Problem Report ID ADAPT00765364.
The error is likely caused because Response.End() is used inside the ExportToHttpResponse() method.
It is a known issue that Reponse.End() causes the thread to abort. This is by design.
See Microsoft KB312629 Article for more info.
Workaround
....
try
{
reportDocument.ExportToHttpResponse(format, Response, true, Page.Title);
}
catch (System.Threading.ThreadAbortException)
{
}
....
Resolution
You can write your own code to export a Crystal Report directly to the browser in a format such as PDF, Word, Excel, etc. You must make sure you use the appropriate content type.
Sample code to export Crystal Report to web browser as PDF
try
{
boReportDocument.Load(Server.MapPath(#"MyReport.rpt"));
System.IO.Stream oStream = null;
byte[] byteArray = null;
oStream = boReportDocument.ExportToStream (ExportFormatType.PortableDocFormat);
byteArray = new byte[oStream.Length];
oStream.Read(byteArray, 0, Convert.ToInt32(oStream.Length - 1));
Response.ClearContent();
Response.ClearHeaders();
Response.ContentType = "application/pdf";
Response.BinaryWrite(byteArray);
Response.Flush();
Response.Close();
boReportDocument.Close();
boReportDocument.Dispose();
}
catch (Exception ex)
{
string s = ex.Message;
}
The error is thrown because a call to response.End() is made inside of ExportToHttpResponse. Remove your calls to Flush and Close the response and wrap your call to ExportToHttpResponse inside a try/catch block to catch and ignore the System.Threading.ThreadAbortException.