Novice Developer
Novice Developer

Reputation: 4759

convert base64Binary to pdf

I have raw data of base64Binary.

string base64BinaryStr = "J9JbWFnZ......"

How can I make pdf file? I know it need some conversion. Please help me.

Upvotes: 29

Views: 128745

Answers (6)

Ralf de Kleine
Ralf de Kleine

Reputation: 11756

using (System.IO.FileStream stream = System.IO.File.Create("c:\\temp\\file.pdf"))
{
    System.Byte[] byteArray = System.Convert.FromBase64String(base64BinaryStr);
    stream.Write(byteArray, 0, byteArray.Length);
}

Upvotes: 31

Synap Sen
Synap Sen

Reputation: 61

This code does not write any file on the hard drive.

Response.AddHeader("Content-Type", "application/pdf");
Response.AddHeader("Content-Length", base64Result.Length.ToString());
Response.AddHeader("Content-Disposition", "inline;");
Response.AddHeader("Cache-Control", "private, max-age=0, must-revalidate");
Response.AddHeader("Pragma", "public");
Response.BinaryWrite(Convert.FromBase64String(base64Result));

Note: the variable base64Result contains the Base64-String: "JVBERi0xLjMgCiXi48/TIAoxI..."

Upvotes: 6

dush88c
dush88c

Reputation: 2116

First convert the Bas64 string to byte[] and write it into a file.

byte[] bytes = Convert.FromBase64String(base64BinaryStr); 
File.WriteAllBytes(@"FolderPath\pdfFileName.pdf", bytes );

Upvotes: 8

BinaryTank
BinaryTank

Reputation: 49

base64BinaryStr - from webservice SOAP message

byte[] bytes = Convert.FromBase64String(base64BinaryStr); 

Upvotes: 4

MusiGenesis
MusiGenesis

Reputation: 75386

Step 1 is converting from your base64 string to a byte array:

byte[] bytes = Convert.FromBase64String(base64BinaryStr);

Step 2 is saving the byte array to disk:

System.IO.FileStream stream = 
    new FileStream(@"C:\file.pdf", FileMode.CreateNew);
System.IO.BinaryWriter writer = 
    new BinaryWriter(stream);
writer.Write(bytes, 0, bytes.Length);
writer.Close();

Upvotes: 52

Mike Clark
Mike Clark

Reputation: 11979

All you need to do is run it through any Base64 decoder which will take your data as a string and pass back an array of bytes. Then, simply write that file out with pdf in the file name. Or, if you are streaming this back to a browser, simple write the bytes to the output stream, marking the appropriate mime-type in the headers.

Most languages either have built in methods for converted to/from Base64. Or a simple Google with your specific language will return numerous implementations you can use. The process of going back and forth to Base64 is pretty straightforward and can be implemented by even novice developers.

Upvotes: 5

Related Questions