将Base64编码的字符串转换为PDF

时间:2018-09-12 07:07:35

标签: c# asp.net-mvc utf-8

我有代表要转换为PDF文件的PDF文件的Base64字符串,并使用C#中的默认PDF阅读器或浏览器打开。

我只写了Base64字符串的一部分,因为它太长了,无法在此处粘贴。

public void DownloadPDF()
{
    string pdflocation = "E:\\";
    string fileName = "softcore.pdf";
    // This is only part of Base64 string
    var base64String = "JVBERi0xLjQKJdP0zOEKMSAwIue704O58dOXPgst+hmQ+laj/"; 
    int mod4 = base64String.Length % 4;
    if (mod4 > 0)
    {
        base64String += new string('=', 4 - mod4);
    }
    byte[] data = Convert.FromBase64String(base64String);        

    if (Directory.Exists(pdflocation))
    {
        pdflocation = pdflocation + fileName;
        using (MemoryStream Writer = new System.IO.MemoryStream())
        {
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "attachment; filename=" + fileName);
            Response.AddHeader("content-length", data.Length.ToString());
            Writer.WriteTo(Response.OutputStream);
            Response.Flush();
            Response.End();
            //Writer.Write(data, 0, data.Length);
        }                
    }
}

我面临的问题是它显示为pdf生成,但最后却显示网络错误。

来自输入的编码Base64字符串的解码字符串: enter image description here

1 个答案:

答案 0 :(得分:1)

如果将PDF从某些在线平台(例如 freeformatter.com/base64-encoder.html )转换为base 64并在以下代码中使用该base 64字符串,则此代码可以正常工作:

                 string pdflocation = "D:\\";
                  string fileName = "softcore.pdf";

                  // put your base64 string converted from online platform here instead of V
                  var base64String = V;

                  int mod4 = base64String.Length % 4;

                  // as of my research this mod4 will be greater than 0 if the base 64 string is corrupted
                  if (mod4 > 0)
                  {
                        base64String += new string('=', 4 - mod4);
                  }
                  pdflocation = pdflocation + fileName;

                  byte[] data = Convert.FromBase64String(base64String);

                  using (FileStream stream = System.IO.File.Create(pdflocation))
                  {
                        stream.Write(data, 0, data.Length);
                  }

这应将PDF文件保存在D:\\中,同样问题出在以base 64编码的字符串中

希望这会有所帮助。