Serialization Exception - binaryformatter

what is Exception "End of Stream encountered before parsing was completed." in the my code?
BinaryFormatter t = new BinaryFormatter();
MemoryStream n = new MemoryStream();
t.Serialize(n, j);
BinaryFormatter q = new BinaryFormatter();
MemoryStream x = new MemoryStream();
q.Deserialize(n);

After serializing the object to the stream, the stream's Position is at the end.
Therefore, there is nothing more in the stream for the deserializer to read.
You need to rewind the stream, by setting n.Position = 0.

Related

Using Temp File Method for signing in iText Java instead of depending on System Memory

We are using PKCS7 Signatures and are signing a document on the server using a signature created on the client. We are creating Pdf Objects in memory, and want to switch to a system where we do not need to depend on system memory. Currently, I am saving the PdfSignatureAppearance Object created while generating hash in session,and then using this object from session when I receive a response from client (Signed Hash Content). Could you please help me figure out a way through which I do not need to save the PdfSignatureAppearance object in session and can directly use the Temp File for signing?
First, we generate a hash of file after inserting signature appearance as shown in the code below:
File file = new File("To be signed file location")
char version = '\u0000'
ByteArrayOutputStream out = new ByteArrayOutputStream()
String outputFile = "Signed file name"
FileOutputStream fileOutputStream = new FileOutputStream(outputFile)
PdfReader pdfReader = new PdfReader(new FileInputStream(file.absolutePath))
PdfStamper stamper = new PdfStamper(pdfReader, out, version, true)
PdfFormField pdfFormField = PdfFormField.createSignature(stamper.getWriter())
String signatureName = "Signature1"
pdfFormField.setWidget(new Rectangle((float) 20, (float) 20, (float) 100, (float) 60), (PdfName) null)
pdfFormField.setFlags(4)
pdfFormField.put(PdfName.DA, new PdfString("/Helv 0 Tf 0 g"))
pdfFormField.setFieldName(signatureName)
pdfFormField.setPage(1)
stamper.addAnnotation(pdfFormField, i)
stamper.close()
pdfReader = new PdfReader(out.toByteArray())
stamper = PdfStamper.createSignature(pdfReader, fileOutputStream, version, (File) null, true)
PdfSignatureAppearance appearance = stamper.getSignatureAppearance()
appearance.setLayer2Text("Digitally Signed by Name")
appearance.setImage(Image.getInstance(esignRequestCO.logoLocation))
appearance.setAcro6Layers(true)
Calendar cal = Calendar.getInstance()
cal.setTime(new Date())
cal.add(12, 5)
appearance.setSignDate(cal)
appearance.setVisibleSignature(signatureName)
int contentEstimated = 16384
HashMap<PdfName, Integer> exc = new HashMap()
exc.put(PdfName.CONTENTS, contentEstimated * 2 + 2)
PdfSignature dic = new PdfSignature(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED)
dic.setReason(appearance.getReason())
dic.setLocation(appearance.getLocation())
dic.setDate(new PdfDate(appearance.getSignDate()))
appearance.setCryptoDictionary(dic)
appearance.preClose(exc)
InputStream inp = appearance.getRangeStream()
byte[] bytes = IOUtils.toByteArray(inp)
String hash = DigestUtils.sha256Hex(bytes)
As soon as we get the signed content, we insert the content in the file using same appearance object as shown below:
int contentEstimated = 16384
PdfSignatureAppearance appearance = "PdfSignatureAppearance object from session generated in previous step"
byte[] p7barray = "signed content here".bytes
byte[] paddedSig = new byte[contentEstimated]
System.arraycopy(p7barray, 0, paddedSig, 0, p7barray.length)
PdfDictionary dic2 = new PdfDictionary()
dic2.put(PdfName.CONTENTS, (new PdfString(paddedSig)).setHexWriting(true))
appearance.close(dic2)

docx with track change producing incorrect output in Apache Tika

I am parsing docx files using apache tika.
AutoDetectParser parser = new AutoDetectParser();
ContentHandler contentHandler = new BodyContentHandler();
inputStream = new BufferedInputStream(new FileInputStream(inputFileName));
Metadata metadata = new Metadata();
OfficeParserConfig officeParserConfig = new OfficeParserConfig();
officeParserConfig.setIncludeDeletedContent(false);
parseContext.set(OfficeParserConfig.class, officeParserConfig);
parser.parse(inputStream, contentHandler, metadata, parseContext);
System.out.println(contentHandler.toString());
When I am sending track_revised docx file it's adding all the text deleted with the actual text and inserted text. Is there a way to tell parser to exclude the deleted text?
I did figure it out
AutoDetectParser parser = new AutoDetectParser();
ContentHandler contentHandler = new BodyContentHandler();
inputStream = new BufferedInputStream(new FileInputStream(inputFileName));
Metadata metadata = new Metadata();
ParseContext parseContext = new ParseContext();
OfficeParserConfig officeParserConfig = new OfficeParserConfig();
officeParserConfig.setUseSAXDocxExtractor(true);
officeParserConfig.setIncludeDeletedContent(false);
parseContext.set(OfficeParserConfig.class, officeParserConfig);
parser.parse(inputStream, contentHandler, metadata, parseContext);
System.out.println(contentHandler.toString());

