Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
520 views
in Technique[技术] by (71.8m points)

c# - PDFsharp save to MemoryStream

I want to save a PdfSharp.Pdf.PdfDocument by its Save method to a Stream, but it doesn't attach the PDF header settings to it. So when I read back the Stream and return it to the user, he see that the PDF file is invalid. Is there a solution to attach the PDF header settings when PDFsharp saves to memory?

question from:https://stackoverflow.com/questions/1073277/pdfsharp-save-to-memorystream

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

If you think there is an issue with PdfDocument.Save, then please report this on the PDFsharp forum (but please be more specific with your error description). Your "solution" looks like a hack to me. "pdfRenderer.Save" calls "PdfDocument.Save" internally. Whatever the problem is - your "solution" still calls the same Save routine.

Edit: To get a byte[] containing a PDF file, you only have to call:

MemoryStream stream = new MemoryStream();
document.Save(stream, false);
byte[] bytes = stream.ToArray();

Early versions of PDFsharp do not reset the stream position.

So you have to call

ms.Seek(0, SeekOrigin.Begin); 

to reset the stream position before reading from the stream; this is no longer required for current versions.

Using ToArray can often be used instead of reading from the stream.

Edit 2: instead of stream.ToArray() it may be more efficient to use stream.GetBuffer(), but this buffer is usually larger than the PDF file and you only have to use stream.Length bytes from that buffer. Very useful for method that take a byte[] along with a length parameter.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...