【问题标题】:How to convert PDF Base64 into pdf then PDF into an image in C#如何将 PDF Base64 转换为 pdf 然后 PDF 转换为 C# 中的图像
【发布时间】:2020-06-28 04:54:17
【问题描述】:

以下是添加的代码: 图像对象位于library.imaging 中。

"using System.Drawing;"
"using System.Drawing.Imaging;"
{
  byte[] b = Convert.FromBase64String("R0lGODlhAQABAIAAA");
  Image image;
  using (MemoryStream memstr = new MemoryStream(b))
  {
    image = Image.FromStream(memstr);
  }
}

这是我正在处理的新代码:

{
  string base64BinaryStr = " ";
  byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
  string FileName = (@"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));

  BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));            
  writer.Write(PDFDecoded);
  string s = Encoding.UTF8.GetString(PDFDecoded);
}   

【问题讨论】:

  • 分解您的问题。这是你想要实现的两件不同的事情,其中​​一件几乎肯定与你所坚持的事情无关。这个问题和你的 date-conversion 标签有什么关系?
  • 是的,第一步将 BAse64 转为 pdf,然后将相同的 pdf 转为图像
  • 好的,你坚持哪一部分?
  • MemoryStream,在内存中,它永远不会被保存到文件中。尽管如此,将 pdf 转换为图像将使用库
  • 它现在可以工作了,谢谢@John

标签: c# pdf file-conversion


【解决方案1】:

这是你当前的代码:

byte[] PDFDecoded = Convert.FromBase64String(base64BinaryStr);
string FileName = (@"C:\Users\Downloads\PDF " + DateTime.Now.ToString("dd-MM-yyyy-hh-mm"));

BinaryWriter writer = new BinaryWriter(File.Create(FileName + ".pdf"));            
writer.Write(PDFDecoded);

您实际上不需要BinaryWriterFile.Create 已经给你一个FileStream

FileStream writer = File.Create(FileName + ".pdf");
writer.Write(PDFDecoded, 0, PDFDecoded.Length);

但这仍然会有您遇到的问题,因为您没有将数据刷新到它。我们还需要关闭文件。值得庆幸的是,我们可以将它包装在 using 中,它对我们来说都可以:

using (FileStream writer = File.Create(FileName + ".pdf"))
{
    writer.Write(PDFDecoded, 0, PDFDecoded.Length); 
}

但更简单的方法是:

File.WriteAllBytes(FileName + ".pdf", PDFDecoded);

至于 PDF -> Image,您可能需要查看是否有可用的库(搜索“PDF to Image NuGet”)可以帮助您解决此问题,因为我认为没有构建任何东西-在。

【讨论】:

  • @Zoraiz 如果我解决了你的问题,你能接受我的回答吗?
【解决方案2】:

只是一个想法,您不需要创建物理 PDF 文件,您可以将其保存在内存中并从那里将其转换为图像。

现在的问题是你不能使用System.Drawing.Imaging中的Image来做这个,它不支持阅读PDF文件。

相反,您需要搜索一些可以做到这一点的库。
比如试试GemBox.Pdf,可以这样使用:

string base64String = "...";
byte[] pdfBytes = Convert.FromBase64String(base64String);

using (PdfDocument pdfDocument = PdfDocument.Load(new MemoryStream(pdfBytes)))
{
    ImageSaveOptions imageOptions = new ImageSaveOptions(ImageSaveFormat.Png);

    string imageName = DateTime.Now.ToString("dd-MM-yyyy-hh-mm") + ".png";
    pdfDocument.Save(@"C:\Users\Downloads\" + imageName, imageOptions);
}

我使用了Convert 示例中提供的代码。

【讨论】:

  • 我还需要 Pdf 文件@hertzogth
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多