iText7: Error at file pointer when merging two pdfs

We are in the last steps of evaluating iText7. We use iText 7.1.0 and html2pdf 2.0.0.
What we do: we send a json_encoded collection with pdf-data (which includes html for header, body and footer) to our Java app. There we iterate over the collection, create a byteArrayOutputStream for each pdf-data element and merge them together. We then send the results to a script which echoes it to e.g. a browser. Although the pdf is displayed correctly, we encounter errors while creating it:
com.itextpdf.io.IOException: Error at file pointer 226,416.
...
Caused by: com.itextpdf.io.IOException: xref subsection not found.
... 73 common frames omitted
If we create only one part of the collection, no error is thrown.
Iterate over collection and merge:
#RequestMapping(value = "/pdf", method = RequestMethod.POST, produces = MediaType.APPLICATION_PDF_VALUE)
public byte[] index(#RequestBody PDFDataModelCollection elements, Model model) throws IOException {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
try (PdfDocument resultDoc = new PdfDocument(writer)) {
for (PDFDataModel pdfDataModel : elements.getElements()) {
PdfReader reader = new PdfReader(new ByteArrayInputStream(creationService.createDatasheet(pdfDataModel)));
try (PdfDocument sourceDoc = new PdfDocument(reader)) {
int n = sourceDoc.getNumberOfPages(); //<-- IOException on second iteration
for (int i = 1; i <= n; i++) {
PdfPage page = sourceDoc.getPage(i).copyTo(resultDoc);
resultDoc.addPage(page);
}
}
}
}
return byteArrayOutputStream.toByteArray(); //outputs the final pdf
}
Creation of part:
public byte[] createDatasheet(PDFDataModel pdfDataModel) throws IOException {
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
//Initialize PDF document
PdfDocument pdfDoc = new PdfDocument(writer);
try (
Document document = new Document(pdfDoc)
) {
//header, footer, etc
//body
for (IElement element : HtmlConverter.convertToElements(pdfDataModel.getBody(), this.props)) {
document.add((IBlockElement) element);
}
footer.writeTotalNumberOnPages(pdfDoc);
}
return byteArrayOutputStream.toByteArray();
}
We are grateful for any suggestion.
In createDatasheet you appear to re-use some byteArrayOutputStream without clearing it first.
In the first iteration, therefore, everything works as desired, at the end of createDatasheet you have a single PDF file in it.
In the second iteration, though, you have two PDF files in that byteArrayOutputStream, one after the other. This concatenation does not form a valid single PDF.
Thus, byteArrayOutputStream.toByteArray() returns something broken.
To fix this, either make the byteArrayOutputStream local to createDatasheet and create a new instance every time or alternatively reset byteArrayOutputStream at the start of createDatasheet:
public byte[] createDatasheet(PDFDataModel pdfDataModel) throws IOException {
byteArrayOutputStream.reset();
PdfWriter writer = new PdfWriter(byteArrayOutputStream);
[...]

Streaming OpenXML result

By using OpenXML to manipulating a Word document (as a template), the server application saves the new content as a temporary file and then sends it to user to download.
The question is how to make these content ready to download without saving it on the server as a temporary file? Is it possible to save OpenXML result as a byte[] or Stream instead of saving it as a file?
Using this page:
OpenXML file download without temporary file
I changed my code to this one:
byte[] result = null;
byte[] templateBytes = System.IO.File.ReadAllBytes(wordTemplate);
using (MemoryStream templateStream = new MemoryStream())
{
templateStream.Write(templateBytes, 0, (int)templateBytes.Length);
using (WordprocessingDocument doc = WordprocessingDocument.Open(templateStream, true))
{
MainDocumentPart mainPart = doc.MainDocumentPart;
...
mainPart.Document.Save();
templateStream.Position = 0;
using (MemoryStream memoryStream = new MemoryStream())
{
templateStream.CopyTo(memoryStream);
result = memoryStream.ToArray();
}
}
}
You can create the WordprocessingDocument and then use the Save() method to save it to a Stream.
http://msdn.microsoft.com/en-us/library/cc882497
var memoryStream = new MemoryStream();
document.Clone(memoryStream);

SQL FileStream Opening XPS FIle

I am trying to read an XPS file that I have inserted into my database using the Filestream attribute. Here is my code thus far.
RewardsDataContext dx = new RewardsDataContext();
var img = (from c in dx.RwProductsTests
select c).FirstOrDefault();
byte[] buffer = img.Blob.ToArray();
MemoryStream ms = new MemoryStream();
ms.Write(buffer, 0, buffer.Length);
ms.Position = 0;
Package package = Package.Open(ms, FileMode.OpenOrCreate, FileAccess.ReadWrite);
XpsDocument MyDoc = new XpsDocument(package);
dv1.Document = MyDoc.GetFixedDocumentSequence();
dx.Dispose();
and I get the following error.
XpsDocument URI is null. Use XpsDocument constructor that takes URI parameter.