views:

229

answers:

2

I have got to convert a PDF to a Base64 Encoded and write it to a element in a XML file.
I have got the Base64 Encoded string (very long/big) but the spec im working from says the following:

This has been chosen, to ensure the XML file may be displayed and validated without any potential problems caused by the handling of the raw binary composition of the original JPEG file. The file data should display correctly in an XML compliant browser, such as Internet Explorer. The data must be presented in fixed 76 character rows, each row separated with a line break.
First question is about the bit about the JPEG is that valid if i using pdf?

Secondly not sure how to achive this: The data must be presented in fixed 76 character rows, each row separated with a line break.
How can i achive this with Linq to XML

+1  A: 

This is not a very efficient solution because of the inserts (it would probably be better to build the string by adding 76 characters from the encoded file content, then a new line, then 76 characters, then again a new line, ...) but it is short and demonstrates the general idea. If memory usage and performance is a concern, one could also think about replacing the Convert.ToBase64String() call by code that directly encodes the bytes into the StringBuilder.

public static XElement BuildNode(Byte[] data, XName tagName, Int32 lineLength)
{
    StringBuilder sb = new StringBuilder(Convert.ToBase64String(data));

    Int32 position = 0;

    while (position < sb.Length)
    {
        sb.Insert(position, Environment.NewLine);
        position += lineLength + Environment.NewLine.Length;
    }

    sb.AppendLine();

    return new XElement(tagName, sb.ToString());
}

For example

String text = "I have got to convert a PDF to a Base64 Encoded " +
              "and write it to a element in a XML file.";

Byte[] data = Encoding.UTF8.GetBytes(text);

StringBuilder sb = new StringBuilder();
TextWriter tw = new StringWriter(sb);

using (var writer = new XmlTextWriter(tw) { Formatting = Formatting.Indented })
{
    XDocument document = new XDocument(BuildNode(data, "Content", 40));

    document.Save(writer);
}

Console.WriteLine(sb.ToString());

prints the following.

<?xml version="1.0" encoding="utf-16"?>
<Content>
SSBoYXZlIGdvdCB0byBjb252ZXJ0IGEgUERGIHRv
IGEgQmFzZTY0IEVuY29kZWQgYW5kIHdyaXRlIGl0
IHRvIGEgZWxlbWVudCBpbiBhIFhNTCBmaWxlLg==
</Content>
Daniel Brückner
+2  A: 
Convert.ToBase64String(pdfBytes, Base64FormattingOptions.InsertLineBreaks);
SLaks