I am using a third party API to send documents from a .NET C# application. The documents need to be base64 encoded string of a valid file format (.doc or .pdf or .jpg). The issue I’m having is that I want to send some additional data to this endpoint that is just a string e.g. “message”. I also don’t want to create any files in the directory.
So the approach I’m thinking of is:
- Create a file that doesn’t get saved to disk and is a specific file format like pdf
- Add text content to this file
- Encode the whole file to a base64 string
I don’t want to save the file anywhere, I just need to somehow create a file with the text content so I can encode it to base64.
But I’m unsure how to do this.
I’m pretty lost and would appreciate any help, guidance or opinions. Please correct me if I’m approaching this problem in the wrong way!
I’ve looked in MemoryMappedFiles and different libraries like PdfSharp but I was hoping to do this without adding another external dependency to the application. I tried programmatically creating a PDF file with the text content and then encoding that to a base64 string, but when I tried decoding the base64, the file I would get an error “Failed to load PDF document.”
E.g.
var text = "message";
var textBytes = Encoding.UTF8.GetBytes(text);
// Define PDF file header and footer
const string pdfHeader = "%PDF-1.4n";
const string pdfFooter = "%%EOF";
// Define PDF content with text
var pdfContent = $"{pdfHeader}1 0 obj << /Length {textBytes.Length} >> streamn{text}nendstreamnendobjn{pdfFooter}";
// Convert the PDF text to a byte array
var pdfBytes = Encoding.ASCII.GetBytes(pdfContent);
return Convert.ToBase64String(pdfBytes);
howdy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.