|
using System.Net; |
|
using System.Net.Http; |
|
using System.Net.Http.Headers; |
|
using System.Threading.Tasks; |
|
using DinkToPdf; |
|
using Microsoft.AspNetCore.Http; |
|
using Microsoft.Azure.WebJobs; |
|
using Microsoft.Azure.WebJobs.Extensions.Http; |
|
using Microsoft.Extensions.Logging; |
|
using IPdfConverter = DinkToPdf.Contracts.IConverter; |
|
|
|
namespace ExportFunctionApp |
|
{ |
|
public static class ExportPdf |
|
{ |
|
private static readonly IPdfConverter _pdfConverter = new SynchronizedConverter(new PdfTools()); |
|
|
|
[FunctionName("ExportPdf")] |
|
public static async Task<HttpResponseMessage> Run( |
|
[HttpTrigger(AuthorizationLevel.Function, "post")] HttpRequest req, |
|
ILogger log) |
|
{ |
|
log.LogInformation("Processing PDF Request"); |
|
|
|
string html = await req.ReadAsStringAsync(); |
|
|
|
var pdf = BuildPdf(html); |
|
|
|
log.LogInformation($"PDF Generated. Length={pdf.Length}"); |
|
|
|
var res = new HttpResponseMessage(HttpStatusCode.OK) |
|
{ |
|
Content = new ByteArrayContent(pdf) |
|
}; |
|
|
|
res.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf"); |
|
res.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("inline"); |
|
|
|
return res; |
|
} |
|
|
|
private static byte[] BuildPdf(string html) |
|
{ |
|
const double margin = 25; |
|
|
|
return _pdfConverter.Convert(new HtmlToPdfDocument() |
|
{ |
|
GlobalSettings = { |
|
Orientation = Orientation.Portrait, |
|
PaperSize = PaperKind.A4, |
|
Margins = new MarginSettings(margin, margin, margin, margin), |
|
}, |
|
Objects = |
|
{ |
|
new ObjectSettings |
|
{ |
|
WebSettings = new WebSettings |
|
{ |
|
PrintMediaType = true, |
|
EnableIntelligentShrinking = true |
|
}, |
|
HtmlContent = html |
|
} |
|
} |
|
}); |
|
} |
|
} |
|
} |
Thanks for sharing this. For some reason the pdf I get out of this just shows a bunch of solid squares. Any idea why that might be?
This only happens on azure function, azure webjob, or azure website. When i host in a vm (as web api) it works fine.