将PDF转换为byte[]后再保存

5

我正在使用PDFSharp,并从位图图像创建pdf。我可以保存并查看图像作为pdf,没有问题。但现在我想做的是,在将pdf保存为实际文件之前,将其转换为byte[]。我可以在保存后将其保存为byte[]。我将有两种不同的方法,一种将pdf保存到用户可以打开它的文件中,另一种将pdf保存为将发送到数据库的字节,但我可能不会同时执行两种方法。也许有一天我需要将文件保存为一个文件,而另一天则将其保存为byte而不需要将其保存为文件。我目前的代码:

    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

     }

希望我说的有意义,如果需要可以进一步解释


如果我这样做可以吗?那么我该如何将建议的字节流转换回可视化的PDF呢?我看到的每个示例都使用了接受文件路径的WriteAllBytes()方法。 - user3825831
2个回答

12

您可以使用MemoryStream来实现此目的:

byte[] pdfData;
using (var ms = new MemoryStream()) {
    document.Save(ms);
    pdfData = ms.ToArray();
}

谢谢,你第一个回答,所以我给了你信用,并且我找到了如何将字节转换回PDF的方法。 - user3825831

1
尝试使用MemoryStream:
using(var ms = new MemoryStream()){
  document.Save(ms);
  byte[] bytes = ms.ToArray();
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接