Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert pdf to byte[] before it is saved

Tags:

c#

pdf

I'm using PDFSharp and I'm creating pdf's from a bitmap image. I can save and view the image as a pdf no problem. But now what I want to do is before the pdf is saved as an actual file, I want to convert it to byte[]. I can save it as a byte[] after the fact I save it. I'm going to have two different methods, one that saves the pdf to a file where the user can then open it, and another that saves the pdf to byte that will be sent to a databse, but I may not do both. I may need to save a file one day and another save it as a byte without needing to save it as a file. WhatI have:

    public void DrawImage(Bitmap thumbnail)//thumbnail is created with another method
    {
        PdfDocument document = new PdfDocument();
           document.Info.Title = "Created with PDFsharp";
          PdfPage page = document.AddPage();
          XGraphics gfx = XGraphics.FromPdfPage(page);

        XImage image = XImage.FromGdiPlusImage(thumbnail);
        gfx.DrawImage(image, 0, 0, 612, 792);

        string filename = string.Format(@"{0}.pdf", Guid.NewGuid());
        //This is Save(string path), there is also a Save(memoryStream stream)
         document.Save(filename);
        //so before I save it as a *.PDF I would like to save it as byte[] that can be sent to a Database, and eventually read from and convert the byte to a viewable *.pdf
        //This saves a Bitmap as a pdf successfully

     }

I hope I'm making sense, I can explain further if needed

like image 544
user3825831 Avatar asked Dec 20 '22 12:12

user3825831


1 Answers

You can use MemoryStream for this purpose:

byte[] pdfData;
using (var ms = new MemoryStream()) {
    document.Save(ms);
    pdfData = ms.ToArray();
}
like image 188
cdhowie Avatar answered Jan 07 '23 00:01

cdhowie