Convert in-memory pdf to byte[]
I'm writing a websercive in C# that will generate pdf-files and send back to the caller as a byte[]. The pdf file is generated using a third party component, but I'm struggling with the conversion. The pdf is just an in-memory object in the web service, and I can't find any good way of converting the generated pdf to a byte[] before returning it to the caller. Any advice on this?
Edited for clarification:
I'm working with a pdf in-memory object (Aspose.pdf Pdf-object to be precise) which is constructed in the webservice using the data sent in to the web service. It is never saved by the webservice, the caller should convert the byte[] back to a pdf-file and save it 开发者_C百科on their end.
If the PDF library allows to save to a stream, you can stream it to a MemoryStream
- from this you can get your byte[]
by calling GetBuffer
.
You can apparently Save() the document to a stream object:
http://www.aspose.com/documentation/.net-components/aspose.pdf-for-.net/aspose.pdf.pdf.save_overload_3.html
You could probably create a MemoryStream object and send that to the Save() method to fetch the binary data.
I remember doing something similar with Aspose.pdf a while back. Here's some POC code I wrote that opens a PDF page and steams it back. Hope it helps..
public ActionResult Index(int pageNumber)
{
ActionResult result = null;
var path = Server.MapPath("~/Content/BigPdf.pdf");
if (pageNumber == 0)
{
result = new FilePathResult(path, "application/pdf");
}
else
{
string inFile = path;
string outFile = ".\\ExtractStream.pdf";
//Creating stream objects holding the PDF files in Open Mode
var inStream = new FileStream(inFile, FileMode.Open);
//Creating output stream object that will store the extracted pages as a PDF file
var outputStream = new MemoryStream();
//Instantiating PdfFileEditor object
var editor = new PdfFileEditor();
//Creating an array of integers having numbers of the pages to be extracted from PDF file
var pages = new int[] { pageNumber };
//Calling Extract method
editor.Extract(inStream, pages, outputStream);
inStream.Close();
//Closing output stream
outputStream.Seek(0, SeekOrigin.Begin);//rewind stream
var converter = new PdfConverter();
converter.BindPdf(outputStream);
converter.DoConvert();
var imageStream = new MemoryStream();
while (converter.HasNextImage())
{
converter.GetNextImage(imageStream, ImageFormat.Jpeg );
}
imageStream.Seek(0, SeekOrigin.Begin);//rewind stream
result = new FileStreamResult(imageStream, "image/Jpeg");
}
return result;
}
精彩评论