recently I was trying to save Aspose.Cells.Workbook to stream with
private Stream GetWorkbook()
{
// processing workbook here
// ...
// saving to stream
return workbook.SaveToStream();
}
private void Save()
{
using (stream = GetWorkbook())
using (var fileStream = new FileStream(filePath, FileMode.Create, FileAccess.Write))
{
stream.CopyTo(fileStream);
}
}
But when I'm trying to open generated .xlsx file Excel sends me an error that file is corrupted.
SaveToStream() method will only save your workbook in XLS format. So you should not use this method but use the following code to save your workbook in memory stream object. It should fix your issue.
C#
//Load your Excel file
Workbook wb = new Workbook(yourFile);
//Create memory stream object
MemoryStream ms = new MemoryStream();
//Determine the save format
SaveFormat svfmt = (SaveFormat)wb.FileFormat;
//Save the workbook to memory stream
wb.Save(ms, svfmt);
Note: I am working as Developer Evangelist at Aspose
Related
I am using syncfusion OCR to scan PDFs which produces a document and push it for download as the end result. I am trying to grab the file from the stream and put copy it to my server but i am getting an error saying stream does not support reading. Here is my code
try
{
string binaries = Path.Combine(this._hostingEnvironment.ContentRootPath, "Tesseractbinaries", "Windows");
//Initialize OCR processor with tesseract binaries.
OCRProcessor processor = new OCRProcessor(binaries);
//Set language to the OCR processor.
processor.Settings.Language = Languages.English;
string path = Path.Combine(this._hostingEnvironment.ContentRootPath, #"Data\font", "times.ttf");
FileStream fontStream = new FileStream(path, FileMode.Open);
//Create a true type font to support unicode characters in PDF.
processor.UnicodeFont = new PdfTrueTypeFont(fontStream, 8);
//Set temporary folder to save intermediate files.
processor.Settings.TempFolder = Path.Combine(this._hostingEnvironment.ContentRootPath, "Data");
//Load a PDF document.
FileStream inputDocument = new FileStream(Path.Combine(this._hostingEnvironment.ContentRootPath, "Data", "pistone.pdf"), FileMode.Open);
PdfLoadedDocument loadedDocument = new PdfLoadedDocument(inputDocument);
//Perform OCR with language data.
string tessdataPath = Path.Combine(this._hostingEnvironment.ContentRootPath, "tessdata");
//string tessdataPath = Path.Combine(#"tessdata");
processor.PerformOCR(loadedDocument, tessdataPath);
//Save the PDF document.
MemoryStream outputDocument = new MemoryStream();
loadedDocument.Save(outputDocument);
outputDocument.Position = 0;
//Dispose OCR processor and PDF document.
processor.Dispose();
loadedDocument.Close(true);
//Download the PDF document in the browser.
FileStreamResult fileStreamResult = new FileStreamResult(outputDocument, "application/pdf");
fileStreamResult.FileDownloadName = "OCRed_PDF_document.pdf";
//setting a path for saving it to my server and copying it to the folder downloads
string filePath = Path.Combine("downloads", fileStreamResult.FileDownloadName);
using (Stream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write))
{
fileStream.CopyTo(fileStream);
}
return fileStreamResult;
}
catch (Exception ex)
{
throw;
}
fileStream.CopyTo(fileStream) seems to be attempting to copy a stream to itself.
Try replacing with fileStreamResult.FileStream.CopyTo(fileStream) ?
We can resolve this error by using fileStreamResult.FileStream.CopyTo(fileStream) instead of fileStream.CopyTo(fileStream) in sample level. Please try the below code snippet or sample on your end and let us know the result.
Please find the below modified code snippet,
using (Stream fileStream = new FileStream(filePath, FileMode.Append, FileAccess.Write)){ fileStreamResult.FileStream.CopyTo(fileStream);}
Please refer to the below link for more information,
UG: https://help.syncfusion.com/file-formats/pdf/working-with-ocr/dot-net-core
KB: https://www.syncfusion.com/kb/11696/how-to-perform-ocr-in-asp-net-core-platform
I have a variable which holds a stream of content .
The variable is speicified as shown below ,
Task<Stream> tempStream = ....
Specifically this tempStream variable holds a A pdf stream.
I want to to write this stream into a file . How can I do this in c# ?
the following should work:
path = #"Path\\to\\output";
using (FileStream outputFileStream = new FileStream(path, FileMode.Create))
{
tempStream.CopyTo(outpoutFileStream);
}
I have a System.IO.Packaging.Package in memory (it is a WordprocessingDocument) and want to stream it down to browser to save it. The word document has been modified by the MVC-based application and the resulting file has been modified for the current request.
I understand the package represents a 'zip' file containing a number of parts. These parts include headers, footers and main body document. I've modified each individually and now want to stream the package back to the user.
I can get the individual part streams... package.GetPart(new Uri("/word/document.xml", UriKind.Relative)).GetStream()
However I'm missing how to get an output stream on the entire document (package)- without writing to the file system.
Thanks in advance
No- what I think I need is something like this... I've already read in the template document and made modifications in memory. Now I want to stream a modified document (leaving the template un-touched) back to the user.
MemoryStream stream = new MemoryStream();
WordprocessingDocument docOut =
WordprocessingDocument.Create( stream, WordprocessingDocumentType.Document);
foreach (var part in package.GetParts())
{
using (StreamReader streamReader = new StreamReader(part.GetStream()))
{
PackagePart newPart = docOut.Package.CreatePart(
part.Uri, part.ContentType );
using (StreamWriter streamWriter = new StreamWriter(newPart.GetStream(FileMode.Create)))
{
streamWriter.Write(streamReader.ReadToEnd());
}
}
}
Unfortunately- this produces a 'corrupt' word document...
OpenXmlPackage.Close Method saves all changes in all parts to the underlying store. If you opened the package from a stream, just use that stream:
public Stream packageStream() {
var ms = new MemoryStream();
var wrdPk = WordprocessingDocument.Create(ms, WordprocessingDocumentType.Document);
// Build the package ...
var docPart = wrdPk.AddMainDocumentPart();
docPart.Document = new Document(
new Body(new Paragraph(new Run(new Text("Hello world.")))));
// Flush all changes
wrdPk.Close();
return ms;
}
I'm using StreamWriter to generate a dynamic file and holding it in a MemoryStream. Everything appears to be alright until I go to save the file using rebex sftp.
The example they give on their site works fine:
// upload a text using a MemoryStream
string message = "Hello from Rebex FTP for .NET!";
byte[] data = System.Text.Encoding.Default.GetBytes(message);
System.IO.MemoryStream ms = new System.IO.MemoryStream(data);
client.PutFile(ms, "message.txt");
However the code below does not:
using (var stream = new MemoryStream())
{
using (var writer = new StreamWriter(stream))
{
writer.AutoFlush = true;
writer.Write("test");
}
client.PutFile(stream, "test.txt");
}
The file "test.txt" is saved, however it is empty. Do I need to do more than just enable AutoFlush for this to work?
After writing to the MemoryStream, the stream is positioned at the end. The PutFile method reads from the current position to the end. That's exactly 0 bytes.
You need to position the stream at the beginning before passing it to PutFile:
...
}
stream.Seek(0, SeekOrigin.Begin);
client.PutFile(stream, "test.txt");
You may also need to prevent the StreamWriter from disposing the MemoryStream:
var writer = new StreamWriter(stream);
writer.Write("test");
writer.Flush();
stream.Seek(0, SeekOrigin.Begin);
client.PutFile(stream, "test.txt");
I am trying to create a pdf file with iTextSharp. My attempt writes the content of the pdf to a MemoryStream so I can write the result both into file and a database BLOB. The file gets created, has a size of about 21kB and it looks like a pdf when opend with Notepad++. But my PDF viewer says it's currupted.
Here is a little code snippet (only tries to write to a file, not to a database):
Document myDocument = new Document();
MemoryStream myMemoryStream = new MemoryStream();
PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);
myDocument.Open();
// Content of the pdf gets inserted here
using (FileStream fs = File.Create("D:\\...\\aTestFile.pdf"))
{
myMemoryStream.WriteTo(fs);
}
myMemoryStream.Close();
Where is the mistake I make?
Thank you,
Norbert
I think your problem was that you weren't properly adding content to your PDF. This is done through the Document.Add() method and you finish up by calling Document.Close().
When you call Document.Close() however, your MemoryStream also closes so you won't be able to write it to your FileStream as you have. You can get around this by storing the content of your MemoryStream to a byte array.
The following code snippet works for me:
using (MemoryStream myMemoryStream = new MemoryStream()) {
Document myDocument = new Document();
PdfWriter myPDFWriter = PdfWriter.GetInstance(myDocument, myMemoryStream);
myDocument.Open();
// Add to content to your PDF here...
myDocument.Add(new Paragraph("I hope this works for you."));
// We're done adding stuff to our PDF.
myDocument.Close();
byte[] content = myMemoryStream.ToArray();
// Write out PDF from memory stream.
using (FileStream fs = File.Create("aTestFile.pdf")) {
fs.Write(content, 0, (int)content.Length);
}
}
I had similar issue. My file gets downloaded but the file size will be 13Bytes. I resolved the issue when I used binary writer to write my file
byte[] bytes = new byte[0];
//pass in your API response into the bytes initialized
using (StreamWriter streamWriter = new StreamWriter(FilePath, true))
{
BinaryWriter binaryWriter = new BinaryWriter(streamWriter.BaseStream);
binaryWriter.Write(bytes);
}
Just some thoughts - what happens if you replace the memory stream with a file stream? Does this give you the result you need? This will at least tell you where the problem could be.
If this does work, how do the files differ (in size and binary representation)?
Just a guess, but have you tried seeking to the beginning of the memory stream before writing?
myMemoryStream.Seek(0, SeekOrigin.Begin);
Try double checking your code that manipulates the PDF with iText. Make sure you're calling the appropriate EndText method of any PdfContentByte objects, and make sure you call myDocument.Close() before writing the file to disk. Those are things I've had problems with in the past when generating PDFs with iTextSharp.
documentobject.Close();
using (FileStream fs = System.IO.File.Create(path)){
Memorystreamobject.WriteTo(fs);
}