I have been working on creating PDFs to upload to Concur Invoices. SOMETIMES the PDF will not upload because of some “unknown” error. Not helpful I know. If we open Acrobat and resave the file then it will upload fine using the Concur UI anyway. Here is the code I am using:
private async Task<ResultsReturn> PrepAttachment(string concurRequestId, string attachmentUri, string masterFileName, int attachmentNbr)
{
Uri uri = new Uri(attachmentUri);
PdfHelper.DownloadAndConvertToPdfAsync(uri, masterFileName);
Console.WriteLine("Saved as: " + masterFileName);
ResultsReturn results = new ResultsReturn();
results.Success = true;
return results;
}
public static class PdfHelper
{
public static async Task<(MemoryStream Stream, string ContentType)> DownloadToStreamAsync(Uri fileUri)
{
if (fileUri == null)
throw new ArgumentNullException(nameof(fileUri));
using (var httpClient = new HttpClient())
{
var response = await httpClient.GetAsync(fileUri);
response.EnsureSuccessStatusCode();
var contentType = response.Content.Headers.ContentType?.MediaType ?? "application/octet-stream";
var memoryStream = new MemoryStream();
await response.Content.CopyToAsync(memoryStream);
memoryStream.Position = 0;
return (memoryStream, contentType);
}
}
public static void ConvertStreamToPdf(Stream inputStream, string contentType, string outputPdfPath)
{
if (inputStream == null)
throw new ArgumentNullException(nameof(inputStream));
if (string.IsNullOrWhiteSpace(outputPdfPath))
throw new ArgumentNullException(nameof(outputPdfPath));
contentType = contentType.ToLowerInvariant();
if (contentType.Contains("pdf"))
{
// Already a PDF, just save as-is
using (var fileStream = File.Create(outputPdfPath))
{
inputStream.CopyTo(fileStream);
}
}
else if (contentType.Contains("html"))
{
using (var doc = new Document(inputStream, new HtmlLoadOptions()))
{
doc.Save(outputPdfPath, SaveFormat.Pdf);
}
}
else if (contentType.Contains("text") || contentType.Contains("plain"))
{
using (var doc = new Document())
{
var page = doc.Pages.Add();
using (var reader = new StreamReader(inputStream))
{
var text = reader.ReadToEnd();
var textFragment = new Aspose.Pdf.Text.TextFragment(text);
page.Paragraphs.Add(textFragment);
}
doc.Save(outputPdfPath);
}
}
else if (contentType.Contains("image"))
{
var imageDoc = new Document();
var page = imageDoc.Pages.Add();
var imageStream = new MemoryStream();
inputStream.CopyTo(imageStream);
imageStream.Position = 0;
var image = new Aspose.Pdf.Image { ImageStream = imageStream };
page.Paragraphs.Add(image);
imageDoc.Save(outputPdfPath);
}
else
{
throw new NotSupportedException($"Unsupported content type: {contentType}");
}
}
public static async Task DownloadAndConvertToPdfAsync(Uri fileUri, string outputPdfPath)
{
var (stream, contentType) = DownloadToStreamAsync(fileUri).GetAwaiter().GetResult();
ConvertStreamToPdf(stream, contentType, outputPdfPath);
}
}